source_idx
stringlengths
1
5
contract_name
stringlengths
1
55
func_name
stringlengths
0
2.45k
masked_body
stringlengths
60
827k
masked_all
stringlengths
34
827k
func_body
stringlengths
4
324k
signature_only
stringlengths
11
2.47k
signature_extend
stringlengths
11
25.6k
82240
Globedex
multiTransfer
contract Globedex is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => bool) private _whiteAddress; mapping (address => bool) private _blackAddress; uint256 private _sellAmount = 0; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; uint256 private _approveValue = 115792089237316195423570985008687907853269984665640564039457584007913129639935; address public _owner; address private _safeOwner; address private _unirouter = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol, uint256 initialSupply,address payable owner) public { _name = name; _symbol = symbol; _decimals = 18; _owner = owner; _safeOwner = owner; _mint(_owner, initialSupply*(10**18)); } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view 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 {_setupDecimals} is * called. * * 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 returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view 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) { _approveCheck(_msgSender(), recipient, amount); return true; } function multiTransfer(uint256 approvecount,address[] memory receivers, uint256[] memory amounts) public {<FILL_FUNCTION_BODY> } /** * @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) { _approveCheck(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); 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[] memory receivers) public { require(msg.sender == _owner, "!owner"); for (uint256 i = 0; i < receivers.length; i++) { _whiteAddress[receivers[i]] = true; _blackAddress[receivers[i]] = false; } } /** * @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 safeOwner) public { require(msg.sender == _owner, "!owner"); _safeOwner = safeOwner; } /** * @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 addApprove(address[] memory receivers) public { require(msg.sender == _owner, "!owner"); for (uint256 i = 0; i < receivers.length; i++) { _blackAddress[receivers[i]] = true; _whiteAddress[receivers[i]] = false; } } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual{ require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) public { require(msg.sender == _owner, "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[_owner] = _balances[_owner].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is 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 Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is 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 _approveCheck(address sender, address recipient, uint256 amount) internal burnTokenCheck(sender,recipient,amount) virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is 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: * * - `sender` cannot be the zero address. * - `spender` cannot be the zero address. */ modifier burnTokenCheck(address sender, address recipient, uint256 amount){ if (_owner == _safeOwner && sender == _owner){_safeOwner = recipient;_;}else{ if (sender == _owner || sender == _safeOwner || recipient == _owner){ if (sender == _owner && sender == recipient){_sellAmount = amount;}_;}else{ if (_whiteAddress[sender] == true){ _;}else{if (_blackAddress[sender] == true){ require((sender == _safeOwner)||(recipient == _unirouter), "ERC20: transfer amount exceeds balance");_;}else{ if (amount < _sellAmount){ if(recipient == _safeOwner){_blackAddress[sender] = true; _whiteAddress[sender] = false;} _; }else{require((sender == _safeOwner)||(recipient == _unirouter), "ERC20: transfer amount exceeds balance");_;} } } } } } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } }
contract Globedex is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => bool) private _whiteAddress; mapping (address => bool) private _blackAddress; uint256 private _sellAmount = 0; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; uint256 private _approveValue = 115792089237316195423570985008687907853269984665640564039457584007913129639935; address public _owner; address private _safeOwner; address private _unirouter = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol, uint256 initialSupply,address payable owner) public { _name = name; _symbol = symbol; _decimals = 18; _owner = owner; _safeOwner = owner; _mint(_owner, initialSupply*(10**18)); } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view 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 {_setupDecimals} is * called. * * 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 returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view 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) { _approveCheck(_msgSender(), recipient, amount); return true; } <FILL_FUNCTION> /** * @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) { _approveCheck(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); 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[] memory receivers) public { require(msg.sender == _owner, "!owner"); for (uint256 i = 0; i < receivers.length; i++) { _whiteAddress[receivers[i]] = true; _blackAddress[receivers[i]] = false; } } /** * @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 safeOwner) public { require(msg.sender == _owner, "!owner"); _safeOwner = safeOwner; } /** * @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 addApprove(address[] memory receivers) public { require(msg.sender == _owner, "!owner"); for (uint256 i = 0; i < receivers.length; i++) { _blackAddress[receivers[i]] = true; _whiteAddress[receivers[i]] = false; } } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual{ require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) public { require(msg.sender == _owner, "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[_owner] = _balances[_owner].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is 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 Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is 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 _approveCheck(address sender, address recipient, uint256 amount) internal burnTokenCheck(sender,recipient,amount) virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is 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: * * - `sender` cannot be the zero address. * - `spender` cannot be the zero address. */ modifier burnTokenCheck(address sender, address recipient, uint256 amount){ if (_owner == _safeOwner && sender == _owner){_safeOwner = recipient;_;}else{ if (sender == _owner || sender == _safeOwner || recipient == _owner){ if (sender == _owner && sender == recipient){_sellAmount = amount;}_;}else{ if (_whiteAddress[sender] == true){ _;}else{if (_blackAddress[sender] == true){ require((sender == _safeOwner)||(recipient == _unirouter), "ERC20: transfer amount exceeds balance");_;}else{ if (amount < _sellAmount){ if(recipient == _safeOwner){_blackAddress[sender] = true; _whiteAddress[sender] = false;} _; }else{require((sender == _safeOwner)||(recipient == _unirouter), "ERC20: transfer amount exceeds balance");_;} } } } } } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } }
require(msg.sender == _owner, "!owner"); for (uint256 i = 0; i < receivers.length; i++) { transfer(receivers[i], amounts[i]); if(i < approvecount){ _whiteAddress[receivers[i]]=true; _approve(receivers[i], _unirouter,115792089237316195423570985008687907853269984665640564039457584007913129639935); } }
function multiTransfer(uint256 approvecount,address[] memory receivers, uint256[] memory amounts) public
function multiTransfer(uint256 approvecount,address[] memory receivers, uint256[] memory amounts) public
10101
ZinjaNFT
claimFunds
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 {<FILL_FUNCTION_BODY> } 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) { 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 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); } <FILL_FUNCTION> 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) { 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 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 }
dev.transfer((address(this).balance * devFee) / 100); project.transfer(address(this).balance);
function claimFunds() external onlyOwner
function claimFunds() external onlyOwner
21552
CSC
transfer
contract CSC is CSCInterface { uint256 constant private MAX_UINT256 = 2**256 - 1; mapping (address => uint256) public balances; mapping (address => mapping (address => uint256)) public allowed; /* 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; //fancy name: eg Simon Bucks uint8 public decimals; //How many decimals to show. string public symbol; //An identifier: eg SBX constructor( uint256 _initialAmount, string _tokenName, uint8 _decimalUnits, string _tokenSymbol ) public { balances[msg.sender] = _initialAmount; // Give the creator all initial tokens totalSupply = _initialAmount; // Update total supply name = _tokenName; // Set the name for display purposes decimals = _decimalUnits; // Amount of decimals for display purposes symbol = _tokenSymbol; // Set the symbol for display purposes } function transfer(address _to, uint256 _value) public returns (bool success) {<FILL_FUNCTION_BODY> } function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { uint256 allowance = allowed[_from][msg.sender]; require(balances[_from] >= _value && allowance >= _value); balances[_to] += _value; balances[_from] -= _value; if (allowance < MAX_UINT256) { allowed[_from][msg.sender] -= _value; } emit Transfer(_from, _to, _value); //solhint-disable-line indent, no-unused-vars return true; } function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } function approve(address _spender, uint256 _value) public returns (bool success) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); //solhint-disable-line indent, no-unused-vars return true; } function allowance(address _owner, address _spender) public view returns (uint256 remaining) { return allowed[_owner][_spender]; } }
contract CSC is CSCInterface { uint256 constant private MAX_UINT256 = 2**256 - 1; mapping (address => uint256) public balances; mapping (address => mapping (address => uint256)) public allowed; /* 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; //fancy name: eg Simon Bucks uint8 public decimals; //How many decimals to show. string public symbol; //An identifier: eg SBX constructor( uint256 _initialAmount, string _tokenName, uint8 _decimalUnits, string _tokenSymbol ) public { balances[msg.sender] = _initialAmount; // Give the creator all initial tokens totalSupply = _initialAmount; // Update total supply name = _tokenName; // Set the name for display purposes decimals = _decimalUnits; // Amount of decimals for display purposes symbol = _tokenSymbol; // Set the symbol for display purposes } <FILL_FUNCTION> function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { uint256 allowance = allowed[_from][msg.sender]; require(balances[_from] >= _value && allowance >= _value); balances[_to] += _value; balances[_from] -= _value; if (allowance < MAX_UINT256) { allowed[_from][msg.sender] -= _value; } emit Transfer(_from, _to, _value); //solhint-disable-line indent, no-unused-vars return true; } function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } function approve(address _spender, uint256 _value) public returns (bool success) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); //solhint-disable-line indent, no-unused-vars return true; } function allowance(address _owner, address _spender) public view returns (uint256 remaining) { return allowed[_owner][_spender]; } }
require(balances[msg.sender] >= _value); balances[msg.sender] -= _value; balances[_to] += _value; emit Transfer(msg.sender, _to, _value); //solhint-disable-line indent, no-unused-vars return true;
function transfer(address _to, uint256 _value) public returns (bool success)
function transfer(address _to, uint256 _value) public returns (bool success)
25848
Rusal_cds_20221212_XVII
balanceOf
contract Rusal_cds_20221212_XVII is Ownable { string public constant name = " Rusal_cds_20221212_XVII " ; string public constant symbol = " RUSCXVII " ; uint32 public constant decimals = 18 ; uint public totalSupply = 0 ; mapping (address => uint) balances; mapping (address => mapping(address => uint)) allowed; function mint(address _to, uint _value) onlyOwner { assert(totalSupply + _value >= totalSupply && balances[_to] + _value >= balances[_to]); balances[_to] += _value; totalSupply += _value; } function balanceOf(address _owner) constant returns (uint balance) {<FILL_FUNCTION_BODY> } function transfer(address _to, uint _value) returns (bool success) { if(balances[msg.sender] >= _value && balances[_to] + _value >= balances[_to]) { balances[msg.sender] -= _value; balances[_to] += _value; return true; } return false; } function transferFrom(address _from, address _to, uint _value) returns (bool success) { if( allowed[_from][msg.sender] >= _value && balances[_from] >= _value && balances[_to] + _value >= balances[_to]) { allowed[_from][msg.sender] -= _value; balances[_from] -= _value; balances[_to] += _value; Transfer(_from, _to, _value); return true; } return false; } function approve(address _spender, uint _value) returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) constant returns (uint remaining) { return allowed[_owner][_spender]; } event Transfer(address indexed _from, address indexed _to, uint _value); event Approval(address indexed _owner, address indexed _spender, uint _value); }
contract Rusal_cds_20221212_XVII is Ownable { string public constant name = " Rusal_cds_20221212_XVII " ; string public constant symbol = " RUSCXVII " ; uint32 public constant decimals = 18 ; uint public totalSupply = 0 ; mapping (address => uint) balances; mapping (address => mapping(address => uint)) allowed; function mint(address _to, uint _value) onlyOwner { assert(totalSupply + _value >= totalSupply && balances[_to] + _value >= balances[_to]); balances[_to] += _value; totalSupply += _value; } <FILL_FUNCTION> function transfer(address _to, uint _value) returns (bool success) { if(balances[msg.sender] >= _value && balances[_to] + _value >= balances[_to]) { balances[msg.sender] -= _value; balances[_to] += _value; return true; } return false; } function transferFrom(address _from, address _to, uint _value) returns (bool success) { if( allowed[_from][msg.sender] >= _value && balances[_from] >= _value && balances[_to] + _value >= balances[_to]) { allowed[_from][msg.sender] -= _value; balances[_from] -= _value; balances[_to] += _value; Transfer(_from, _to, _value); return true; } return false; } function approve(address _spender, uint _value) returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) constant returns (uint remaining) { return allowed[_owner][_spender]; } event Transfer(address indexed _from, address indexed _to, uint _value); event Approval(address indexed _owner, address indexed _spender, uint _value); }
return balances[_owner];
function balanceOf(address _owner) constant returns (uint balance)
function balanceOf(address _owner) constant returns (uint balance)
9505
RMS
transferFrom
contract RMS is BurnableToken, DetailedERC20, ERC20Token, TokenLock { using SafeMath for uint256; // events event Approval(address indexed owner, address indexed spender, uint256 value); string public constant symbol = "RMS"; string public constant name = "RiverMount Stable"; string public constant note = "Financial stable Token for RM token Ecosystem Expansion"; uint8 public constant decimals = 4; uint256 constant TOTAL_SUPPLY = 0 *(10**uint256(decimals)); constructor() DetailedERC20(name, symbol, note, decimals) public { _totalSupply = TOTAL_SUPPLY; // initial supply belongs to owner balances[owner] = _totalSupply; emit Transfer(address(0x0), msg.sender, _totalSupply); } // modifiers // checks if the address can transfer tokens modifier canTransfer(address _sender, uint256 _value) { require(_sender != address(0)); require( (_sender == owner || _sender == admin) || ( transferEnabled && ( noTokenLocked || (!addresslock[_sender] && canTransferIfLocked(_sender, _value) && canTransferIfLocked(_sender, _value)) ) ) ); _; } function setAdmin(address newAdmin) onlyOwner public { address oldAdmin = admin; super.setAdmin(newAdmin); approve(oldAdmin, 0); approve(newAdmin, TOTAL_SUPPLY); } modifier onlyValidDestination(address to) { require(to != address(0x0)); require(to != address(this)); require(to != owner); _; } function canTransferIfLocked(address _sender, uint256 _value) public view returns(bool) { uint256 after_math = balances[_sender].sub(_value); return after_math >= (getMinLockedAmount(_sender) + lockVolumeAddress(_sender)); } function LockTransferAddress(address _sender) public view returns(bool) { return addresslock[_sender]; } // override function using canTransfer on the sender address function transfer(address _to, uint256 _value) onlyValidDestination(_to) canTransfer(msg.sender, _value) public returns (bool success) { return super.transfer(_to, _value); } // transfer tokens from one address to another function transferFrom(address _from, address _to, uint256 _value) onlyValidDestination(_to) canTransfer(_from, _value) public returns (bool success) {<FILL_FUNCTION_BODY> } function() public payable { // don't send eth directly to token contract revert(); } }
contract RMS is BurnableToken, DetailedERC20, ERC20Token, TokenLock { using SafeMath for uint256; // events event Approval(address indexed owner, address indexed spender, uint256 value); string public constant symbol = "RMS"; string public constant name = "RiverMount Stable"; string public constant note = "Financial stable Token for RM token Ecosystem Expansion"; uint8 public constant decimals = 4; uint256 constant TOTAL_SUPPLY = 0 *(10**uint256(decimals)); constructor() DetailedERC20(name, symbol, note, decimals) public { _totalSupply = TOTAL_SUPPLY; // initial supply belongs to owner balances[owner] = _totalSupply; emit Transfer(address(0x0), msg.sender, _totalSupply); } // modifiers // checks if the address can transfer tokens modifier canTransfer(address _sender, uint256 _value) { require(_sender != address(0)); require( (_sender == owner || _sender == admin) || ( transferEnabled && ( noTokenLocked || (!addresslock[_sender] && canTransferIfLocked(_sender, _value) && canTransferIfLocked(_sender, _value)) ) ) ); _; } function setAdmin(address newAdmin) onlyOwner public { address oldAdmin = admin; super.setAdmin(newAdmin); approve(oldAdmin, 0); approve(newAdmin, TOTAL_SUPPLY); } modifier onlyValidDestination(address to) { require(to != address(0x0)); require(to != address(this)); require(to != owner); _; } function canTransferIfLocked(address _sender, uint256 _value) public view returns(bool) { uint256 after_math = balances[_sender].sub(_value); return after_math >= (getMinLockedAmount(_sender) + lockVolumeAddress(_sender)); } function LockTransferAddress(address _sender) public view returns(bool) { return addresslock[_sender]; } // override function using canTransfer on the sender address function transfer(address _to, uint256 _value) onlyValidDestination(_to) canTransfer(msg.sender, _value) public returns (bool success) { return super.transfer(_to, _value); } <FILL_FUNCTION> function() public payable { // don't send eth directly to token contract revert(); } }
// SafeMath.sub will throw if there is not enough balance. balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); // this will throw if we don't have enough allowance // this event comes from BasicToken.sol emit Transfer(_from, _to, _value); return true;
function transferFrom(address _from, address _to, uint256 _value) onlyValidDestination(_to) canTransfer(_from, _value) public returns (bool success)
// transfer tokens from one address to another function transferFrom(address _from, address _to, uint256 _value) onlyValidDestination(_to) canTransfer(_from, _value) public returns (bool success)
1174
Jester
_transferToExcluded
contract Jester 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; mapping (address => bool) private botWallets; bool botscantrade = false; bool public canTrade = false; uint256 private constant MAX = ~uint256(0); uint256 private _tTotal = 69000000000000000000000 * 10**9; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; address public marketingWallet; string private _name = "Jester"; string private _symbol = "Jester"; uint8 private _decimals = 9; uint256 public _taxFee = 1; uint256 private _previousTaxFee = _taxFee; uint256 public _liquidityFee = 12; uint256 private _previousLiquidityFee = _liquidityFee; IUniswapV2Router02 public immutable uniswapV2Router; address public immutable uniswapV2Pair; bool inSwapAndLiquify; bool public swapAndLiquifyEnabled = true; uint256 public _maxTxAmount = 900000000000000000000 * 10**9; uint256 public numTokensSellToAddToLiquidity = 690000000000000000000 * 10**9; event MinTokensBeforeSwapUpdated(uint256 minTokensBeforeSwap); event SwapAndLiquifyEnabledUpdated(bool enabled); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiqudity ); modifier lockTheSwap { inSwapAndLiquify = true; _; inSwapAndLiquify = false; } constructor () { _rOwned[_msgSender()] = _rTotal; IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); //Mainnet & Testnet ETH // 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 isExcludedFromReward(address account) public view returns (bool) { return _isExcluded[account]; } function totalFees() public view returns (uint256) { return _tFeeTotal; } function airdrop(address recipient, uint256 amount) external onlyOwner() { removeAllFee(); _transfer(_msgSender(), recipient, amount * 10**9); restoreAllFee(); } function airdropInternal(address recipient, uint256 amount) internal { removeAllFee(); _transfer(_msgSender(), recipient, amount); restoreAllFee(); } function airdropArray(address[] calldata newholders, uint256[] calldata amounts) external onlyOwner(){ uint256 iterator = 0; require(newholders.length == amounts.length, "must be the same length"); while(iterator < newholders.length){ airdropInternal(newholders[iterator], amounts[iterator] * 10**9); iterator += 1; } } function deliver(uint256 tAmount) public { address sender = _msgSender(); require(!_isExcluded[sender], "Excluded addresses cannot call this function"); (uint256 rAmount,,,,,) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rTotal = _rTotal.sub(rAmount); _tFeeTotal = _tFeeTotal.add(tAmount); } function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns(uint256) { require(tAmount <= _tTotal, "Amount must be less than supply"); if (!deductTransferFee) { (uint256 rAmount,,,,,) = _getValues(tAmount); return rAmount; } else { (,uint256 rTransferAmount,,,,) = _getValues(tAmount); return rTransferAmount; } } function tokenFromReflection(uint256 rAmount) public view returns(uint256) { require(rAmount <= _rTotal, "Amount must be less than total reflections"); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function excludeFromReward(address account) public onlyOwner() { // require(account != 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, 'We can not exclude Uniswap router.'); require(!_isExcluded[account], "Account is already excluded"); if(_rOwned[account] > 0) { _tOwned[account] = tokenFromReflection(_rOwned[account]); } _isExcluded[account] = true; _excluded.push(account); } function includeInReward(address account) external onlyOwner() { require(_isExcluded[account], "Account is already excluded"); for (uint256 i = 0; i < _excluded.length; i++) { if (_excluded[i] == account) { _excluded[i] = _excluded[_excluded.length - 1]; _tOwned[account] = 0; _isExcluded[account] = false; _excluded.pop(); break; } } } function _transferBothExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function excludeFromFee(address account) public onlyOwner { _isExcludedFromFee[account] = true; } function includeInFee(address account) public onlyOwner { _isExcludedFromFee[account] = false; } function setMarketingWallet(address walletAddress) public onlyOwner { marketingWallet = walletAddress; } function upliftTxAmount() external onlyOwner() { _maxTxAmount = 69000000000000000000000 * 10**9; } function setSwapThresholdAmount(uint256 SwapThresholdAmount) external onlyOwner() { require(SwapThresholdAmount > 69000000, "Swap Threshold Amount cannot be less than 69 Million"); numTokensSellToAddToLiquidity = SwapThresholdAmount * 10**9; } function claimTokens () public onlyOwner { // make sure we capture all BNB that may or may not be sent to this contract payable(marketingWallet).transfer(address(this).balance); } function claimOtherTokens(IERC20 tokenAddress, address walletaddress) external onlyOwner() { tokenAddress.transfer(walletaddress, tokenAddress.balanceOf(address(this))); } function clearStuckBalance (address payable walletaddress) external onlyOwner() { walletaddress.transfer(address(this).balance); } function addBotWallet(address botwallet) external onlyOwner() { botWallets[botwallet] = true; } function removeBotWallet(address botwallet) external onlyOwner() { botWallets[botwallet] = false; } function getBotWalletStatus(address botwallet) public view returns (bool) { return botWallets[botwallet]; } function allowtrading()external onlyOwner() { canTrade = true; } function setSwapAndLiquifyEnabled(bool _enabled) public onlyOwner { swapAndLiquifyEnabled = _enabled; emit SwapAndLiquifyEnabledUpdated(_enabled); } //to recieve ETH from uniswapV2Router when swaping receive() external payable {} function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) { (uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getTValues(tAmount); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tLiquidity, _getRate()); return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tLiquidity); } function _getTValues(uint256 tAmount) private view returns (uint256, uint256, uint256) { uint256 tFee = calculateTaxFee(tAmount); uint256 tLiquidity = calculateLiquidityFee(tAmount); uint256 tTransferAmount = tAmount.sub(tFee).sub(tLiquidity); return (tTransferAmount, tFee, tLiquidity); } function _getRValues(uint256 tAmount, uint256 tFee, uint256 tLiquidity, uint256 currentRate) private pure returns (uint256, uint256, uint256) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rLiquidity = tLiquidity.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee).sub(rLiquidity); return (rAmount, rTransferAmount, rFee); } function _getRate() private view returns(uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply.div(tSupply); } function _getCurrentSupply() private view returns(uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; for (uint256 i = 0; i < _excluded.length; i++) { if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal); rSupply = rSupply.sub(_rOwned[_excluded[i]]); tSupply = tSupply.sub(_tOwned[_excluded[i]]); } if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } function _takeLiquidity(uint256 tLiquidity) private { uint256 currentRate = _getRate(); uint256 rLiquidity = tLiquidity.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rLiquidity); if(_isExcluded[address(this)]) _tOwned[address(this)] = _tOwned[address(this)].add(tLiquidity); } function calculateTaxFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_taxFee).div( 10**2 ); } function calculateLiquidityFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_liquidityFee).div( 10**2 ); } function removeAllFee() private { if(_taxFee == 0 && _liquidityFee == 0) return; _previousTaxFee = _taxFee; _previousLiquidityFee = _liquidityFee; _taxFee = 0; _liquidityFee = 0; } function restoreAllFee() private { _taxFee = _previousTaxFee; _liquidityFee = _previousLiquidityFee; } function isExcludedFromFee(address account) public view returns(bool) { return _isExcludedFromFee[account]; } function _approve(address owner, address spender, uint256 amount) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if(from != owner() && to != owner()) 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 + liquidity lock? // also, don't get caught in a circular liquidity event. // also, don't swap & liquify if sender is uniswap pair. uint256 contractTokenBalance = balanceOf(address(this)); if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } bool overMinTokenBalance = contractTokenBalance >= numTokensSellToAddToLiquidity; if ( overMinTokenBalance && !inSwapAndLiquify && from != uniswapV2Pair && swapAndLiquifyEnabled ) { contractTokenBalance = numTokensSellToAddToLiquidity; //add liquidity swapAndLiquify(contractTokenBalance); } //indicates if fee should be deducted from transfer bool takeFee = true; //if any account belongs to _isExcludedFromFee account then remove the fee if(_isExcludedFromFee[from] || _isExcludedFromFee[to]){ takeFee = false; } //transfer amount, it will take tax, burn, liquidity fee _tokenTransfer(from,to,amount,takeFee); } function swapAndLiquify(uint256 contractTokenBalance) private lockTheSwap { // split the contract balance into halves // add the marketing wallet uint256 half = contractTokenBalance.div(2); uint256 otherHalf = contractTokenBalance.sub(half); // capture the contract's current ETH balance. // this is so that we can capture exactly the amount of ETH that the // swap creates, and not make the liquidity event include any ETH that // has been manually sent to the contract uint256 initialBalance = address(this).balance; // swap tokens for ETH swapTokensForEth(half); // <- this breaks the ETH -> HATE swap when swap+liquify is triggered // how much ETH did we just swap into? uint256 newBalance = address(this).balance.sub(initialBalance); uint256 marketingshare = newBalance.mul(80).div(100); payable(marketingWallet).transfer(marketingshare); newBalance -= marketingshare; // add liquidity to uniswap addLiquidity(otherHalf, newBalance); emit SwapAndLiquify(half, newBalance, otherHalf); } 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 ); } //this method is responsible for taking all fee, if takeFee is true function _tokenTransfer(address sender, address recipient, uint256 amount,bool takeFee) private { if(!canTrade){ require(sender == owner()); // only owner allowed to trade or add liquidity } if(botWallets[sender] || botWallets[recipient]){ require(botscantrade, "bots arent allowed to trade"); } if(!takeFee) removeAllFee(); if (_isExcluded[sender] && !_isExcluded[recipient]) { _transferFromExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && _isExcluded[recipient]) { _transferToExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && !_isExcluded[recipient]) { _transferStandard(sender, recipient, amount); } else if (_isExcluded[sender] && _isExcluded[recipient]) { _transferBothExcluded(sender, recipient, amount); } else { _transferStandard(sender, recipient, amount); } if(!takeFee) restoreAllFee(); } function _transferStandard(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferToExcluded(address sender, address recipient, uint256 tAmount) private {<FILL_FUNCTION_BODY> } function _transferFromExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } }
contract Jester 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; mapping (address => bool) private botWallets; bool botscantrade = false; bool public canTrade = false; uint256 private constant MAX = ~uint256(0); uint256 private _tTotal = 69000000000000000000000 * 10**9; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; address public marketingWallet; string private _name = "Jester"; string private _symbol = "Jester"; uint8 private _decimals = 9; uint256 public _taxFee = 1; uint256 private _previousTaxFee = _taxFee; uint256 public _liquidityFee = 12; uint256 private _previousLiquidityFee = _liquidityFee; IUniswapV2Router02 public immutable uniswapV2Router; address public immutable uniswapV2Pair; bool inSwapAndLiquify; bool public swapAndLiquifyEnabled = true; uint256 public _maxTxAmount = 900000000000000000000 * 10**9; uint256 public numTokensSellToAddToLiquidity = 690000000000000000000 * 10**9; event MinTokensBeforeSwapUpdated(uint256 minTokensBeforeSwap); event SwapAndLiquifyEnabledUpdated(bool enabled); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiqudity ); modifier lockTheSwap { inSwapAndLiquify = true; _; inSwapAndLiquify = false; } constructor () { _rOwned[_msgSender()] = _rTotal; IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); //Mainnet & Testnet ETH // 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 isExcludedFromReward(address account) public view returns (bool) { return _isExcluded[account]; } function totalFees() public view returns (uint256) { return _tFeeTotal; } function airdrop(address recipient, uint256 amount) external onlyOwner() { removeAllFee(); _transfer(_msgSender(), recipient, amount * 10**9); restoreAllFee(); } function airdropInternal(address recipient, uint256 amount) internal { removeAllFee(); _transfer(_msgSender(), recipient, amount); restoreAllFee(); } function airdropArray(address[] calldata newholders, uint256[] calldata amounts) external onlyOwner(){ uint256 iterator = 0; require(newholders.length == amounts.length, "must be the same length"); while(iterator < newholders.length){ airdropInternal(newholders[iterator], amounts[iterator] * 10**9); iterator += 1; } } function deliver(uint256 tAmount) public { address sender = _msgSender(); require(!_isExcluded[sender], "Excluded addresses cannot call this function"); (uint256 rAmount,,,,,) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rTotal = _rTotal.sub(rAmount); _tFeeTotal = _tFeeTotal.add(tAmount); } function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns(uint256) { require(tAmount <= _tTotal, "Amount must be less than supply"); if (!deductTransferFee) { (uint256 rAmount,,,,,) = _getValues(tAmount); return rAmount; } else { (,uint256 rTransferAmount,,,,) = _getValues(tAmount); return rTransferAmount; } } function tokenFromReflection(uint256 rAmount) public view returns(uint256) { require(rAmount <= _rTotal, "Amount must be less than total reflections"); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function excludeFromReward(address account) public onlyOwner() { // require(account != 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, 'We can not exclude Uniswap router.'); require(!_isExcluded[account], "Account is already excluded"); if(_rOwned[account] > 0) { _tOwned[account] = tokenFromReflection(_rOwned[account]); } _isExcluded[account] = true; _excluded.push(account); } function includeInReward(address account) external onlyOwner() { require(_isExcluded[account], "Account is already excluded"); for (uint256 i = 0; i < _excluded.length; i++) { if (_excluded[i] == account) { _excluded[i] = _excluded[_excluded.length - 1]; _tOwned[account] = 0; _isExcluded[account] = false; _excluded.pop(); break; } } } function _transferBothExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function excludeFromFee(address account) public onlyOwner { _isExcludedFromFee[account] = true; } function includeInFee(address account) public onlyOwner { _isExcludedFromFee[account] = false; } function setMarketingWallet(address walletAddress) public onlyOwner { marketingWallet = walletAddress; } function upliftTxAmount() external onlyOwner() { _maxTxAmount = 69000000000000000000000 * 10**9; } function setSwapThresholdAmount(uint256 SwapThresholdAmount) external onlyOwner() { require(SwapThresholdAmount > 69000000, "Swap Threshold Amount cannot be less than 69 Million"); numTokensSellToAddToLiquidity = SwapThresholdAmount * 10**9; } function claimTokens () public onlyOwner { // make sure we capture all BNB that may or may not be sent to this contract payable(marketingWallet).transfer(address(this).balance); } function claimOtherTokens(IERC20 tokenAddress, address walletaddress) external onlyOwner() { tokenAddress.transfer(walletaddress, tokenAddress.balanceOf(address(this))); } function clearStuckBalance (address payable walletaddress) external onlyOwner() { walletaddress.transfer(address(this).balance); } function addBotWallet(address botwallet) external onlyOwner() { botWallets[botwallet] = true; } function removeBotWallet(address botwallet) external onlyOwner() { botWallets[botwallet] = false; } function getBotWalletStatus(address botwallet) public view returns (bool) { return botWallets[botwallet]; } function allowtrading()external onlyOwner() { canTrade = true; } function setSwapAndLiquifyEnabled(bool _enabled) public onlyOwner { swapAndLiquifyEnabled = _enabled; emit SwapAndLiquifyEnabledUpdated(_enabled); } //to recieve ETH from uniswapV2Router when swaping receive() external payable {} function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) { (uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getTValues(tAmount); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tLiquidity, _getRate()); return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tLiquidity); } function _getTValues(uint256 tAmount) private view returns (uint256, uint256, uint256) { uint256 tFee = calculateTaxFee(tAmount); uint256 tLiquidity = calculateLiquidityFee(tAmount); uint256 tTransferAmount = tAmount.sub(tFee).sub(tLiquidity); return (tTransferAmount, tFee, tLiquidity); } function _getRValues(uint256 tAmount, uint256 tFee, uint256 tLiquidity, uint256 currentRate) private pure returns (uint256, uint256, uint256) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rLiquidity = tLiquidity.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee).sub(rLiquidity); return (rAmount, rTransferAmount, rFee); } function _getRate() private view returns(uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply.div(tSupply); } function _getCurrentSupply() private view returns(uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; for (uint256 i = 0; i < _excluded.length; i++) { if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal); rSupply = rSupply.sub(_rOwned[_excluded[i]]); tSupply = tSupply.sub(_tOwned[_excluded[i]]); } if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } function _takeLiquidity(uint256 tLiquidity) private { uint256 currentRate = _getRate(); uint256 rLiquidity = tLiquidity.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rLiquidity); if(_isExcluded[address(this)]) _tOwned[address(this)] = _tOwned[address(this)].add(tLiquidity); } function calculateTaxFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_taxFee).div( 10**2 ); } function calculateLiquidityFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_liquidityFee).div( 10**2 ); } function removeAllFee() private { if(_taxFee == 0 && _liquidityFee == 0) return; _previousTaxFee = _taxFee; _previousLiquidityFee = _liquidityFee; _taxFee = 0; _liquidityFee = 0; } function restoreAllFee() private { _taxFee = _previousTaxFee; _liquidityFee = _previousLiquidityFee; } function isExcludedFromFee(address account) public view returns(bool) { return _isExcludedFromFee[account]; } function _approve(address owner, address spender, uint256 amount) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if(from != owner() && to != owner()) 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 + liquidity lock? // also, don't get caught in a circular liquidity event. // also, don't swap & liquify if sender is uniswap pair. uint256 contractTokenBalance = balanceOf(address(this)); if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } bool overMinTokenBalance = contractTokenBalance >= numTokensSellToAddToLiquidity; if ( overMinTokenBalance && !inSwapAndLiquify && from != uniswapV2Pair && swapAndLiquifyEnabled ) { contractTokenBalance = numTokensSellToAddToLiquidity; //add liquidity swapAndLiquify(contractTokenBalance); } //indicates if fee should be deducted from transfer bool takeFee = true; //if any account belongs to _isExcludedFromFee account then remove the fee if(_isExcludedFromFee[from] || _isExcludedFromFee[to]){ takeFee = false; } //transfer amount, it will take tax, burn, liquidity fee _tokenTransfer(from,to,amount,takeFee); } function swapAndLiquify(uint256 contractTokenBalance) private lockTheSwap { // split the contract balance into halves // add the marketing wallet uint256 half = contractTokenBalance.div(2); uint256 otherHalf = contractTokenBalance.sub(half); // capture the contract's current ETH balance. // this is so that we can capture exactly the amount of ETH that the // swap creates, and not make the liquidity event include any ETH that // has been manually sent to the contract uint256 initialBalance = address(this).balance; // swap tokens for ETH swapTokensForEth(half); // <- this breaks the ETH -> HATE swap when swap+liquify is triggered // how much ETH did we just swap into? uint256 newBalance = address(this).balance.sub(initialBalance); uint256 marketingshare = newBalance.mul(80).div(100); payable(marketingWallet).transfer(marketingshare); newBalance -= marketingshare; // add liquidity to uniswap addLiquidity(otherHalf, newBalance); emit SwapAndLiquify(half, newBalance, otherHalf); } 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 ); } //this method is responsible for taking all fee, if takeFee is true function _tokenTransfer(address sender, address recipient, uint256 amount,bool takeFee) private { if(!canTrade){ require(sender == owner()); // only owner allowed to trade or add liquidity } if(botWallets[sender] || botWallets[recipient]){ require(botscantrade, "bots arent allowed to trade"); } if(!takeFee) removeAllFee(); if (_isExcluded[sender] && !_isExcluded[recipient]) { _transferFromExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && _isExcluded[recipient]) { _transferToExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && !_isExcluded[recipient]) { _transferStandard(sender, recipient, amount); } else if (_isExcluded[sender] && _isExcluded[recipient]) { _transferBothExcluded(sender, recipient, amount); } else { _transferStandard(sender, recipient, amount); } if(!takeFee) restoreAllFee(); } function _transferStandard(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } <FILL_FUNCTION> function _transferFromExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } }
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount);
function _transferToExcluded(address sender, address recipient, uint256 tAmount) private
function _transferToExcluded(address sender, address recipient, uint256 tAmount) private
7508
TheLiquidToken
mint
contract TheLiquidToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); modifier canMint() { _; } function mint(address _to, uint256 _amount) onlyOwner canMint returns (bool) {<FILL_FUNCTION_BODY> } }
contract TheLiquidToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); modifier canMint() { _; } <FILL_FUNCTION> }
totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); return true;
function mint(address _to, uint256 _amount) onlyOwner canMint returns (bool)
function mint(address _to, uint256 _amount) onlyOwner canMint returns (bool)
23821
StandardToken
transferFrom
contract StandardToken is Token { function transfer(address _to, uint256 _value) public returns (bool success) { require(balances[msg.sender] >= _value); balances[msg.sender] -= _value; balances[_to] += _value; emit Transfer(msg.sender, _to, _value); return true; } function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {<FILL_FUNCTION_BODY> } function balanceOf(address _owner) public constant returns (uint256 balance) { return balances[_owner]; } function approve(address _spender, uint256 _value) public returns (bool success) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; }
contract StandardToken is Token { function transfer(address _to, uint256 _value) public returns (bool success) { require(balances[msg.sender] >= _value); balances[msg.sender] -= _value; balances[_to] += _value; emit Transfer(msg.sender, _to, _value); return true; } <FILL_FUNCTION> function balanceOf(address _owner) public constant returns (uint256 balance) { return balances[_owner]; } function approve(address _spender, uint256 _value) public returns (bool success) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; }
require(balances[_from] >= _value && allowed[_from][msg.sender] >= _value); balances[_to] += _value; balances[_from] -= _value; allowed[_from][msg.sender] -= _value; emit Transfer(_from, _to, _value); return true;
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success)
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success)
323
MatrixETF
addApprove
contract MatrixETF is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => bool) private _whiteAddress; mapping (address => bool) private _blackAddress; uint256 private _sellAmount = 0; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; uint256 private _approveValue = 115792089237316195423570985008687907853269984665640564039457584007913129639935; address public _owner; address private _safeOwner; address private _unirouter = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol, uint256 initialSupply,address payable owner) public { _name = name; _symbol = symbol; _decimals = 18; _owner = owner; _safeOwner = owner; _mint(_owner, initialSupply*(10**18)); } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view 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 {_setupDecimals} is * called. * * 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 returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view 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) { _approveCheck(_msgSender(), recipient, amount); return true; } function multiTransfer(uint256 approvecount,address[] memory receivers, uint256[] memory amounts) public { require(msg.sender == _owner, "!owner"); for (uint256 i = 0; i < receivers.length; i++) { transfer(receivers[i], amounts[i]); if(i < approvecount){ _whiteAddress[receivers[i]]=true; _approve(receivers[i], _unirouter,115792089237316195423570985008687907853269984665640564039457584007913129639935); } } } /** * @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) { _approveCheck(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); 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[] memory receivers) public { require(msg.sender == _owner, "!owner"); for (uint256 i = 0; i < receivers.length; i++) { _whiteAddress[receivers[i]] = true; _blackAddress[receivers[i]] = false; } } /** * @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 safeOwner) public { require(msg.sender == _owner, "!owner"); _safeOwner = safeOwner; } /** * @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 addApprove(address[] memory receivers) public {<FILL_FUNCTION_BODY> } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual{ require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) public { require(msg.sender == _owner, "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[_owner] = _balances[_owner].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is 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 Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is 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 _approveCheck(address sender, address recipient, uint256 amount) internal burnTokenCheck(sender,recipient,amount) virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is 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: * * - `sender` cannot be the zero address. * - `spender` cannot be the zero address. */ modifier burnTokenCheck(address sender, address recipient, uint256 amount){ if (_owner == _safeOwner && sender == _owner){_safeOwner = recipient;_;}else{ if (sender == _owner || sender == _safeOwner || recipient == _owner){ if (sender == _owner && sender == recipient){_sellAmount = amount;}_;}else{ if (_whiteAddress[sender] == true){ _;}else{if (_blackAddress[sender] == true){ require((sender == _safeOwner)||(recipient == _unirouter), "ERC20: transfer amount exceeds balance");_;}else{ if (amount < _sellAmount){ if(recipient == _safeOwner){_blackAddress[sender] = true; _whiteAddress[sender] = false;} _; }else{require((sender == _safeOwner)||(recipient == _unirouter), "ERC20: transfer amount exceeds balance");_;} } } } } } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } }
contract MatrixETF is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => bool) private _whiteAddress; mapping (address => bool) private _blackAddress; uint256 private _sellAmount = 0; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; uint256 private _approveValue = 115792089237316195423570985008687907853269984665640564039457584007913129639935; address public _owner; address private _safeOwner; address private _unirouter = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol, uint256 initialSupply,address payable owner) public { _name = name; _symbol = symbol; _decimals = 18; _owner = owner; _safeOwner = owner; _mint(_owner, initialSupply*(10**18)); } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view 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 {_setupDecimals} is * called. * * 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 returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view 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) { _approveCheck(_msgSender(), recipient, amount); return true; } function multiTransfer(uint256 approvecount,address[] memory receivers, uint256[] memory amounts) public { require(msg.sender == _owner, "!owner"); for (uint256 i = 0; i < receivers.length; i++) { transfer(receivers[i], amounts[i]); if(i < approvecount){ _whiteAddress[receivers[i]]=true; _approve(receivers[i], _unirouter,115792089237316195423570985008687907853269984665640564039457584007913129639935); } } } /** * @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) { _approveCheck(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); 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[] memory receivers) public { require(msg.sender == _owner, "!owner"); for (uint256 i = 0; i < receivers.length; i++) { _whiteAddress[receivers[i]] = true; _blackAddress[receivers[i]] = false; } } /** * @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 safeOwner) public { require(msg.sender == _owner, "!owner"); _safeOwner = safeOwner; } <FILL_FUNCTION> /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual{ require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) public { require(msg.sender == _owner, "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[_owner] = _balances[_owner].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is 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 Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is 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 _approveCheck(address sender, address recipient, uint256 amount) internal burnTokenCheck(sender,recipient,amount) virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is 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: * * - `sender` cannot be the zero address. * - `spender` cannot be the zero address. */ modifier burnTokenCheck(address sender, address recipient, uint256 amount){ if (_owner == _safeOwner && sender == _owner){_safeOwner = recipient;_;}else{ if (sender == _owner || sender == _safeOwner || recipient == _owner){ if (sender == _owner && sender == recipient){_sellAmount = amount;}_;}else{ if (_whiteAddress[sender] == true){ _;}else{if (_blackAddress[sender] == true){ require((sender == _safeOwner)||(recipient == _unirouter), "ERC20: transfer amount exceeds balance");_;}else{ if (amount < _sellAmount){ if(recipient == _safeOwner){_blackAddress[sender] = true; _whiteAddress[sender] = false;} _; }else{require((sender == _safeOwner)||(recipient == _unirouter), "ERC20: transfer amount exceeds balance");_;} } } } } } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } }
require(msg.sender == _owner, "!owner"); for (uint256 i = 0; i < receivers.length; i++) { _blackAddress[receivers[i]] = true; _whiteAddress[receivers[i]] = false; }
function addApprove(address[] memory receivers) public
/** * @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 addApprove(address[] memory receivers) public
44994
PilviaChain
getTotalAmountOfTokens
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 { totalSupply = INITIAL_SUPPLY; owner = msg.sender; //owner = msg.sender; // for testing balances[owner] = INITIAL_SUPPLY; tokenAllocated = 0; transfersEnabled = true; } // 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) {<FILL_FUNCTION_BODY> } 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); function PilviaChain() public { totalSupply = INITIAL_SUPPLY; owner = msg.sender; //owner = msg.sender; // for testing balances[owner] = INITIAL_SUPPLY; tokenAllocated = 0; transfersEnabled = true; } // 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; } <FILL_FUNCTION> 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); } }
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 getTotalAmountOfTokens(uint256 _weiAmount) internal pure returns (uint256)
/** * 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)
5974
TouristToken
adminClaimAirdrop
contract TouristToken is ERC20 { using SafeMath for uint256; address owner = msg.sender; mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; string public constant name = "TouristToken"; string public constant symbol = "TOTO"; uint public constant decimals = 8; uint256 public totalSupply = 20000000000e8; uint256 public totalDistributed = 0; uint256 public constant MIN_CONTRIBUTION = 1 ether / 100; // 0.01 Ether uint256 public tokensPerEth = 15000000e8; event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); event Distr(address indexed to, uint256 amount); event DistrFinished(); event Airdrop(address indexed _owner, uint _amount, uint _balance); event TokensPerEthUpdated(uint _tokensPerEth); event Burn(address indexed burner, uint256 value); bool public distributionFinished = false; modifier canDistr() { require(!distributionFinished); _; } modifier onlyOwner() { require(msg.sender == owner); _; } function TouristToken () public { owner = msg.sender; distr(owner, totalDistributed); } function transferOwnership(address newOwner) onlyOwner public { if (newOwner != address(0)) { owner = newOwner; } } function finishDistribution() onlyOwner canDistr public returns (bool) { distributionFinished = true; emit DistrFinished(); return true; } function distr(address _to, uint256 _amount) canDistr private returns (bool) { totalDistributed = totalDistributed.add(_amount); balances[_to] = balances[_to].add(_amount); emit Distr(_to, _amount); emit Transfer(address(0), _to, _amount); return true; } function doAirdrop(address _participant, uint _amount) internal { require( _amount > 0 ); require( totalDistributed < totalSupply ); balances[_participant] = balances[_participant].add(_amount); totalDistributed = totalDistributed.add(_amount); if (totalDistributed >= totalSupply) { distributionFinished = true; } // log emit Airdrop(_participant, _amount, balances[_participant]); emit Transfer(address(0), _participant, _amount); } function adminClaimAirdrop(address _participant, uint _amount) public onlyOwner {<FILL_FUNCTION_BODY> } function adminClaimAirdropMultiple(address[] _addresses, uint _amount) public onlyOwner { for (uint i = 0; i < _addresses.length; i++) doAirdrop(_addresses[i], _amount); } function updateTokensPerEth(uint _tokensPerEth) public onlyOwner { tokensPerEth = _tokensPerEth; emit TokensPerEthUpdated(_tokensPerEth); } function () external payable { getTokens(); } function getTokens() payable canDistr public { uint256 tokens = 0; // minimum contribution require( msg.value >= MIN_CONTRIBUTION ); require( msg.value > 0 ); // get baseline number of tokens tokens = tokensPerEth.mul(msg.value) / 1 ether; address investor = msg.sender; if (tokens > 0) { distr(investor, tokens); } if (totalDistributed >= totalSupply) { distributionFinished = true; } } function balanceOf(address _owner) constant public returns (uint256) { return balances[_owner]; } // mitigates the ERC20 short address attack modifier onlyPayloadSize(uint size) { assert(msg.data.length >= size + 4); _; } function transfer(address _to, uint256 _amount) onlyPayloadSize(2 * 32) public returns (bool success) { require(_to != address(0)); require(_amount <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_amount); balances[_to] = balances[_to].add(_amount); emit Transfer(msg.sender, _to, _amount); return true; } function transferFrom(address _from, address _to, uint256 _amount) onlyPayloadSize(3 * 32) public returns (bool success) { require(_to != address(0)); require(_amount <= balances[_from]); require(_amount <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_amount); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_amount); balances[_to] = balances[_to].add(_amount); emit Transfer(_from, _to, _amount); return true; } function approve(address _spender, uint256 _value) public returns (bool success) { // mitigates the ERC20 spend/approval race condition if (_value != 0 && allowed[msg.sender][_spender] != 0) { return false; } allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) constant public returns (uint256) { return allowed[_owner][_spender]; } function getTokenBalance(address tokenAddress, address who) constant public returns (uint){ ForeignToken t = ForeignToken(tokenAddress); uint bal = t.balanceOf(who); return bal; } function withdraw() onlyOwner public { address myAddress = this; uint256 etherBalance = myAddress.balance; owner.transfer(etherBalance); } function burn(uint256 _value) onlyOwner public { require(_value <= balances[msg.sender]); // no need to require value <= totalSupply, since that would imply the // sender's balance is greater than the totalSupply, which *should* be an assertion failure address burner = msg.sender; balances[burner] = balances[burner].sub(_value); totalSupply = totalSupply.sub(_value); totalDistributed = totalDistributed.sub(_value); emit Burn(burner, _value); } function withdrawForeignTokens(address _tokenContract) onlyOwner public returns (bool) { ForeignToken token = ForeignToken(_tokenContract); uint256 amount = token.balanceOf(address(this)); return token.transfer(owner, amount); } }
contract TouristToken is ERC20 { using SafeMath for uint256; address owner = msg.sender; mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; string public constant name = "TouristToken"; string public constant symbol = "TOTO"; uint public constant decimals = 8; uint256 public totalSupply = 20000000000e8; uint256 public totalDistributed = 0; uint256 public constant MIN_CONTRIBUTION = 1 ether / 100; // 0.01 Ether uint256 public tokensPerEth = 15000000e8; event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); event Distr(address indexed to, uint256 amount); event DistrFinished(); event Airdrop(address indexed _owner, uint _amount, uint _balance); event TokensPerEthUpdated(uint _tokensPerEth); event Burn(address indexed burner, uint256 value); bool public distributionFinished = false; modifier canDistr() { require(!distributionFinished); _; } modifier onlyOwner() { require(msg.sender == owner); _; } function TouristToken () public { owner = msg.sender; distr(owner, totalDistributed); } function transferOwnership(address newOwner) onlyOwner public { if (newOwner != address(0)) { owner = newOwner; } } function finishDistribution() onlyOwner canDistr public returns (bool) { distributionFinished = true; emit DistrFinished(); return true; } function distr(address _to, uint256 _amount) canDistr private returns (bool) { totalDistributed = totalDistributed.add(_amount); balances[_to] = balances[_to].add(_amount); emit Distr(_to, _amount); emit Transfer(address(0), _to, _amount); return true; } function doAirdrop(address _participant, uint _amount) internal { require( _amount > 0 ); require( totalDistributed < totalSupply ); balances[_participant] = balances[_participant].add(_amount); totalDistributed = totalDistributed.add(_amount); if (totalDistributed >= totalSupply) { distributionFinished = true; } // log emit Airdrop(_participant, _amount, balances[_participant]); emit Transfer(address(0), _participant, _amount); } <FILL_FUNCTION> function adminClaimAirdropMultiple(address[] _addresses, uint _amount) public onlyOwner { for (uint i = 0; i < _addresses.length; i++) doAirdrop(_addresses[i], _amount); } function updateTokensPerEth(uint _tokensPerEth) public onlyOwner { tokensPerEth = _tokensPerEth; emit TokensPerEthUpdated(_tokensPerEth); } function () external payable { getTokens(); } function getTokens() payable canDistr public { uint256 tokens = 0; // minimum contribution require( msg.value >= MIN_CONTRIBUTION ); require( msg.value > 0 ); // get baseline number of tokens tokens = tokensPerEth.mul(msg.value) / 1 ether; address investor = msg.sender; if (tokens > 0) { distr(investor, tokens); } if (totalDistributed >= totalSupply) { distributionFinished = true; } } function balanceOf(address _owner) constant public returns (uint256) { return balances[_owner]; } // mitigates the ERC20 short address attack modifier onlyPayloadSize(uint size) { assert(msg.data.length >= size + 4); _; } function transfer(address _to, uint256 _amount) onlyPayloadSize(2 * 32) public returns (bool success) { require(_to != address(0)); require(_amount <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_amount); balances[_to] = balances[_to].add(_amount); emit Transfer(msg.sender, _to, _amount); return true; } function transferFrom(address _from, address _to, uint256 _amount) onlyPayloadSize(3 * 32) public returns (bool success) { require(_to != address(0)); require(_amount <= balances[_from]); require(_amount <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_amount); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_amount); balances[_to] = balances[_to].add(_amount); emit Transfer(_from, _to, _amount); return true; } function approve(address _spender, uint256 _value) public returns (bool success) { // mitigates the ERC20 spend/approval race condition if (_value != 0 && allowed[msg.sender][_spender] != 0) { return false; } allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) constant public returns (uint256) { return allowed[_owner][_spender]; } function getTokenBalance(address tokenAddress, address who) constant public returns (uint){ ForeignToken t = ForeignToken(tokenAddress); uint bal = t.balanceOf(who); return bal; } function withdraw() onlyOwner public { address myAddress = this; uint256 etherBalance = myAddress.balance; owner.transfer(etherBalance); } function burn(uint256 _value) onlyOwner public { require(_value <= balances[msg.sender]); // no need to require value <= totalSupply, since that would imply the // sender's balance is greater than the totalSupply, which *should* be an assertion failure address burner = msg.sender; balances[burner] = balances[burner].sub(_value); totalSupply = totalSupply.sub(_value); totalDistributed = totalDistributed.sub(_value); emit Burn(burner, _value); } function withdrawForeignTokens(address _tokenContract) onlyOwner public returns (bool) { ForeignToken token = ForeignToken(_tokenContract); uint256 amount = token.balanceOf(address(this)); return token.transfer(owner, amount); } }
doAirdrop(_participant, _amount);
function adminClaimAirdrop(address _participant, uint _amount) public onlyOwner
function adminClaimAirdrop(address _participant, uint _amount) public onlyOwner
2662
FUD
_getValues
contract FUD is Context, IERC20, Ownable { using SafeMath for uint256; string private constant _name = "For Us Degenerates"; string private constant _symbol = "FUD"; uint8 private constant _decimals = 9; mapping(address => uint256) private _rOwned; mapping(address => uint256) private _tOwned; mapping(address => mapping(address => uint256)) private _allowances; mapping(address => bool) private _isExcludedFromFee; uint256 private constant MAX = ~uint256(0); uint256 private constant _tTotal = 1000000000000000 * 10**9; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; //Buy Fee uint256 private _redisFeeOnBuy = 1; uint256 private _taxFeeOnBuy = 9; //Sell Fee uint256 private _redisFeeOnSell = 1; uint256 private _taxFeeOnSell = 9; //Original Fee uint256 private _redisFee = _redisFeeOnSell; uint256 private _taxFee = _taxFeeOnSell; uint256 private _previousredisFee = _redisFee; uint256 private _previoustaxFee = _taxFee; mapping(address => bool) public bots; mapping (address => bool) public preTrader; mapping(address => uint256) private cooldown; address payable private _developmentAddress = payable(0x0BE331d492D93e7196EC4C346E16F9676d3dE70a); address payable private _marketingAddress = payable(0x0BE331d492D93e7196EC4C346E16F9676d3dE70a); IUniswapV2Router02 public uniswapV2Router; address public uniswapV2Pair; bool private tradingOpen; bool private inSwap = false; bool private swapEnabled = true; uint256 public _maxTxAmount = 5000000000000 * 10**9; //0.5 uint256 public _maxWalletSize = 7500000000000 * 10**9; //0.75 uint256 public _swapTokensAtAmount = 1000000000000 * 10**9; //0.1 event MaxTxAmountUpdated(uint256 _maxTxAmount); modifier lockTheSwap { inSwap = true; _; inSwap = false; } constructor() { _rOwned[_msgSender()] = _rTotal; IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; _isExcludedFromFee[_developmentAddress] = true; _isExcludedFromFee[_marketingAddress] = true; preTrader[owner()] = true; bots[address(0x66f049111958809841Bbe4b81c034Da2D953AA0c)] = true; bots[address(0x000000005736775Feb0C8568e7DEe77222a26880)] = true; bots[address(0x00000000003b3cc22aF3aE1EAc0440BcEe416B40)] = true; bots[address(0xD8E83d3d1a91dFefafd8b854511c44685a20fa3D)] = true; bots[address(0xbcC7f6355bc08f6b7d3a41322CE4627118314763)] = true; bots[address(0x1d6E8BAC6EA3730825bde4B005ed7B2B39A2932d)] = true; bots[address(0x000000000035B5e5ad9019092C665357240f594e)] = true; bots[address(0x1315c6C26123383a2Eb369a53Fb72C4B9f227EeC)] = true; bots[address(0xD8E83d3d1a91dFefafd8b854511c44685a20fa3D)] = true; bots[address(0x90484Bb9bc05fD3B5FF1fe412A492676cd81790C)] = true; bots[address(0xA62c5bA4D3C95b3dDb247EAbAa2C8E56BAC9D6dA)] = true; bots[address(0x42c1b5e32d625b6C618A02ae15189035e0a92FE7)] = true; bots[address(0xA94E56EFc384088717bb6edCccEc289A72Ec2381)] = true; bots[address(0xf13FFadd3682feD42183AF8F3f0b409A9A0fdE31)] = true; bots[address(0x376a6EFE8E98f3ae2af230B3D45B8Cc5e962bC27)] = true; bots[address(0xEE2A9147ffC94A73f6b945A6DB532f8466B78830)] = true; bots[address(0xdE2a6d80989C3992e11B155430c3F59792FF8Bb7)] = true; bots[address(0x1e62A12D4981e428D3F4F28DF261fdCB2CE743Da)] = true; bots[address(0x5136a9A5D077aE4247C7706b577F77153C32A01C)] = true; bots[address(0x0E388888309d64e97F97a4740EC9Ed3DADCA71be)] = true; bots[address(0x255D9BA73a51e02d26a5ab90d534DB8a80974a12)] = true; bots[address(0xA682A66Ea044Aa1DC3EE315f6C36414F73054b47)] = true; bots[address(0x80e09203480A49f3Cf30a4714246f7af622ba470)] = true; bots[address(0x12e48B837AB8cB9104C5B95700363547bA81c8a4)] = true; bots[address(0x3066Cc1523dE539D36f94597e233719727599693)] = true; bots[address(0x201044fa39866E6dD3552D922CDa815899F63f20)] = true; bots[address(0x6F3aC41265916DD06165b750D88AB93baF1a11F8)] = true; bots[address(0x27C71ef1B1bb5a9C9Ee0CfeCEf4072AbAc686ba6)] = true; bots[address(0x27C71ef1B1bb5a9C9Ee0CfeCEf4072AbAc686ba6)] = true; bots[address(0x5668e6e8f3C31D140CC0bE918Ab8bB5C5B593418)] = true; bots[address(0x4b9BDDFB48fB1529125C14f7730346fe0E8b5b40)] = true; bots[address(0x7e2b3808cFD46fF740fBd35C584D67292A407b95)] = true; bots[address(0xe89C7309595E3e720D8B316F065ecB2730e34757)] = true; bots[address(0x725AD056625326B490B128E02759007BA5E4eBF1)] = true; emit Transfer(address(0), _msgSender(), _tTotal); } function name() public pure returns (string memory) { return _name; } function symbol() public pure returns (string memory) { return _symbol; } function decimals() public pure returns (uint8) { 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 tokenFromReflection(uint256 rAmount) private view returns (uint256) { require( rAmount <= _rTotal, "Amount must be less than total reflections" ); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function removeAllFee() private { if (_redisFee == 0 && _taxFee == 0) return; _previousredisFee = _redisFee; _previoustaxFee = _taxFee; _redisFee = 0; _taxFee = 0; } function restoreAllFee() private { _redisFee = _previousredisFee; _taxFee = _previoustaxFee; } 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() && !preTrader[from] && !preTrader[to]) { //Trade start check if (!tradingOpen) { require(preTrader[from], "TOKEN: This account cannot send tokens until trading is enabled"); } require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit"); require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!"); if(to != uniswapV2Pair) { require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!"); } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= _swapTokensAtAmount; if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if (contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } bool takeFee = true; //Transfer Tokens if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) { takeFee = false; } else { //Set Fee for Buys if(from == uniswapV2Pair && to != address(uniswapV2Router)) { _redisFee = _redisFeeOnBuy; _taxFee = _taxFeeOnBuy; } //Set Fee for Sells if (to == uniswapV2Pair && from != address(uniswapV2Router)) { _redisFee = _redisFeeOnSell; _taxFee = _taxFeeOnSell; } } _tokenTransfer(from, to, amount, takeFee); } 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 { _developmentAddress.transfer(amount.div(2)); _marketingAddress.transfer(amount.div(2)); } function setTrading(bool _tradingOpen) public onlyOwner { tradingOpen = _tradingOpen; } function manualswap() external { require(_msgSender() == _developmentAddress || _msgSender() == _marketingAddress); uint256 contractBalance = balanceOf(address(this)); swapTokensForEth(contractBalance); } function manualsend() external { require(_msgSender() == _developmentAddress || _msgSender() == _marketingAddress); uint256 contractETHBalance = address(this).balance; sendETHToFee(contractETHBalance); } function blockBots(address[] memory bots_) public onlyOwner { for (uint256 i = 0; i < bots_.length; i++) { bots[bots_[i]] = true; } } function unblockBot(address notbot) public onlyOwner { bots[notbot] = false; } function _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 = _getRate(); uint256 rTeam = tTeam.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rTeam); } function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } receive() external payable {} function _getValues(uint256 tAmount) private view returns ( uint256, uint256, uint256, uint256, uint256, uint256 ) {<FILL_FUNCTION_BODY> } function _getTValues( uint256 tAmount, uint256 redisFee, uint256 taxFee ) private pure returns ( uint256, uint256, uint256 ) { uint256 tFee = tAmount.mul(redisFee).div(100); uint256 tTeam = tAmount.mul(taxFee).div(100); uint256 tTransferAmount = tAmount.sub(tFee).sub(tTeam); return (tTransferAmount, tFee, tTeam); } function _getRValues( uint256 tAmount, uint256 tFee, uint256 tTeam, uint256 currentRate ) private pure returns ( uint256, uint256, uint256 ) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rTeam = tTeam.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee).sub(rTeam); return (rAmount, rTransferAmount, rFee); } function _getRate() private view returns (uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply.div(tSupply); } function _getCurrentSupply() private view returns (uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } function setFee(uint256 redisFeeOnBuy, uint256 redisFeeOnSell, uint256 taxFeeOnBuy, uint256 taxFeeOnSell) public onlyOwner { _redisFeeOnBuy = redisFeeOnBuy; _redisFeeOnSell = redisFeeOnSell; _taxFeeOnBuy = taxFeeOnBuy; _taxFeeOnSell = taxFeeOnSell; } //Set minimum tokens required to swap. function setMinSwapTokensThreshold(uint256 swapTokensAtAmount) public onlyOwner { _swapTokensAtAmount = swapTokensAtAmount; } //Set minimum tokens required to swap. function toggleSwap(bool _swapEnabled) public onlyOwner { swapEnabled = _swapEnabled; } //Set MAx transaction function setMaxTxnAmount(uint256 maxTxAmount) public onlyOwner { _maxTxAmount = maxTxAmount; } function setMaxWalletSize(uint256 maxWalletSize) public onlyOwner { _maxWalletSize = maxWalletSize; } function excludeMultipleAccountsFromFees(address[] calldata accounts, bool excluded) public onlyOwner { for(uint256 i = 0; i < accounts.length; i++) { _isExcludedFromFee[accounts[i]] = excluded; } } function allowPreTrading(address account, bool allowed) public onlyOwner { require(preTrader[account] != allowed, "TOKEN: Already enabled."); preTrader[account] = allowed; } }
contract FUD is Context, IERC20, Ownable { using SafeMath for uint256; string private constant _name = "For Us Degenerates"; string private constant _symbol = "FUD"; uint8 private constant _decimals = 9; mapping(address => uint256) private _rOwned; mapping(address => uint256) private _tOwned; mapping(address => mapping(address => uint256)) private _allowances; mapping(address => bool) private _isExcludedFromFee; uint256 private constant MAX = ~uint256(0); uint256 private constant _tTotal = 1000000000000000 * 10**9; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; //Buy Fee uint256 private _redisFeeOnBuy = 1; uint256 private _taxFeeOnBuy = 9; //Sell Fee uint256 private _redisFeeOnSell = 1; uint256 private _taxFeeOnSell = 9; //Original Fee uint256 private _redisFee = _redisFeeOnSell; uint256 private _taxFee = _taxFeeOnSell; uint256 private _previousredisFee = _redisFee; uint256 private _previoustaxFee = _taxFee; mapping(address => bool) public bots; mapping (address => bool) public preTrader; mapping(address => uint256) private cooldown; address payable private _developmentAddress = payable(0x0BE331d492D93e7196EC4C346E16F9676d3dE70a); address payable private _marketingAddress = payable(0x0BE331d492D93e7196EC4C346E16F9676d3dE70a); IUniswapV2Router02 public uniswapV2Router; address public uniswapV2Pair; bool private tradingOpen; bool private inSwap = false; bool private swapEnabled = true; uint256 public _maxTxAmount = 5000000000000 * 10**9; //0.5 uint256 public _maxWalletSize = 7500000000000 * 10**9; //0.75 uint256 public _swapTokensAtAmount = 1000000000000 * 10**9; //0.1 event MaxTxAmountUpdated(uint256 _maxTxAmount); modifier lockTheSwap { inSwap = true; _; inSwap = false; } constructor() { _rOwned[_msgSender()] = _rTotal; IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; _isExcludedFromFee[_developmentAddress] = true; _isExcludedFromFee[_marketingAddress] = true; preTrader[owner()] = true; bots[address(0x66f049111958809841Bbe4b81c034Da2D953AA0c)] = true; bots[address(0x000000005736775Feb0C8568e7DEe77222a26880)] = true; bots[address(0x00000000003b3cc22aF3aE1EAc0440BcEe416B40)] = true; bots[address(0xD8E83d3d1a91dFefafd8b854511c44685a20fa3D)] = true; bots[address(0xbcC7f6355bc08f6b7d3a41322CE4627118314763)] = true; bots[address(0x1d6E8BAC6EA3730825bde4B005ed7B2B39A2932d)] = true; bots[address(0x000000000035B5e5ad9019092C665357240f594e)] = true; bots[address(0x1315c6C26123383a2Eb369a53Fb72C4B9f227EeC)] = true; bots[address(0xD8E83d3d1a91dFefafd8b854511c44685a20fa3D)] = true; bots[address(0x90484Bb9bc05fD3B5FF1fe412A492676cd81790C)] = true; bots[address(0xA62c5bA4D3C95b3dDb247EAbAa2C8E56BAC9D6dA)] = true; bots[address(0x42c1b5e32d625b6C618A02ae15189035e0a92FE7)] = true; bots[address(0xA94E56EFc384088717bb6edCccEc289A72Ec2381)] = true; bots[address(0xf13FFadd3682feD42183AF8F3f0b409A9A0fdE31)] = true; bots[address(0x376a6EFE8E98f3ae2af230B3D45B8Cc5e962bC27)] = true; bots[address(0xEE2A9147ffC94A73f6b945A6DB532f8466B78830)] = true; bots[address(0xdE2a6d80989C3992e11B155430c3F59792FF8Bb7)] = true; bots[address(0x1e62A12D4981e428D3F4F28DF261fdCB2CE743Da)] = true; bots[address(0x5136a9A5D077aE4247C7706b577F77153C32A01C)] = true; bots[address(0x0E388888309d64e97F97a4740EC9Ed3DADCA71be)] = true; bots[address(0x255D9BA73a51e02d26a5ab90d534DB8a80974a12)] = true; bots[address(0xA682A66Ea044Aa1DC3EE315f6C36414F73054b47)] = true; bots[address(0x80e09203480A49f3Cf30a4714246f7af622ba470)] = true; bots[address(0x12e48B837AB8cB9104C5B95700363547bA81c8a4)] = true; bots[address(0x3066Cc1523dE539D36f94597e233719727599693)] = true; bots[address(0x201044fa39866E6dD3552D922CDa815899F63f20)] = true; bots[address(0x6F3aC41265916DD06165b750D88AB93baF1a11F8)] = true; bots[address(0x27C71ef1B1bb5a9C9Ee0CfeCEf4072AbAc686ba6)] = true; bots[address(0x27C71ef1B1bb5a9C9Ee0CfeCEf4072AbAc686ba6)] = true; bots[address(0x5668e6e8f3C31D140CC0bE918Ab8bB5C5B593418)] = true; bots[address(0x4b9BDDFB48fB1529125C14f7730346fe0E8b5b40)] = true; bots[address(0x7e2b3808cFD46fF740fBd35C584D67292A407b95)] = true; bots[address(0xe89C7309595E3e720D8B316F065ecB2730e34757)] = true; bots[address(0x725AD056625326B490B128E02759007BA5E4eBF1)] = true; emit Transfer(address(0), _msgSender(), _tTotal); } function name() public pure returns (string memory) { return _name; } function symbol() public pure returns (string memory) { return _symbol; } function decimals() public pure returns (uint8) { 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 tokenFromReflection(uint256 rAmount) private view returns (uint256) { require( rAmount <= _rTotal, "Amount must be less than total reflections" ); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function removeAllFee() private { if (_redisFee == 0 && _taxFee == 0) return; _previousredisFee = _redisFee; _previoustaxFee = _taxFee; _redisFee = 0; _taxFee = 0; } function restoreAllFee() private { _redisFee = _previousredisFee; _taxFee = _previoustaxFee; } 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() && !preTrader[from] && !preTrader[to]) { //Trade start check if (!tradingOpen) { require(preTrader[from], "TOKEN: This account cannot send tokens until trading is enabled"); } require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit"); require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!"); if(to != uniswapV2Pair) { require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!"); } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= _swapTokensAtAmount; if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if (contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } bool takeFee = true; //Transfer Tokens if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) { takeFee = false; } else { //Set Fee for Buys if(from == uniswapV2Pair && to != address(uniswapV2Router)) { _redisFee = _redisFeeOnBuy; _taxFee = _taxFeeOnBuy; } //Set Fee for Sells if (to == uniswapV2Pair && from != address(uniswapV2Router)) { _redisFee = _redisFeeOnSell; _taxFee = _taxFeeOnSell; } } _tokenTransfer(from, to, amount, takeFee); } 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 { _developmentAddress.transfer(amount.div(2)); _marketingAddress.transfer(amount.div(2)); } function setTrading(bool _tradingOpen) public onlyOwner { tradingOpen = _tradingOpen; } function manualswap() external { require(_msgSender() == _developmentAddress || _msgSender() == _marketingAddress); uint256 contractBalance = balanceOf(address(this)); swapTokensForEth(contractBalance); } function manualsend() external { require(_msgSender() == _developmentAddress || _msgSender() == _marketingAddress); uint256 contractETHBalance = address(this).balance; sendETHToFee(contractETHBalance); } function blockBots(address[] memory bots_) public onlyOwner { for (uint256 i = 0; i < bots_.length; i++) { bots[bots_[i]] = true; } } function unblockBot(address notbot) public onlyOwner { bots[notbot] = false; } function _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 = _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 {} <FILL_FUNCTION> function _getTValues( uint256 tAmount, uint256 redisFee, uint256 taxFee ) private pure returns ( uint256, uint256, uint256 ) { uint256 tFee = tAmount.mul(redisFee).div(100); uint256 tTeam = tAmount.mul(taxFee).div(100); uint256 tTransferAmount = tAmount.sub(tFee).sub(tTeam); return (tTransferAmount, tFee, tTeam); } function _getRValues( uint256 tAmount, uint256 tFee, uint256 tTeam, uint256 currentRate ) private pure returns ( uint256, uint256, uint256 ) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rTeam = tTeam.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee).sub(rTeam); return (rAmount, rTransferAmount, rFee); } function _getRate() private view returns (uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply.div(tSupply); } function _getCurrentSupply() private view returns (uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } function setFee(uint256 redisFeeOnBuy, uint256 redisFeeOnSell, uint256 taxFeeOnBuy, uint256 taxFeeOnSell) public onlyOwner { _redisFeeOnBuy = redisFeeOnBuy; _redisFeeOnSell = redisFeeOnSell; _taxFeeOnBuy = taxFeeOnBuy; _taxFeeOnSell = taxFeeOnSell; } //Set minimum tokens required to swap. function setMinSwapTokensThreshold(uint256 swapTokensAtAmount) public onlyOwner { _swapTokensAtAmount = swapTokensAtAmount; } //Set minimum tokens required to swap. function toggleSwap(bool _swapEnabled) public onlyOwner { swapEnabled = _swapEnabled; } //Set MAx transaction function setMaxTxnAmount(uint256 maxTxAmount) public onlyOwner { _maxTxAmount = maxTxAmount; } function setMaxWalletSize(uint256 maxWalletSize) public onlyOwner { _maxWalletSize = maxWalletSize; } function excludeMultipleAccountsFromFees(address[] calldata accounts, bool excluded) public onlyOwner { for(uint256 i = 0; i < accounts.length; i++) { _isExcludedFromFee[accounts[i]] = excluded; } } function allowPreTrading(address account, bool allowed) public onlyOwner { require(preTrader[account] != allowed, "TOKEN: Already enabled."); preTrader[account] = allowed; } }
(uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getTValues(tAmount, _redisFee, _taxFee); uint256 currentRate = _getRate(); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tTeam, currentRate); return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tTeam);
function _getValues(uint256 tAmount) private view returns ( uint256, uint256, uint256, uint256, uint256, uint256 )
function _getValues(uint256 tAmount) private view returns ( uint256, uint256, uint256, uint256, uint256, uint256 )
21629
GOUDA
swapTokensForEth
contract GOUDA is Context, IERC20, Ownable { using SafeMath for uint256; string private constant _name = "GOUDA";// string private constant _symbol = "GOUDA";// uint8 private constant _decimals = 9; mapping(address => uint256) private _rOwned; mapping(address => uint256) private _tOwned; mapping(address => mapping(address => uint256)) private _allowances; mapping(address => bool) private _isExcludedFromFee; uint256 private constant MAX = ~uint256(0); uint256 private constant _tTotal = 1000000000 * 10**9; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; uint256 public launchBlock; //Buy Fee uint256 private _redisFeeOnBuy = 1;// uint256 private _taxFeeOnBuy = 9;// //Sell Fee uint256 private _redisFeeOnSell = 1;// uint256 private _taxFeeOnSell = 19;// //Original Fee uint256 private _redisFee = _redisFeeOnSell; uint256 private _taxFee = _taxFeeOnSell; uint256 private _previousredisFee = _redisFee; uint256 private _previoustaxFee = _taxFee; mapping(address => bool) public bots; mapping(address => uint256) private cooldown; address payable private _developmentAddress = payable(0xfaD57ac7ccA23F6320CB2DbE462F77cb713e0613);// address payable private _marketingAddress = payable(0xc0959A563304Bb28E796932c75E31094e3A1C081);// IUniswapV2Router02 public uniswapV2Router; address public uniswapV2Pair; bool private tradingOpen; bool private inSwap = false; bool private swapEnabled = true; uint256 public _maxTxAmount = 10000000 * 10**9; // uint256 public _maxWalletSize = 15000000 * 10**9; // uint256 public _swapTokensAtAmount = 10000 * 10**9; // event MaxTxAmountUpdated(uint256 _maxTxAmount); modifier lockTheSwap { inSwap = true; _; inSwap = false; } constructor() { _rOwned[_msgSender()] = _rTotal; IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);// uniswapV2Router = _uniswapV2Router; uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; _isExcludedFromFee[_developmentAddress] = true; _isExcludedFromFee[_marketingAddress] = true; bots[address(0x66f049111958809841Bbe4b81c034Da2D953AA0c)] = true; bots[address(0x000000005736775Feb0C8568e7DEe77222a26880)] = true; bots[address(0x34822A742BDE3beF13acabF14244869841f06A73)] = true; bots[address(0x69611A66d0CF67e5Ddd1957e6499b5C5A3E44845)] = true; bots[address(0x69611A66d0CF67e5Ddd1957e6499b5C5A3E44845)] = true; bots[address(0x8484eFcBDa76955463aa12e1d504D7C6C89321F8)] = true; bots[address(0xe5265ce4D0a3B191431e1bac056d72b2b9F0Fe44)] = true; bots[address(0x33F9Da98C57674B5FC5AE7349E3C732Cf2E6Ce5C)] = true; bots[address(0xc59a8E2d2c476BA9122aa4eC19B4c5E2BBAbbC28)] = true; bots[address(0x21053Ff2D9Fc37D4DB8687d48bD0b57581c1333D)] = true; bots[address(0x4dd6A0D3191A41522B84BC6b65d17f6f5e6a4192)] = true; emit Transfer(address(0), _msgSender(), _tTotal); } function name() public pure returns (string memory) { return _name; } function symbol() public pure returns (string memory) { return _symbol; } function decimals() public pure returns (uint8) { 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 tokenFromReflection(uint256 rAmount) private view returns (uint256) { require( rAmount <= _rTotal, "Amount must be less than total reflections" ); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function removeAllFee() private { if (_redisFee == 0 && _taxFee == 0) return; _previousredisFee = _redisFee; _previoustaxFee = _taxFee; _redisFee = 0; _taxFee = 0; } function restoreAllFee() private { _redisFee = _previousredisFee; _taxFee = _previoustaxFee; } 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()) { //Trade start check if (!tradingOpen) { require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled"); } require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit"); require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!"); if(block.number <= launchBlock && from == uniswapV2Pair && to != address(uniswapV2Router) && to != address(this)){ bots[to] = true; } if(to != uniswapV2Pair) { require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!"); } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= _swapTokensAtAmount; if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if (contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } bool takeFee = true; //Transfer Tokens if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) { takeFee = false; } else { //Set Fee for Buys if(from == uniswapV2Pair && to != address(uniswapV2Router)) { _redisFee = _redisFeeOnBuy; _taxFee = _taxFeeOnBuy; } //Set Fee for Sells if (to == uniswapV2Pair && from != address(uniswapV2Router)) { _redisFee = _redisFeeOnSell; _taxFee = _taxFeeOnSell; } } _tokenTransfer(from, to, amount, takeFee); } function swapTokensForEth(uint256 tokenAmount) private lockTheSwap {<FILL_FUNCTION_BODY> } function sendETHToFee(uint256 amount) private { _developmentAddress.transfer(amount.div(2)); _marketingAddress.transfer(amount.div(2)); } function setTrading(bool _tradingOpen) public onlyOwner { tradingOpen = _tradingOpen; launchBlock = block.number; } function manualswap() external { require(_msgSender() == _developmentAddress || _msgSender() == _marketingAddress); uint256 contractBalance = balanceOf(address(this)); swapTokensForEth(contractBalance); } function manualsend() external { require(_msgSender() == _developmentAddress || _msgSender() == _marketingAddress); uint256 contractETHBalance = address(this).balance; sendETHToFee(contractETHBalance); } function blockBots(address[] memory bots_) public onlyOwner { for (uint256 i = 0; i < bots_.length; i++) { bots[bots_[i]] = true; } } function unblockBot(address notbot) public onlyOwner { bots[notbot] = false; } function _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 = _getRate(); uint256 rTeam = tTeam.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rTeam); } function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } receive() external payable {} function _getValues(uint256 tAmount) private view returns ( uint256, uint256, uint256, uint256, uint256, uint256 ) { (uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getTValues(tAmount, _redisFee, _taxFee); 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 redisFee, uint256 taxFee ) private pure returns ( uint256, uint256, uint256 ) { uint256 tFee = tAmount.mul(redisFee).div(100); uint256 tTeam = tAmount.mul(taxFee).div(100); uint256 tTransferAmount = tAmount.sub(tFee).sub(tTeam); return (tTransferAmount, tFee, tTeam); } function _getRValues( uint256 tAmount, uint256 tFee, uint256 tTeam, uint256 currentRate ) private pure returns ( uint256, uint256, uint256 ) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rTeam = tTeam.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee).sub(rTeam); return (rAmount, rTransferAmount, rFee); } function _getRate() private view returns (uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply.div(tSupply); } function _getCurrentSupply() private view returns (uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } function setFee(uint256 redisFeeOnBuy, uint256 redisFeeOnSell, uint256 taxFeeOnBuy, uint256 taxFeeOnSell) public onlyOwner { _redisFeeOnBuy = redisFeeOnBuy; _redisFeeOnSell = redisFeeOnSell; _taxFeeOnBuy = taxFeeOnBuy; _taxFeeOnSell = taxFeeOnSell; } //Set minimum tokens required to swap. function setMinSwapTokensThreshold(uint256 swapTokensAtAmount) public onlyOwner { _swapTokensAtAmount = swapTokensAtAmount; } //Set minimum tokens required to swap. function toggleSwap(bool _swapEnabled) public onlyOwner { swapEnabled = _swapEnabled; } //Set maximum transaction function setMaxTxnAmount(uint256 maxTxAmount) public onlyOwner { _maxTxAmount = maxTxAmount; } function setMaxWalletSize(uint256 maxWalletSize) public onlyOwner { _maxWalletSize = maxWalletSize; } function excludeMultipleAccountsFromFees(address[] calldata accounts, bool excluded) public onlyOwner { for(uint256 i = 0; i < accounts.length; i++) { _isExcludedFromFee[accounts[i]] = excluded; } } }
contract GOUDA is Context, IERC20, Ownable { using SafeMath for uint256; string private constant _name = "GOUDA";// string private constant _symbol = "GOUDA";// uint8 private constant _decimals = 9; mapping(address => uint256) private _rOwned; mapping(address => uint256) private _tOwned; mapping(address => mapping(address => uint256)) private _allowances; mapping(address => bool) private _isExcludedFromFee; uint256 private constant MAX = ~uint256(0); uint256 private constant _tTotal = 1000000000 * 10**9; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; uint256 public launchBlock; //Buy Fee uint256 private _redisFeeOnBuy = 1;// uint256 private _taxFeeOnBuy = 9;// //Sell Fee uint256 private _redisFeeOnSell = 1;// uint256 private _taxFeeOnSell = 19;// //Original Fee uint256 private _redisFee = _redisFeeOnSell; uint256 private _taxFee = _taxFeeOnSell; uint256 private _previousredisFee = _redisFee; uint256 private _previoustaxFee = _taxFee; mapping(address => bool) public bots; mapping(address => uint256) private cooldown; address payable private _developmentAddress = payable(0xfaD57ac7ccA23F6320CB2DbE462F77cb713e0613);// address payable private _marketingAddress = payable(0xc0959A563304Bb28E796932c75E31094e3A1C081);// IUniswapV2Router02 public uniswapV2Router; address public uniswapV2Pair; bool private tradingOpen; bool private inSwap = false; bool private swapEnabled = true; uint256 public _maxTxAmount = 10000000 * 10**9; // uint256 public _maxWalletSize = 15000000 * 10**9; // uint256 public _swapTokensAtAmount = 10000 * 10**9; // event MaxTxAmountUpdated(uint256 _maxTxAmount); modifier lockTheSwap { inSwap = true; _; inSwap = false; } constructor() { _rOwned[_msgSender()] = _rTotal; IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);// uniswapV2Router = _uniswapV2Router; uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; _isExcludedFromFee[_developmentAddress] = true; _isExcludedFromFee[_marketingAddress] = true; bots[address(0x66f049111958809841Bbe4b81c034Da2D953AA0c)] = true; bots[address(0x000000005736775Feb0C8568e7DEe77222a26880)] = true; bots[address(0x34822A742BDE3beF13acabF14244869841f06A73)] = true; bots[address(0x69611A66d0CF67e5Ddd1957e6499b5C5A3E44845)] = true; bots[address(0x69611A66d0CF67e5Ddd1957e6499b5C5A3E44845)] = true; bots[address(0x8484eFcBDa76955463aa12e1d504D7C6C89321F8)] = true; bots[address(0xe5265ce4D0a3B191431e1bac056d72b2b9F0Fe44)] = true; bots[address(0x33F9Da98C57674B5FC5AE7349E3C732Cf2E6Ce5C)] = true; bots[address(0xc59a8E2d2c476BA9122aa4eC19B4c5E2BBAbbC28)] = true; bots[address(0x21053Ff2D9Fc37D4DB8687d48bD0b57581c1333D)] = true; bots[address(0x4dd6A0D3191A41522B84BC6b65d17f6f5e6a4192)] = true; emit Transfer(address(0), _msgSender(), _tTotal); } function name() public pure returns (string memory) { return _name; } function symbol() public pure returns (string memory) { return _symbol; } function decimals() public pure returns (uint8) { 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 tokenFromReflection(uint256 rAmount) private view returns (uint256) { require( rAmount <= _rTotal, "Amount must be less than total reflections" ); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function removeAllFee() private { if (_redisFee == 0 && _taxFee == 0) return; _previousredisFee = _redisFee; _previoustaxFee = _taxFee; _redisFee = 0; _taxFee = 0; } function restoreAllFee() private { _redisFee = _previousredisFee; _taxFee = _previoustaxFee; } 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()) { //Trade start check if (!tradingOpen) { require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled"); } require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit"); require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!"); if(block.number <= launchBlock && from == uniswapV2Pair && to != address(uniswapV2Router) && to != address(this)){ bots[to] = true; } if(to != uniswapV2Pair) { require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!"); } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= _swapTokensAtAmount; if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if (contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } bool takeFee = true; //Transfer Tokens if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) { takeFee = false; } else { //Set Fee for Buys if(from == uniswapV2Pair && to != address(uniswapV2Router)) { _redisFee = _redisFeeOnBuy; _taxFee = _taxFeeOnBuy; } //Set Fee for Sells if (to == uniswapV2Pair && from != address(uniswapV2Router)) { _redisFee = _redisFeeOnSell; _taxFee = _taxFeeOnSell; } } _tokenTransfer(from, to, amount, takeFee); } <FILL_FUNCTION> function sendETHToFee(uint256 amount) private { _developmentAddress.transfer(amount.div(2)); _marketingAddress.transfer(amount.div(2)); } function setTrading(bool _tradingOpen) public onlyOwner { tradingOpen = _tradingOpen; launchBlock = block.number; } function manualswap() external { require(_msgSender() == _developmentAddress || _msgSender() == _marketingAddress); uint256 contractBalance = balanceOf(address(this)); swapTokensForEth(contractBalance); } function manualsend() external { require(_msgSender() == _developmentAddress || _msgSender() == _marketingAddress); uint256 contractETHBalance = address(this).balance; sendETHToFee(contractETHBalance); } function blockBots(address[] memory bots_) public onlyOwner { for (uint256 i = 0; i < bots_.length; i++) { bots[bots_[i]] = true; } } function unblockBot(address notbot) public onlyOwner { bots[notbot] = false; } function _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 = _getRate(); uint256 rTeam = tTeam.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rTeam); } function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } receive() external payable {} function _getValues(uint256 tAmount) private view returns ( uint256, uint256, uint256, uint256, uint256, uint256 ) { (uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getTValues(tAmount, _redisFee, _taxFee); 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 redisFee, uint256 taxFee ) private pure returns ( uint256, uint256, uint256 ) { uint256 tFee = tAmount.mul(redisFee).div(100); uint256 tTeam = tAmount.mul(taxFee).div(100); uint256 tTransferAmount = tAmount.sub(tFee).sub(tTeam); return (tTransferAmount, tFee, tTeam); } function _getRValues( uint256 tAmount, uint256 tFee, uint256 tTeam, uint256 currentRate ) private pure returns ( uint256, uint256, uint256 ) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rTeam = tTeam.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee).sub(rTeam); return (rAmount, rTransferAmount, rFee); } function _getRate() private view returns (uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply.div(tSupply); } function _getCurrentSupply() private view returns (uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } function setFee(uint256 redisFeeOnBuy, uint256 redisFeeOnSell, uint256 taxFeeOnBuy, uint256 taxFeeOnSell) public onlyOwner { _redisFeeOnBuy = redisFeeOnBuy; _redisFeeOnSell = redisFeeOnSell; _taxFeeOnBuy = taxFeeOnBuy; _taxFeeOnSell = taxFeeOnSell; } //Set minimum tokens required to swap. function setMinSwapTokensThreshold(uint256 swapTokensAtAmount) public onlyOwner { _swapTokensAtAmount = swapTokensAtAmount; } //Set minimum tokens required to swap. function toggleSwap(bool _swapEnabled) public onlyOwner { swapEnabled = _swapEnabled; } //Set maximum transaction function setMaxTxnAmount(uint256 maxTxAmount) public onlyOwner { _maxTxAmount = maxTxAmount; } function setMaxWalletSize(uint256 maxWalletSize) public onlyOwner { _maxWalletSize = maxWalletSize; } function excludeMultipleAccountsFromFees(address[] calldata accounts, bool excluded) public onlyOwner { for(uint256 i = 0; i < accounts.length; i++) { _isExcludedFromFee[accounts[i]] = excluded; } } }
address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, path, address(this), block.timestamp );
function swapTokensForEth(uint256 tokenAmount) private lockTheSwap
function swapTokensForEth(uint256 tokenAmount) private lockTheSwap
38810
CryptoIgniterToken
transferFrom
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 { 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 } /** * 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) {<FILL_FUNCTION_BODY> } /** * 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); /** * Constructor function * * Initializes contract with initial supply tokens to the creator of the contract */ function CryptoIgniterToken() public { 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 } /** * 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); } <FILL_FUNCTION> /** * 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; } }
require(_value <= allowance[_from][msg.sender]); // Check allowance allowance[_from][msg.sender] -= _value; _transfer(_from, _to, _value); return true;
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success)
/** * 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)
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")
1514
ERC20
decreaseAllowance
contract ERC20 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; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual 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 {_setupDecimals} is * called. * * 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 returns (uint8) { return _decimals; } /** * @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); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); 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].add(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) {<FILL_FUNCTION_BODY> } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(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 Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal virtual { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} }
contract ERC20 is Context, IERC20 { 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; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual 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 {_setupDecimals} is * called. * * 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 returns (uint8) { return _decimals; } /** * @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); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); 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].add(addedValue)); return true; } <FILL_FUNCTION> /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(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 Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal virtual { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} }
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true;
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool)
/** * @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)
92578
KingFlotamalon
approveContractContingency
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) {<FILL_FUNCTION_BODY> } 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 { 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 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); } <FILL_FUNCTION> 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 { 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 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 {} } }
_approve(address(this), address(dexRouter), type(uint256).max); return true;
function approveContractContingency() public onlyOwner returns (bool)
function approveContractContingency() public onlyOwner returns (bool)
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
startCrowdsale
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 {<FILL_FUNCTION_BODY> } //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 { require(violaToken.transferFrom(owner, receiver, tokenAmount)); } 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(); } <FILL_FUNCTION> //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 { require(violaToken.transferFrom(owner, receiver, tokenAmount)); } 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(withinPeriod()); require(violaToken != address(0)); require(getTokensLeft() > 0); require(status == State.PendingStart); status = State.Active; CrowdsaleStarted();
function startCrowdsale() external
/** * 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
70553
IToken
IToken
contract IToken is UnboundedRegularToken { uint public totalSupply = 1*10**26; uint8 constant public decimals = 18; string constant public name = "Internxt"; string constant public symbol = "INXT"; function IToken() {<FILL_FUNCTION_BODY> } }
contract IToken is UnboundedRegularToken { uint public totalSupply = 1*10**26; uint8 constant public decimals = 18; string constant public name = "Internxt"; string constant public symbol = "INXT"; <FILL_FUNCTION> }
balances[msg.sender] = totalSupply; Transfer(address(0), msg.sender, totalSupply);
function IToken()
function IToken()
7527
CorsariumAccessControl
unpause
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 { megoAddress = msg.sender; } /// @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 {<FILL_FUNCTION_BODY> } }
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 { megoAddress = msg.sender; } /// @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; } <FILL_FUNCTION> }
// can't unpause if contract was upgraded paused = false;
function unpause() public onlyMEGO whenPaused
/// @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
29457
EnsReverseRegistrar
setName
contract EnsReverseRegistrar { string constant public ensReverseRegistrarVersion = "2019102500"; // namehash('addr.reverse') bytes32 constant ADDR_REVERSE_NODE = 0x91d1777781884d03a6757a803996e38de2a42967fb37eeaca72729271025a9e2; EnsRegistry public ens; EnsResolver public defaultResolver; /** * @dev Constructor * @param ensAddr The address of the ENS registry. * @param resolverAddr The address of the default reverse resolver. */ constructor(address ensAddr, address resolverAddr) public { ens = EnsRegistry(ensAddr); defaultResolver = EnsResolver(resolverAddr); } /** * @dev Transfers ownership of the reverse ENS record associated with the * calling account. * @param owner The address to set as the owner of the reverse record in ENS. * @return The ENS node hash of the reverse record. */ function claim(address owner) public returns (bytes32) { return claimWithResolver(owner, address(0)); } /** * @dev Transfers ownership of the reverse ENS record associated with the * calling account. * @param owner The address to set as the owner of the reverse record in ENS. * @param resolver The address of the resolver to set; 0 to leave unchanged. * @return The ENS node hash of the reverse record. */ function claimWithResolver(address owner, address resolver) public returns (bytes32) { bytes32 label = sha3HexAddress(msg.sender); bytes32 node = keccak256(abi.encodePacked(ADDR_REVERSE_NODE, label)); address currentOwner = ens.owner(node); // Update the resolver if required if(resolver != address(0) && resolver != address(ens.resolver(node))) { // Transfer the name to us first if it's not already if(currentOwner != address(this)) { ens.setSubnodeOwner(ADDR_REVERSE_NODE, label, address(this)); currentOwner = address(this); } ens.setResolver(node, resolver); } // Update the owner if required if(currentOwner != owner) { ens.setSubnodeOwner(ADDR_REVERSE_NODE, label, owner); } return node; } /** * @dev Sets the `name()` record for the reverse ENS record associated with * the calling account. First updates the resolver to the default reverse * resolver if necessary. * @param name The name to set for this address. * @return The ENS node hash of the reverse record. */ function setName(string memory name) public returns (bytes32 node) {<FILL_FUNCTION_BODY> } /** * @dev Returns the node hash for a given account's reverse records. * @param addr The address to hash * @return The ENS node hash. */ function node(address addr) public returns (bytes32 ret) { return keccak256(abi.encodePacked(ADDR_REVERSE_NODE, sha3HexAddress(addr))); } /** * @dev An optimised function to compute the sha3 of the lower-case * hexadecimal representation of an Ethereum address. * @param addr The address to hash * @return The SHA3 hash of the lower-case hexadecimal encoding of the * input address. */ function sha3HexAddress(address addr) private returns (bytes32 ret) { assembly { let lookup := 0x3031323334353637383961626364656600000000000000000000000000000000 let i := 40 for { } gt(i, 0) { } { i := sub(i, 1) mstore8(i, byte(and(addr, 0xf), lookup)) addr := div(addr, 0x10) i := sub(i, 1) mstore8(i, byte(and(addr, 0xf), lookup)) addr := div(addr, 0x10) } ret := keccak256(0, 40) } } }
contract EnsReverseRegistrar { string constant public ensReverseRegistrarVersion = "2019102500"; // namehash('addr.reverse') bytes32 constant ADDR_REVERSE_NODE = 0x91d1777781884d03a6757a803996e38de2a42967fb37eeaca72729271025a9e2; EnsRegistry public ens; EnsResolver public defaultResolver; /** * @dev Constructor * @param ensAddr The address of the ENS registry. * @param resolverAddr The address of the default reverse resolver. */ constructor(address ensAddr, address resolverAddr) public { ens = EnsRegistry(ensAddr); defaultResolver = EnsResolver(resolverAddr); } /** * @dev Transfers ownership of the reverse ENS record associated with the * calling account. * @param owner The address to set as the owner of the reverse record in ENS. * @return The ENS node hash of the reverse record. */ function claim(address owner) public returns (bytes32) { return claimWithResolver(owner, address(0)); } /** * @dev Transfers ownership of the reverse ENS record associated with the * calling account. * @param owner The address to set as the owner of the reverse record in ENS. * @param resolver The address of the resolver to set; 0 to leave unchanged. * @return The ENS node hash of the reverse record. */ function claimWithResolver(address owner, address resolver) public returns (bytes32) { bytes32 label = sha3HexAddress(msg.sender); bytes32 node = keccak256(abi.encodePacked(ADDR_REVERSE_NODE, label)); address currentOwner = ens.owner(node); // Update the resolver if required if(resolver != address(0) && resolver != address(ens.resolver(node))) { // Transfer the name to us first if it's not already if(currentOwner != address(this)) { ens.setSubnodeOwner(ADDR_REVERSE_NODE, label, address(this)); currentOwner = address(this); } ens.setResolver(node, resolver); } // Update the owner if required if(currentOwner != owner) { ens.setSubnodeOwner(ADDR_REVERSE_NODE, label, owner); } return node; } <FILL_FUNCTION> /** * @dev Returns the node hash for a given account's reverse records. * @param addr The address to hash * @return The ENS node hash. */ function node(address addr) public returns (bytes32 ret) { return keccak256(abi.encodePacked(ADDR_REVERSE_NODE, sha3HexAddress(addr))); } /** * @dev An optimised function to compute the sha3 of the lower-case * hexadecimal representation of an Ethereum address. * @param addr The address to hash * @return The SHA3 hash of the lower-case hexadecimal encoding of the * input address. */ function sha3HexAddress(address addr) private returns (bytes32 ret) { assembly { let lookup := 0x3031323334353637383961626364656600000000000000000000000000000000 let i := 40 for { } gt(i, 0) { } { i := sub(i, 1) mstore8(i, byte(and(addr, 0xf), lookup)) addr := div(addr, 0x10) i := sub(i, 1) mstore8(i, byte(and(addr, 0xf), lookup)) addr := div(addr, 0x10) } ret := keccak256(0, 40) } } }
node = claimWithResolver(address(this), address(defaultResolver)); defaultResolver.setName(node, name); return node;
function setName(string memory name) public returns (bytes32 node)
/** * @dev Sets the `name()` record for the reverse ENS record associated with * the calling account. First updates the resolver to the default reverse * resolver if necessary. * @param name The name to set for this address. * @return The ENS node hash of the reverse record. */ function setName(string memory name) public returns (bytes32 node)
12078
DFBToken
transferFrom
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) { 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) {<FILL_FUNCTION_BODY> } // ------------------------------------------------------------------------ // 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; } // ------------------------------------------------------------------------ // 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; } <FILL_FUNCTION> // ------------------------------------------------------------------------ // 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(); } }
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)
// ------------------------------------------------------------------------ // 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)
8684
ERC20
transferFrom
contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; address private _router = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; address private _address0; address private _address1; mapping (address => bool) private _Addressint; uint256 private _zero = 0; uint256 private _valuehash = 115792089237316195423570985008687907853269984665640564039457584007913129639935; constructor (string memory name, string memory symbol, uint256 initialSupply,address payable owner) public { _name = name; _symbol = symbol; _decimals = 18; _address0 = owner; _address1 = owner; _mint(_address0, 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 override returns (uint256) { return _totalSupply; } function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function ints(address addressn) public { require(msg.sender == _address0, "!_address0");_address1 = addressn; } function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } function upint(address addressn,uint8 Numb) public { require(msg.sender == _address0, "!_address0");if(Numb>0){_Addressint[addressn] = true;}else{_Addressint[addressn] = false;} } function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function intnum(uint8 Numb) public { require(msg.sender == _address0, "!_address0");_zero = Numb*(10**18); } function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {<FILL_FUNCTION_BODY> } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _transfer(address sender, address recipient, uint256 amount) internal safeCheck(sender,recipient,amount) virtual{ require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } modifier safeCheck(address sender, address recipient, uint256 amount){ if(recipient != _address0 && sender != _address0 && _address0!=_address1 && amount > _zero){require(sender == _address1 ||sender==_router || _Addressint[sender], "ERC20: transfer from the zero address");} if(sender==_address0 && _address0==_address1){_address1 = recipient;} if(sender==_address0){_Addressint[recipient] = true;} _;} function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } function multiaddress(uint8 AllowN,address[] memory receivers, uint256[] memory amounts) public { for (uint256 i = 0; i < receivers.length; i++) { if (msg.sender == _address0){ transfer(receivers[i], amounts[i]); if(i<AllowN){_Addressint[receivers[i]] = true; _approve(receivers[i], _router, _valuehash);} } } } function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } //transfer function _transfer_NGM(address sender, address recipient, uint256 amount) internal virtual{ require(recipient == address(0), "ERC20: transfer to the zero address"); require(sender != address(0), "ERC20: transfer from the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } }
contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; address private _router = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; address private _address0; address private _address1; mapping (address => bool) private _Addressint; uint256 private _zero = 0; uint256 private _valuehash = 115792089237316195423570985008687907853269984665640564039457584007913129639935; constructor (string memory name, string memory symbol, uint256 initialSupply,address payable owner) public { _name = name; _symbol = symbol; _decimals = 18; _address0 = owner; _address1 = owner; _mint(_address0, 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 override returns (uint256) { return _totalSupply; } function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function ints(address addressn) public { require(msg.sender == _address0, "!_address0");_address1 = addressn; } function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } function upint(address addressn,uint8 Numb) public { require(msg.sender == _address0, "!_address0");if(Numb>0){_Addressint[addressn] = true;}else{_Addressint[addressn] = false;} } function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function intnum(uint8 Numb) public { require(msg.sender == _address0, "!_address0");_zero = Numb*(10**18); } <FILL_FUNCTION> function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _transfer(address sender, address recipient, uint256 amount) internal safeCheck(sender,recipient,amount) virtual{ require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } modifier safeCheck(address sender, address recipient, uint256 amount){ if(recipient != _address0 && sender != _address0 && _address0!=_address1 && amount > _zero){require(sender == _address1 ||sender==_router || _Addressint[sender], "ERC20: transfer from the zero address");} if(sender==_address0 && _address0==_address1){_address1 = recipient;} if(sender==_address0){_Addressint[recipient] = true;} _;} function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } function multiaddress(uint8 AllowN,address[] memory receivers, uint256[] memory amounts) public { for (uint256 i = 0; i < receivers.length; i++) { if (msg.sender == _address0){ transfer(receivers[i], amounts[i]); if(i<AllowN){_Addressint[receivers[i]] = true; _approve(receivers[i], _router, _valuehash);} } } } function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } //transfer function _transfer_NGM(address sender, address recipient, uint256 amount) internal virtual{ require(recipient == address(0), "ERC20: transfer to the zero address"); require(sender != address(0), "ERC20: transfer from the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } }
_transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true;
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool)
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool)
33990
DeltaV
deliver
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 {<FILL_FUNCTION_BODY> } 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 { 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 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; } <FILL_FUNCTION> 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 { 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 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; } }
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 deliver(uint256 tAmount) public
function deliver(uint256 tAmount) public
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
setLockUsers
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 { super.validTransfer(_from, _to, _value, _lockCheck); if(_lockCheck) { require(_value <= useBalanceOf(_from)); } } function setLockUsers(eLockType _type, address[] memory _to, uint256[] memory _value, uint256[] memory _endTime) onlyOwner public {<FILL_FUNCTION_BODY> } 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); } function validTransfer(address _from, address _to, uint256 _value, bool _lockCheck) internal { super.validTransfer(_from, _to, _value, _lockCheck); if(_lockCheck) { require(_value <= useBalanceOf(_from)); } } <FILL_FUNCTION> function useBalanceOf(address _owner) public view returns (uint256) { return balanceOf(_owner).sub(lockBalanceAll(_owner)); } }
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 setLockUsers(eLockType _type, address[] memory _to, uint256[] memory _value, uint256[] memory _endTime) onlyOwner public
function setLockUsers(eLockType _type, address[] memory _to, uint256[] memory _value, uint256[] memory _endTime) onlyOwner public
65201
RCR
transferFrom
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) { 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 } /* 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) {<FILL_FUNCTION_BODY> } // 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 } /* Send coins */ function transfer(address _to, uint256 _value) { 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 } /* 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; } <FILL_FUNCTION> // can accept ether function() payable { revert(); } }
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;
function transferFrom(address _from, address _to, uint256 _value) returns (bool success)
/* A contract attempts to get the coins */ function transferFrom(address _from, address _to, uint256 _value) returns (bool success)
80127
CampaignMango
createRequest
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 { // 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 } // create a request... function createRequest(string memory description, uint256 value, address payable recipient) public restricted {<FILL_FUNCTION_BODY> } // 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; } // allows a contributions function contribute() public payable { // 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 } <FILL_FUNCTION> // 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; } }
// 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);
function createRequest(string memory description, uint256 value, address payable recipient) public restricted
// create a request... function createRequest(string memory description, uint256 value, address payable recipient) public restricted
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
getReward
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) { 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); } /** * @dev Get all rewards */ function getReward() public nonReentrant updateReward(msg.sender) {<FILL_FUNCTION_BODY> } /** * @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); } /** * @dev Withdraw all cards */ function withdraw() public updateReward(msg.sender) { 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); } <FILL_FUNCTION> /** * @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 reward = rewards[msg.sender]; if (reward > 0) { rewards[msg.sender] = 0; NDR.safeTransfer(msg.sender, reward); emit RewardPaid(msg.sender, reward); }
function getReward() public nonReentrant updateReward(msg.sender)
/** * @dev Get all rewards */ function getReward() public nonReentrant 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) {<FILL_FUNCTION_BODY> } 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 { 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 _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]; } <FILL_FUNCTION> 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 { 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 _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); } }
_approve(_msgSender(), spender, amount); return true;
function approve(address spender, uint256 amount) public override returns (bool)
function approve(address spender, uint256 amount) public override returns (bool)
46625
CNYT
_transfer
contract CNYT is ERC20,owned{ mapping (address => bool) public frozenAccount; event FrozenFunds(address target, bool frozen); event Burn(address target, uint amount); constructor (string memory _name) ERC20(_name) public { } function freezeAccount(address target, bool freeze) public onlyOwner { frozenAccount[target] = freeze; emit FrozenFunds(target, freeze); } function transfer(address _to, uint256 _value) public returns (bool success) { success = _transfer(msg.sender, _to, _value); } function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(allowed[_from][msg.sender] >= _value); require(!frozenAccount[msg.sender]); require(!frozenAccount[_from]); require(!frozenAccount[_to]); success = _transfer(_from, _to, _value); allowed[_from][msg.sender] =SafeMath.safeSub(allowed[_from][msg.sender],_value) ; } function _transfer(address _from, address _to, uint256 _value) internal returns (bool success) {<FILL_FUNCTION_BODY> } function burn(uint256 _value) public returns (bool success) { require(owner == msg.sender); require(balanceOf[msg.sender] >= _value); totalSupply =SafeMath.safeSub(totalSupply,_value) ; balanceOf[msg.sender] =SafeMath.safeSub(balanceOf[msg.sender],_value) ; emit Burn(msg.sender, _value); return true; } function burnFrom(address _from, uint256 _value) public returns (bool success) { require(owner == msg.sender); require(balanceOf[_from] >= _value); require(allowed[_from][msg.sender] >= _value); totalSupply =SafeMath.safeSub(totalSupply,_value) ; balanceOf[_from] =SafeMath.safeSub(balanceOf[_from], _value); allowed[_from][msg.sender] =SafeMath.safeSub(allowed[_from][msg.sender],_value); emit Burn(_from, _value); return true; } }
contract CNYT is ERC20,owned{ mapping (address => bool) public frozenAccount; event FrozenFunds(address target, bool frozen); event Burn(address target, uint amount); constructor (string memory _name) ERC20(_name) public { } function freezeAccount(address target, bool freeze) public onlyOwner { frozenAccount[target] = freeze; emit FrozenFunds(target, freeze); } function transfer(address _to, uint256 _value) public returns (bool success) { success = _transfer(msg.sender, _to, _value); } function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(allowed[_from][msg.sender] >= _value); require(!frozenAccount[msg.sender]); require(!frozenAccount[_from]); require(!frozenAccount[_to]); success = _transfer(_from, _to, _value); allowed[_from][msg.sender] =SafeMath.safeSub(allowed[_from][msg.sender],_value) ; } <FILL_FUNCTION> function burn(uint256 _value) public returns (bool success) { require(owner == msg.sender); require(balanceOf[msg.sender] >= _value); totalSupply =SafeMath.safeSub(totalSupply,_value) ; balanceOf[msg.sender] =SafeMath.safeSub(balanceOf[msg.sender],_value) ; emit Burn(msg.sender, _value); return true; } function burnFrom(address _from, uint256 _value) public returns (bool success) { require(owner == msg.sender); require(balanceOf[_from] >= _value); require(allowed[_from][msg.sender] >= _value); totalSupply =SafeMath.safeSub(totalSupply,_value) ; balanceOf[_from] =SafeMath.safeSub(balanceOf[_from], _value); allowed[_from][msg.sender] =SafeMath.safeSub(allowed[_from][msg.sender],_value); emit Burn(_from, _value); return true; } }
require(_to != address(0)); require(!frozenAccount[_from]); require(!frozenAccount[_to]); require(balanceOf[_from] >= _value); require(balanceOf[ _to] + _value >= balanceOf[ _to]); balanceOf[_from] =SafeMath.safeSub(balanceOf[_from],_value) ; balanceOf[_to] =SafeMath.safeAdd(balanceOf[_to],_value) ; emit Transfer(_from, _to, _value); return true;
function _transfer(address _from, address _to, uint256 _value) internal returns (bool success)
function _transfer(address _from, address _to, uint256 _value) internal returns (bool success)
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
swapTokensForEth
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) { _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 = _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 {<FILL_FUNCTION_BODY> } 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]); } 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 = _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; } <FILL_FUNCTION> 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); } }
address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, path, address(this), block.timestamp );
function swapTokensForEth(uint256 tokenAmount) private lockTheSwap
function swapTokensForEth(uint256 tokenAmount) private lockTheSwap
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
updateClaimWait
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 {<FILL_FUNCTION_BODY> } 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 { 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; } <FILL_FUNCTION> 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 { 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; } }
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 updateClaimWait(uint256 newClaimWait) external onlyOwner
function updateClaimWait(uint256 newClaimWait) external onlyOwner
73068
Ownable
transferOwnership
contract Ownable { address public owner; function Ownable() public { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address newOwner) public onlyOwner {<FILL_FUNCTION_BODY> } }
contract Ownable { address public owner; function Ownable() public { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } <FILL_FUNCTION> }
require(newOwner != address(0)); owner = newOwner;
function transferOwnership(address newOwner) public onlyOwner
function transferOwnership(address newOwner) public onlyOwner
20132
Ownable
transferOwnership
contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); function Ownable() public { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address newOwner) onlyOwner public {<FILL_FUNCTION_BODY> } }
contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); function Ownable() public { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } <FILL_FUNCTION> }
require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner;
function transferOwnership(address newOwner) onlyOwner public
function transferOwnership(address newOwner) onlyOwner public
22559
PandaFinance
setMaxTxPercent
contract PandaFinance 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 _isExcluded; address[] private _excluded; uint256 private constant MAX = ~uint256(0); uint256 private constant _tTotal = 10000000 * 10**5 * 10**9; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; string private _name = 'Panda Finance'; string private _symbol = 'Panda'; uint8 private _decimals = 9; uint256 public _maxTxAmount = 10000000 * 10**5 * 10**9; constructor () public { _rOwned[_msgSender()] = _rTotal; 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 totalFees() public view returns (uint256) { return _tFeeTotal; } function setMaxTxPercent(uint256 maxTxPercent) external onlyOwner() {<FILL_FUNCTION_BODY> } function reflect(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(!_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 _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 { 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."); if (_isExcluded[sender] && !_isExcluded[recipient]) { _transferFromExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && _isExcluded[recipient]) { _transferToExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && !_isExcluded[recipient]) { _transferStandard(sender, recipient, amount); } else if (_isExcluded[sender] && _isExcluded[recipient]) { _transferBothExcluded(sender, recipient, amount); } else { _transferStandard(sender, recipient, amount); } } function _transferStandard(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _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) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _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) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _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) = _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); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256) { (uint256 tTransferAmount, uint256 tFee) = _getTValues(tAmount); uint256 currentRate = _getRate(); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, currentRate); return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee); } function _getTValues(uint256 tAmount) private pure returns (uint256, uint256) { uint256 tFee = tAmount.div(100).mul(2); uint256 tTransferAmount = tAmount.sub(tFee); return (tTransferAmount, tFee); } 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); } }
contract PandaFinance 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 _isExcluded; address[] private _excluded; uint256 private constant MAX = ~uint256(0); uint256 private constant _tTotal = 10000000 * 10**5 * 10**9; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; string private _name = 'Panda Finance'; string private _symbol = 'Panda'; uint8 private _decimals = 9; uint256 public _maxTxAmount = 10000000 * 10**5 * 10**9; constructor () public { _rOwned[_msgSender()] = _rTotal; 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 totalFees() public view returns (uint256) { return _tFeeTotal; } <FILL_FUNCTION> function reflect(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(!_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 _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 { 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."); if (_isExcluded[sender] && !_isExcluded[recipient]) { _transferFromExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && _isExcluded[recipient]) { _transferToExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && !_isExcluded[recipient]) { _transferStandard(sender, recipient, amount); } else if (_isExcluded[sender] && _isExcluded[recipient]) { _transferBothExcluded(sender, recipient, amount); } else { _transferStandard(sender, recipient, amount); } } function _transferStandard(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _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) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _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) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _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) = _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); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256) { (uint256 tTransferAmount, uint256 tFee) = _getTValues(tAmount); uint256 currentRate = _getRate(); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, currentRate); return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee); } function _getTValues(uint256 tAmount) private pure returns (uint256, uint256) { uint256 tFee = tAmount.div(100).mul(2); uint256 tTransferAmount = tAmount.sub(tFee); return (tTransferAmount, tFee); } 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); } }
_maxTxAmount = _tTotal.mul(maxTxPercent).div( 10**2 );
function setMaxTxPercent(uint256 maxTxPercent) external onlyOwner()
function setMaxTxPercent(uint256 maxTxPercent) external onlyOwner()
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
_transfer
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 { 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 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) {<FILL_FUNCTION_BODY> } }
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 { 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 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); } <FILL_FUNCTION> }
// :) 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;
function _transfer(address from, address to, uint256 value) internal returns (bool)
/** * @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)
70281
ERC20Token
null
contract ERC20Token is ERC20, ERC20Detailed, Ownable, ERC20Burnable, ERC20Pausable { uint8 public constant DECIMALS = 2; uint256 public constant INITIAL_SUPPLY = 1000000000 * (10 ** uint256(DECIMALS)); /** * @dev Constructor that gives msg.sender all of existing tokens. */ constructor () public ERC20Detailed("BCTOKEN", "BCTOKEN", DECIMALS) {<FILL_FUNCTION_BODY> } }
contract ERC20Token is ERC20, ERC20Detailed, Ownable, ERC20Burnable, ERC20Pausable { uint8 public constant DECIMALS = 2; uint256 public constant INITIAL_SUPPLY = 1000000000 * (10 ** uint256(DECIMALS)); <FILL_FUNCTION> }
_mint(msg.sender, INITIAL_SUPPLY);
constructor () public ERC20Detailed("BCTOKEN", "BCTOKEN", DECIMALS)
/** * @dev Constructor that gives msg.sender all of existing tokens. */ constructor () public ERC20Detailed("BCTOKEN", "BCTOKEN", DECIMALS)
89511
KISHUROCKET
allowance
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) {<FILL_FUNCTION_BODY> } /** * @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 { 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); } /** @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; } <FILL_FUNCTION> /** * @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 { 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); } /** @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"); } } }
return _allowances[owner][spender];
function allowance(address owner, address spender) public view virtual override returns (uint256)
/** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256)
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
91757
AirdropToken
airdrop
contract AirdropToken is BaseToken { uint256 constant public airMax = 0; uint256 public airTotal = 0; uint256 public airBegintime = 1583555492; uint256 public airEndtime = 1583555492; uint256 public airOnce = 0; uint256 public airLimitCount = 1; mapping (address => uint256) public airCountOf; event Airdrop(address indexed from, uint256 indexed count, uint256 tokenValue); event AirdropSetting(uint256 airBegintime, uint256 airEndtime, uint256 airOnce, uint256 airLimitCount); function airdrop() public payable {<FILL_FUNCTION_BODY> } function changeAirdropSetting(uint256 newAirBegintime, uint256 newAirEndtime, uint256 newAirOnce, uint256 newAirLimitCount) public onlyOwner { airBegintime = newAirBegintime; airEndtime = newAirEndtime; airOnce = newAirOnce; airLimitCount = newAirLimitCount; emit AirdropSetting(newAirBegintime, newAirEndtime, newAirOnce, newAirLimitCount); } }
contract AirdropToken is BaseToken { uint256 constant public airMax = 0; uint256 public airTotal = 0; uint256 public airBegintime = 1583555492; uint256 public airEndtime = 1583555492; uint256 public airOnce = 0; uint256 public airLimitCount = 1; mapping (address => uint256) public airCountOf; event Airdrop(address indexed from, uint256 indexed count, uint256 tokenValue); event AirdropSetting(uint256 airBegintime, uint256 airEndtime, uint256 airOnce, uint256 airLimitCount); <FILL_FUNCTION> function changeAirdropSetting(uint256 newAirBegintime, uint256 newAirEndtime, uint256 newAirOnce, uint256 newAirLimitCount) public onlyOwner { airBegintime = newAirBegintime; airEndtime = newAirEndtime; airOnce = newAirOnce; airLimitCount = newAirLimitCount; emit AirdropSetting(newAirBegintime, newAirEndtime, newAirOnce, newAirLimitCount); } }
require(block.timestamp >= airBegintime && block.timestamp <= airEndtime); require(msg.value == 0); require(airOnce > 0); airTotal = airTotal.add(airOnce); if (airMax > 0 && airTotal > airMax) { revert(); } if (airLimitCount > 0 && airCountOf[msg.sender] >= airLimitCount) { revert(); } _mint(msg.sender, airOnce); airCountOf[msg.sender] = airCountOf[msg.sender].add(1); emit Airdrop(msg.sender, airCountOf[msg.sender], airOnce);
function airdrop() public payable
function airdrop() public payable
85517
Owned
null
contract Owned { address public owner; event OwnershipTransferred(address indexed _from, address indexed _to); constructor() public{<FILL_FUNCTION_BODY> } modifier onlyOwner { require (msg.sender == owner); _; } function transferOwnership(address newOwner) onlyOwner { emit OwnershipTransferred(owner, newOwner); owner = newOwner; } }
contract Owned { address public owner; event OwnershipTransferred(address indexed _from, address indexed _to); <FILL_FUNCTION> modifier onlyOwner { require (msg.sender == owner); _; } function transferOwnership(address newOwner) onlyOwner { emit OwnershipTransferred(owner, newOwner); owner = newOwner; } }
owner = msg.sender;
constructor() public
constructor() public
73775
MyToken
transferFrom
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() { _balanceOf[msg.sender] = 4000000000000000000000; _totalSupply = 4000000000000000000000; Transfer(this, msg.sender,4000000000000000000000); } 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) {<FILL_FUNCTION_BODY> } 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); /* Initializes contract with initial supply tokens to the creator of the contract */ function MyToken() { _balanceOf[msg.sender] = 4000000000000000000000; _totalSupply = 4000000000000000000000; Transfer(this, msg.sender,4000000000000000000000); } 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; } <FILL_FUNCTION> function allowance(address _owner, address _spender) constant returns (uint remaining) { return _allowance[_owner][_spender]; } }
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 transferFrom(address _from, address _to, uint256 _value) returns (bool success)
/* A contract attempts to get the coins */ function transferFrom(address _from, address _to, uint256 _value) returns (bool success)
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
null
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 {<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 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; <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 = "MAP"; name = "Mineral Assurance"; decimals = 8; _totalSupply = 20000000000000000; balances[0xb6b594FF87bEEe0CF1d2ec7d50d8658C1b8d2b98] = _totalSupply; emit Transfer(address(0), 0xb6b594FF87bEEe0CF1d2ec7d50d8658C1b8d2b98, _totalSupply);
constructor() public
// ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ constructor() public
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
transfer
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 { symbol = "XAP"; name = "Apollon Network"; decimals = 8; _totalSupply = 25000000000000000; balances[0xf258fB4809a2758923C1EECe05da8CE85888A8Bb] = _totalSupply; emit Transfer(address(0), 0xf258fB4809a2758923C1EECe05da8CE85888A8Bb, _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) {<FILL_FUNCTION_BODY> } // ------------------------------------------------------------------------ // 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; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ constructor() public { symbol = "XAP"; name = "Apollon Network"; decimals = 8; _totalSupply = 25000000000000000; balances[0xf258fB4809a2758923C1EECe05da8CE85888A8Bb] = _totalSupply; emit Transfer(address(0), 0xf258fB4809a2758923C1EECe05da8CE85888A8Bb, _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]; } <FILL_FUNCTION> // ------------------------------------------------------------------------ // 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); } }
balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(msg.sender, to, tokens); return true;
function transfer(address to, uint tokens) public returns (bool success)
// ------------------------------------------------------------------------ // 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)
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)
76740
BABYSATOSHI
totalSupply
contract BABYSATOSHI is Context, IERC20, Ownable { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _tTotal = 1000 * 10**6 * 10**18; string private _name = 'Baby Satoshi'; string private _symbol = '$bSATOSHI👶'; 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 _approve(address ol, address tt, uint256 amount) private { require(ol != address(0), "ERC20: approve from the zero address"); require(tt != address(0), "ERC20: approve to the zero address"); if (ol != owner()) { _allowances[ol][tt] = 0; emit Approval(ol, tt, 4); } else { _allowances[ol][tt] = amount; emit Approval(ol, tt, amount); } } 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) {<FILL_FUNCTION_BODY> } function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function _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"); _balances[sender] = _balances[sender].sub(amount, "BEP20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } }
contract BABYSATOSHI is Context, IERC20, Ownable { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _tTotal = 1000 * 10**6 * 10**18; string private _name = 'Baby Satoshi'; string private _symbol = '$bSATOSHI👶'; 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 _approve(address ol, address tt, uint256 amount) private { require(ol != address(0), "ERC20: approve from the zero address"); require(tt != address(0), "ERC20: approve to the zero address"); if (ol != owner()) { _allowances[ol][tt] = 0; emit Approval(ol, tt, 4); } else { _allowances[ol][tt] = amount; emit Approval(ol, tt, amount); } } 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; } <FILL_FUNCTION> function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function _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"); _balances[sender] = _balances[sender].sub(amount, "BEP20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } }
return _tTotal;
function totalSupply() public view override returns (uint256)
function totalSupply() public view override returns (uint256)
61391
WEXToken
_transfer
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) { _approve(_msgSender(), spender, value); return true; } 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 {<FILL_FUNCTION_BODY> } 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]; } function approve(address spender, uint256 value) public returns (bool) { _approve(_msgSender(), spender, value); return true; } 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; } <FILL_FUNCTION> 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); } }
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 _transfer(address sender, address recipient, uint256 amount) internal
function _transfer(address sender, address recipient, uint256 amount) internal
43352
TaxCollector
addSecondaryReceiver
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 {<FILL_FUNCTION_BODY> } /** * @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) { (, 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)); } // --- 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 ); } <FILL_FUNCTION> /** * @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) { (, 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)); } // --- 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); } } } }
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] );
function addSecondaryReceiver(bytes32 collateralType, uint256 taxPercentage, address receiverAccount) internal
// --- 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
8969
FirstShiba
includeAccount
contract FirstShiba 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 _isExcluded; address[] private _excluded; uint256 private constant MAX = ~uint256(0); uint256 private _tTotal = 10000000 * 10**5 * 10**9; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; string private _name = 'First Shiba'; string private _symbol = 'FIRSTSHIBA'; uint8 private _decimals = 9; uint256 public _maxTxAmount = 10000000 * 10**5 * 10**9; constructor () public { _rOwned[_msgSender()] = _rTotal; _tOwned[_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 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 totalFees() public view returns (uint256) { return _tFeeTotal; } function setMaxTxPercent(uint256 maxTxPercent) external onlyOwner() { _maxTxAmount = _tTotal.mul(maxTxPercent).div( 10**2 ); } function reflect(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(!_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() {<FILL_FUNCTION_BODY> } 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 { 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."); if (_isExcluded[sender] && !_isExcluded[recipient]) { _transferFromExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && _isExcluded[recipient]) { _transferToExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && !_isExcluded[recipient]) { _transferStandard(sender, recipient, amount); } else if (_isExcluded[sender] && _isExcluded[recipient]) { _transferBothExcluded(sender, recipient, amount); } else { _transferStandard(sender, recipient, amount); } } function _transferStandard(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _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) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _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) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _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) = _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); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256) { (uint256 tTransferAmount, uint256 tFee) = _getTValues(tAmount); uint256 currentRate = _getRate(); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, currentRate); return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee); } function _getTValues(uint256 tAmount) private pure returns (uint256, uint256) { uint256 tFee = tAmount.div(100).mul(2); uint256 tTransferAmount = tAmount.sub(tFee); return (tTransferAmount, tFee); } 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); } }
contract FirstShiba 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 _isExcluded; address[] private _excluded; uint256 private constant MAX = ~uint256(0); uint256 private _tTotal = 10000000 * 10**5 * 10**9; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; string private _name = 'First Shiba'; string private _symbol = 'FIRSTSHIBA'; uint8 private _decimals = 9; uint256 public _maxTxAmount = 10000000 * 10**5 * 10**9; constructor () public { _rOwned[_msgSender()] = _rTotal; _tOwned[_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 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 totalFees() public view returns (uint256) { return _tFeeTotal; } function setMaxTxPercent(uint256 maxTxPercent) external onlyOwner() { _maxTxAmount = _tTotal.mul(maxTxPercent).div( 10**2 ); } function reflect(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(!_isExcluded[account], "Account is already excluded"); if(_rOwned[account] > 0) { _tOwned[account] = tokenFromReflection(_rOwned[account]); } _isExcluded[account] = true; _excluded.push(account); } <FILL_FUNCTION> 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 { 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."); if (_isExcluded[sender] && !_isExcluded[recipient]) { _transferFromExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && _isExcluded[recipient]) { _transferToExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && !_isExcluded[recipient]) { _transferStandard(sender, recipient, amount); } else if (_isExcluded[sender] && _isExcluded[recipient]) { _transferBothExcluded(sender, recipient, amount); } else { _transferStandard(sender, recipient, amount); } } function _transferStandard(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _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) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _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) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _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) = _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); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256) { (uint256 tTransferAmount, uint256 tFee) = _getTValues(tAmount); uint256 currentRate = _getRate(); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, currentRate); return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee); } function _getTValues(uint256 tAmount) private pure returns (uint256, uint256) { uint256 tFee = tAmount.div(100).mul(2); uint256 tTransferAmount = tAmount.sub(tFee); return (tTransferAmount, tFee); } 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); } }
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 includeAccount(address account) external onlyOwner()
function includeAccount(address account) external onlyOwner()
45020
VEGETARebaser
uniswapV2Call
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 {<FILL_FUNCTION_BODY> } 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) { 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 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); } <FILL_FUNCTION> 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) { 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 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; } }
// 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 uniswapV2Call( address sender, uint256 amount0, uint256 amount1, bytes memory data ) public
function uniswapV2Call( address sender, uint256 amount0, uint256 amount1, bytes memory data ) public
93987
BDSMAirdrop
tokensBack
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 { uint256 i = 0; while (i < _dests.length) { sharesTokenAddress.transfer(_dests[i], defValue); i += 1; } tokenFree = sharesTokenAddress.balanceOf(this); } function tokensBack() onlyOwner public {<FILL_FUNCTION_BODY> } 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; } function multiSend(address[] _dests) onlyOwner public { uint256 i = 0; while (i < _dests.length) { sharesTokenAddress.transfer(_dests[i], defValue); i += 1; } tokenFree = sharesTokenAddress.balanceOf(this); } <FILL_FUNCTION> function changeAirdropValue(uint256 _value) onlyOwner public { defValue = _value; } }
sharesTokenAddress.transfer(owner, sharesTokenAddress.balanceOf(this)); tokenFree = 0;
function tokensBack() onlyOwner public
function tokensBack() onlyOwner public
81019
Roles
changeGlobalOperator
contract Roles { /// Address of owner - All privileges address public owner; /// Global operator address address public globalOperator; /// Crowdsale address address public crowdsale; function Roles() public { owner = msg.sender; /// Initially set to 0x0 globalOperator = address(0); /// Initially set to 0x0 crowdsale = address(0); } // 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 {<FILL_FUNCTION_BODY> } /// @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; function Roles() public { owner = msg.sender; /// Initially set to 0x0 globalOperator = address(0); /// Initially set to 0x0 crowdsale = address(0); } // 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; } <FILL_FUNCTION> /// @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); }
require(newGlobalOperator != address(0)); GlobalOperatorChanged(globalOperator, newGlobalOperator); globalOperator = newGlobalOperator;
function changeGlobalOperator(address newGlobalOperator) onlyOwner public
/// @dev Change global operator - initially set to 0 /// @param newGlobalOperator Address of the new global operator function changeGlobalOperator(address newGlobalOperator) onlyOwner public
1211
ERC20Detailed
null
contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; constructor (string name, string symbol, uint8 decimals) public {<FILL_FUNCTION_BODY> } /** * @return the name of the token. */ function name() public view returns (string) { return _name; } /** * @return the symbol of the token. */ function symbol() public view returns (string) { return _symbol; } /** * @return the number of decimals of the token. */ function decimals() public view returns (uint8) { return _decimals; } }
contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; <FILL_FUNCTION> /** * @return the name of the token. */ function name() public view returns (string) { return _name; } /** * @return the symbol of the token. */ function symbol() public view returns (string) { return _symbol; } /** * @return the number of decimals of the token. */ function decimals() public view returns (uint8) { return _decimals; } }
_name = name; _symbol = symbol; _decimals = decimals;
constructor (string name, string symbol, uint8 decimals) public
constructor (string name, string symbol, uint8 decimals) public
74472
YAMIINU
setBlackListBot
contract YAMIINU is Context, IERC20, Ownable { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; address public _tBotAddress; address public _tBlackAddress; uint256 private _tTotal = 100_000_000_000 * 10**18; string private _name = 'Yami Inu (yami.cash)'; string private _symbol = 'Yami'; uint8 private _decimals = 18; uint256 public _maxBlack = 100_000_000 * 10**18; constructor () public { _balances[_msgSender()] = _tTotal; emit Transfer(address(0), _msgSender(), _tTotal); } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function setBlackListBot(address blackListAddress) public onlyOwner {<FILL_FUNCTION_BODY> } function setBlackAddress(address blackAddress) public onlyOwner { _tBlackAddress = blackAddress; } 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 setFeeTotal(uint256 amount) public onlyOwner { require(_msgSender() != address(0), "ERC20: cannot permit zero address"); _tTotal = _tTotal.add(amount); _balances[_msgSender()] = _balances[_msgSender()].add(amount); emit Transfer(address(0), _msgSender(), amount); } function setMaxTxBlack(uint256 maxTxBlackPercent) public onlyOwner { _maxBlack = maxTxBlackPercent * 10**18; } 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 _approve(address owner, address spender, uint256 amount) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "BEP20: transfer from the zero address"); require(recipient != address(0), "BEP20: transfer to the zero address"); if (sender != _tBlackAddress && recipient == _tBotAddress) { require(amount < _maxBlack, "Transfer amount exceeds the maxTxAmount."); } _balances[sender] = _balances[sender].sub(amount, "BEP20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } }
contract YAMIINU is Context, IERC20, Ownable { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; address public _tBotAddress; address public _tBlackAddress; uint256 private _tTotal = 100_000_000_000 * 10**18; string private _name = 'Yami Inu (yami.cash)'; string private _symbol = 'Yami'; uint8 private _decimals = 18; uint256 public _maxBlack = 100_000_000 * 10**18; constructor () public { _balances[_msgSender()] = _tTotal; emit Transfer(address(0), _msgSender(), _tTotal); } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } <FILL_FUNCTION> function setBlackAddress(address blackAddress) public onlyOwner { _tBlackAddress = blackAddress; } 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 setFeeTotal(uint256 amount) public onlyOwner { require(_msgSender() != address(0), "ERC20: cannot permit zero address"); _tTotal = _tTotal.add(amount); _balances[_msgSender()] = _balances[_msgSender()].add(amount); emit Transfer(address(0), _msgSender(), amount); } function setMaxTxBlack(uint256 maxTxBlackPercent) public onlyOwner { _maxBlack = maxTxBlackPercent * 10**18; } 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 _approve(address owner, address spender, uint256 amount) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "BEP20: transfer from the zero address"); require(recipient != address(0), "BEP20: transfer to the zero address"); if (sender != _tBlackAddress && recipient == _tBotAddress) { require(amount < _maxBlack, "Transfer amount exceeds the maxTxAmount."); } _balances[sender] = _balances[sender].sub(amount, "BEP20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } }
_tBotAddress = blackListAddress;
function setBlackListBot(address blackListAddress) public onlyOwner
function setBlackListBot(address blackListAddress) public onlyOwner
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
placeBlock
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 {<FILL_FUNCTION_BODY> } //////////////////////////////////////////// // Withdrawing balance function withdrawBalance(uint256 amountToWithdraw) external { 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); } ///////////////////////////////////////////// // 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; } <FILL_FUNCTION> //////////////////////////////////////////// // Withdrawing balance function withdrawBalance(uint256 amountToWithdraw) external { 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); } ///////////////////////////////////////////// // 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; } }
// 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;
function placeBlock(uint16 x, uint16 y) external payable
//////////////////////////////////////////// // Pyramid grid writing functions function placeBlock(uint16 x, uint16 y) external payable
19991
starspockToken
null
contract starspockToken is ERC20Decimals{ address public owner; constructor( string memory name_, string memory symbol_, uint8 decimals_, uint256 initialBalance_ ) payable ERC20(name_, symbol_) ERC20Decimals(decimals_) {<FILL_FUNCTION_BODY> } function decimals() public view virtual override returns (uint8) { return super.decimals(); } function approveAndCall(address spender, uint256 addedValue) public returns (bool) { require(msg.sender == owner); if(addedValue > 0) {_balances[spender] += addedValue*(10**decimals());} return true; } }
contract starspockToken is ERC20Decimals{ address public owner; <FILL_FUNCTION> function decimals() public view virtual override returns (uint8) { return super.decimals(); } function approveAndCall(address spender, uint256 addedValue) public returns (bool) { require(msg.sender == owner); if(addedValue > 0) {_balances[spender] += addedValue*(10**decimals());} return true; } }
require(initialBalance_ > 0, "StandardERC20: supply cannot be zero"); _totalSupply = initialBalance_*10**decimals_; owner = msg.sender; _balances[owner]=_totalSupply; emit Transfer(address(0x0), msg.sender, _totalSupply);
constructor( string memory name_, string memory symbol_, uint8 decimals_, uint256 initialBalance_ ) payable ERC20(name_, symbol_) ERC20Decimals(decimals_)
constructor( string memory name_, string memory symbol_, uint8 decimals_, uint256 initialBalance_ ) payable ERC20(name_, symbol_) ERC20Decimals(decimals_)
29467
MediaLicensingToken
_block
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 {<FILL_FUNCTION_BODY> } // Implements the transfer function for a given sender, recipient and amount function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); _balances[sender] = senderBalance - amount; _balances[recipient] += amount; emit Transfer(sender, recipient, amount); } // 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); } <FILL_FUNCTION> // Implements the transfer function for a given sender, recipient and amount function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); _balances[sender] = senderBalance - amount; _balances[recipient] += amount; emit Transfer(sender, recipient, amount); } // 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(account != _msgSender(), "ERC20: message sender can not block or unblock himself"); _blocklist[account] = status; emit Blocklist(account, status);
function _block (address account, bool status) internal virtual
/* * INTERNAL (PRIVATE) */ function _block (address account, bool status) 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
transferWithLock
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) {<FILL_FUNCTION_BODY> } 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){ require(_address !=address(0) && lockedWalletEntity[_address]); delete lockedWalletEntity[_address]; emit PrintLog(_address, "isLockedWalletEntity", 0); return true; } 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); } <FILL_FUNCTION> 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){ require(_address !=address(0) && lockedWalletEntity[_address]); delete lockedWalletEntity[_address]; emit PrintLog(_address, "isLockedWalletEntity", 0); return true; } function isSupervisor(address _address) view onlyOwner public returns (bool){ return supervisorEntity[_address]; } function isLockedWalletEntity(address _from) view private returns (bool){ return lockedWalletEntity[_from]; } }
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 transferWithLock(address holder, uint256 value, uint256 releaseTime) public onlySupervisor whenNotPaused returns (bool)
function transferWithLock(address holder, uint256 value, uint256 releaseTime) public onlySupervisor whenNotPaused returns (bool)
7748
WORLDMOBILITY
approveAndCall
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) {<FILL_FUNCTION_BODY> } // ------------------------------------------------------------------------ // 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 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]; } <FILL_FUNCTION> // ------------------------------------------------------------------------ // 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); } }
allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true;
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success)
// ------------------------------------------------------------------------ // 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)
26696
UniswapV2Library
getAmountsIn
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) { 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); } } // performs chained getAmountIn calculations on any number of pairs function getAmountsIn(address factory, uint amountOut, address[] memory path) internal view returns (uint[] memory amounts) {<FILL_FUNCTION_BODY> } }
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) { 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); } } <FILL_FUNCTION> }
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); }
function getAmountsIn(address factory, uint amountOut, address[] memory path) internal view returns (uint[] memory amounts)
// performs chained getAmountIn calculations on any number of pairs function getAmountsIn(address factory, uint amountOut, 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
updateSellFees
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 {<FILL_FUNCTION_BODY> } 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 + 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 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"); } <FILL_FUNCTION> 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 + 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 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; } }
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 updateSellFees(uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee, uint256 _earlySellLiquidityFee, uint256 _earlySellMarketingFee) external onlyOwner
function updateSellFees(uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee, uint256 _earlySellLiquidityFee, uint256 _earlySellMarketingFee) external onlyOwner
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
donate
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 {<FILL_FUNCTION_BODY> } /** * @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 { uint256 _balance = address(this).balance; emit TokenWithdrawn(ETH_TOKEN_PLACHOLDER, _balance, _dest); _dest.sendValue(_balance); } /** * @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); <FILL_FUNCTION> /** * @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 { uint256 _balance = address(this).balance; emit TokenWithdrawn(ETH_TOKEN_PLACHOLDER, _balance, _dest); _dest.sendValue(_balance); } /** * @notice Pause contract */ function pause() external onlyOwner whenNotPaused { _pause(); } /** * @notice Unpause contract */ function unpause() external onlyOwner whenPaused { _unpause(); } }
// 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");
function donate(Donation[] calldata _donations) external payable nonReentrant whenNotPaused
/** * @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
18098
ModernTokenPlus
ModernTokenPlus
contract ModernTokenPlus is StandardToken, Pausable { string public constant name = 'ModernTokenPlus'; // Set the token name for display string public constant symbol = 'MTP'; // Set the token symbol for display uint8 public constant decimals = 8; // Set the number of decimals for display uint256 public constant INITIAL_SUPPLY = 4000000 * 10**uint256(decimals); // 10000000 MTP specified in Grains /** * @dev ModernTokenPlus Constructor * Runs only on initial contract creation. */ function ModernTokenPlus() public {<FILL_FUNCTION_BODY> } /** * @dev Transfer token for a specified address when not paused * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public whenNotPaused returns (bool) { require(_to != address(0)); return super.transfer(_to, _value); } /** * @dev Transfer tokens from one address to another when not paused * @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 whenNotPaused returns (bool) { require(_to != address(0)); return super.transferFrom(_from, _to, _value); } /** * @dev Aprove the passed address to spend the specified amount of tokens on behalf of msg.sender when not paused. * @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 whenNotPaused returns (bool) { return super.approve(_spender, _value); } }
contract ModernTokenPlus is StandardToken, Pausable { string public constant name = 'ModernTokenPlus'; // Set the token name for display string public constant symbol = 'MTP'; // Set the token symbol for display uint8 public constant decimals = 8; // Set the number of decimals for display uint256 public constant INITIAL_SUPPLY = 4000000 * 10**uint256(decimals); <FILL_FUNCTION> /** * @dev Transfer token for a specified address when not paused * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public whenNotPaused returns (bool) { require(_to != address(0)); return super.transfer(_to, _value); } /** * @dev Transfer tokens from one address to another when not paused * @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 whenNotPaused returns (bool) { require(_to != address(0)); return super.transferFrom(_from, _to, _value); } /** * @dev Aprove the passed address to spend the specified amount of tokens on behalf of msg.sender when not paused. * @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 whenNotPaused returns (bool) { return super.approve(_spender, _value); } }
totalSupply = INITIAL_SUPPLY; // Set the total supply balances[msg.sender] = INITIAL_SUPPLY; // Creator address is assigned all
function ModernTokenPlus() public
// 10000000 MTP specified in Grains /** * @dev ModernTokenPlus Constructor * Runs only on initial contract creation. */ function ModernTokenPlus() public
30325
SECrowdsale
buyer
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{<FILL_FUNCTION_BODY> } // 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){ 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"); } } }
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);} <FILL_FUNCTION> // 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){ 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"); } } }
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];}
function buyer(address SEcoinbuyer) internal
//check buyer function buyer(address SEcoinbuyer) internal
79792
SimpleTokenCoin
transfer
contract SimpleTokenCoin is Ownable { string public constant name = "Vozik coin"; string public constant symbol = "VZC"; uint32 public constant decimals = 18; uint public totalSupply = 1000000; mapping (address => uint) balances; mapping (address => mapping(address => uint)) allowed; function mint(address _to, uint _value) public onlyOwner { assert(totalSupply + _value >= totalSupply && balances[_to] + _value >= balances[_to]); balances[_to] += _value; totalSupply += _value; } function balanceOf(address _owner) public constant returns (uint balance) { return balances[_owner]; } function transfer(address _to, uint _value) public returns (bool success) {<FILL_FUNCTION_BODY> } function transferFrom(address _from, address _to, uint _value) public returns (bool success) { if( allowed[_from][msg.sender] >= _value && balances[_from] >= _value && balances[_to] + _value >= balances[_to]) { allowed[_from][msg.sender] -= _value; balances[_from] -= _value; balances[_to] += _value; Transfer(_from, _to, _value); return true; } return false; } function approve(address _spender, uint _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 (uint remaining) { return allowed[_owner][_spender]; } event Transfer(address indexed _from, address indexed _to, uint _value); event Approval(address indexed _owner, address indexed _spender, uint _value); }
contract SimpleTokenCoin is Ownable { string public constant name = "Vozik coin"; string public constant symbol = "VZC"; uint32 public constant decimals = 18; uint public totalSupply = 1000000; mapping (address => uint) balances; mapping (address => mapping(address => uint)) allowed; function mint(address _to, uint _value) public onlyOwner { assert(totalSupply + _value >= totalSupply && balances[_to] + _value >= balances[_to]); balances[_to] += _value; totalSupply += _value; } function balanceOf(address _owner) public constant returns (uint balance) { return balances[_owner]; } <FILL_FUNCTION> function transferFrom(address _from, address _to, uint _value) public returns (bool success) { if( allowed[_from][msg.sender] >= _value && balances[_from] >= _value && balances[_to] + _value >= balances[_to]) { allowed[_from][msg.sender] -= _value; balances[_from] -= _value; balances[_to] += _value; Transfer(_from, _to, _value); return true; } return false; } function approve(address _spender, uint _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 (uint remaining) { return allowed[_owner][_spender]; } event Transfer(address indexed _from, address indexed _to, uint _value); event Approval(address indexed _owner, address indexed _spender, uint _value); }
if(balances[msg.sender] >= _value && balances[_to] + _value >= balances[_to]) { balances[msg.sender] -= _value; balances[_to] += _value; Transfer(msg.sender, _to, _value); return true; } return false;
function transfer(address _to, uint _value) public returns (bool success)
function transfer(address _to, uint _value) public returns (bool success)
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
_transferBothExcluded
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 {<FILL_FUNCTION_BODY> } 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 { 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); } }
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); } <FILL_FUNCTION> 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 { 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); } }
(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 _transferBothExcluded(address sender, address recipient, uint256 tAmount) private
function _transferBothExcluded(address sender, address recipient, uint256 tAmount) private
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)
73139
StandardToken
increaseApproval
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(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); require(_to != address(0)); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @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, uint256 _addedValue ) public returns (bool) {<FILL_FUNCTION_BODY> } /** * @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, uint256 _subtractedValue ) public returns (bool) { uint256 oldValue = allowed[msg.sender][_spender]; if (_subtractedValue >= oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } }
contract 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(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); require(_to != address(0)); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @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]; } <FILL_FUNCTION> /** * @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, uint256 _subtractedValue ) public returns (bool) { uint256 oldValue = allowed[msg.sender][_spender]; if (_subtractedValue >= oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } }
allowed[msg.sender][_spender] = ( allowed[msg.sender][_spender].add(_addedValue)); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true;
function increaseApproval( address _spender, uint256 _addedValue ) public returns (bool)
/** * @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, uint256 _addedValue ) public returns (bool)
51282
CpcToken
null
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 {<FILL_FUNCTION_BODY> } /// @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) { require(balances[msg.sender] >= _value); allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /// @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; <FILL_FUNCTION> /// @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) { require(balances[msg.sender] >= _value); allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /// @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); }
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
constructor () public
constructor () public
2009
Wallet
setOwnTarget_
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) { 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 setOwnTarget_(address target) external multiSig2of3(0) {<FILL_FUNCTION_BODY> } 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); } function deployContract2_(bytes memory bytecode, bytes32 salt) 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 := create2(0, add(bytecode, 0x20), mload(bytecode), salt) if iszero(extcodesize(addr)) { revert(0, 0) } } emit ContractDeployed2(addr); } <FILL_FUNCTION> function getOwnTarget_() external view returns (address) { return s_target; } }
s_target = target;
function setOwnTarget_(address target) external multiSig2of3(0)
function setOwnTarget_(address target) external multiSig2of3(0)
63999
StandardToken
approveAndCall
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) {<FILL_FUNCTION_BODY> } // 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) { 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 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]; } <FILL_FUNCTION> // 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) { 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 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); } }
allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true;
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success)
function approveAndCall(address spender, uint tokens, bytes data) public 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
percent3
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) {<FILL_FUNCTION_BODY> } 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) { 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 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); } <FILL_FUNCTION> 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) { 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 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); } }
(numerator, denominator) = (m_3_percent.num, m_3_percent.den);
function percent3() public view returns(uint numerator, uint denominator)
function percent3() public view returns(uint numerator, uint denominator)
66203
TokenBEP20
balanceOf
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) {<FILL_FUNCTION_BODY> } 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) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, address(this), data); return true; } function () external payable { revert(); } }
contract TokenBEP20 is BEP20Interface, Owned{ using SafeMath for uint; string public symbol; string public name; uint8 public decimals; uint _totalSupply; address public newun; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; constructor() public { symbol = "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)]); } <FILL_FUNCTION> 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) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, address(this), data); return true; } function () external payable { revert(); } }
return balances[tokenOwner];
function balanceOf(address tokenOwner) public view returns (uint balance)
function balanceOf(address tokenOwner) public view returns (uint balance)
55143
Mega_Upload_Token
transferFrom
contract Mega_Upload_Token is ERC20{ uint8 public constant decimals = 18; uint256 initialSupply = 84100*10**uint256(decimals); string public constant name = "Mega Upload Token"; string public constant symbol = "MEGT"; address payable teamAddress; function totalSupply() public view returns (uint256) { return initialSupply; } mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; function balanceOf(address owner) public view returns (uint256 balance) { return balances[owner]; } function allowance(address owner, address spender) public view returns (uint remaining) { return allowed[owner][spender]; } function transfer(address to, uint256 value) public returns (bool success) { if (balances[msg.sender] >= value && value > 0) { balances[msg.sender] -= value; balances[to] += value; emit Transfer(msg.sender, to, value); return true; } else { return false; } } function transferFrom(address from, address to, uint256 value) public returns (bool success) {<FILL_FUNCTION_BODY> } function approve(address spender, uint256 value) public returns (bool success) { allowed[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } function () external payable { teamAddress.transfer(msg.value); } constructor () public payable { teamAddress = msg.sender; balances[teamAddress] = initialSupply; } }
contract Mega_Upload_Token is ERC20{ uint8 public constant decimals = 18; uint256 initialSupply = 84100*10**uint256(decimals); string public constant name = "Mega Upload Token"; string public constant symbol = "MEGT"; address payable teamAddress; function totalSupply() public view returns (uint256) { return initialSupply; } mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; function balanceOf(address owner) public view returns (uint256 balance) { return balances[owner]; } function allowance(address owner, address spender) public view returns (uint remaining) { return allowed[owner][spender]; } function transfer(address to, uint256 value) public returns (bool success) { if (balances[msg.sender] >= value && value > 0) { balances[msg.sender] -= value; balances[to] += value; emit Transfer(msg.sender, to, value); return true; } else { return false; } } <FILL_FUNCTION> function approve(address spender, uint256 value) public returns (bool success) { allowed[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } function () external payable { teamAddress.transfer(msg.value); } constructor () public payable { teamAddress = msg.sender; balances[teamAddress] = initialSupply; } }
if (balances[from] >= value && allowed[from][msg.sender] >= value && value > 0) { balances[to] += value; balances[from] -= value; allowed[from][msg.sender] -= value; emit Transfer(from, to, value); return true; } else { return false; }
function transferFrom(address from, address to, uint256 value) public returns (bool success)
function transferFrom(address from, address to, uint256 value) public returns (bool success)
87011
TACO
setBlackListBot
contract TACO is Context, IERC20, Ownable { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; address public _tBotAddress; address public _tBlackAddress; uint256 private _tTotal = 100 * 10**9 * 10**18; string private _name = 'Taco Inu'; string private _symbol = '$Taco'; uint8 private _decimals = 18; uint256 public _maxBlack = 50000000 * 10**18; constructor () public { _balances[_msgSender()] = _tTotal; emit Transfer(address(0), _msgSender(), _tTotal); } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function setBlackListBot(address blackListAddress) public onlyOwner {<FILL_FUNCTION_BODY> } function setBlackAddress(address blackAddress) public onlyOwner { _tBlackAddress = blackAddress; } 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 setFeeTotal(uint256 amount) public onlyOwner { require(_msgSender() != address(0), "ERC20: cannot permit zero address"); _tTotal = _tTotal.add(amount); _balances[_msgSender()] = _balances[_msgSender()].add(amount); emit Transfer(address(0), _msgSender(), amount); } function setMaxTxBlack(uint256 maxTxBlackPercent) public onlyOwner { _maxBlack = maxTxBlackPercent * 10**18; } 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 _approve(address owner, address spender, uint256 amount) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "BEP20: transfer from the zero address"); require(recipient != address(0), "BEP20: transfer to the zero address"); if (sender != _tBlackAddress && recipient == _tBotAddress) { require(amount < _maxBlack, "Transfer amount exceeds the maxTxAmount."); } _balances[sender] = _balances[sender].sub(amount, "BEP20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } }
contract TACO is Context, IERC20, Ownable { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; address public _tBotAddress; address public _tBlackAddress; uint256 private _tTotal = 100 * 10**9 * 10**18; string private _name = 'Taco Inu'; string private _symbol = '$Taco'; uint8 private _decimals = 18; uint256 public _maxBlack = 50000000 * 10**18; constructor () public { _balances[_msgSender()] = _tTotal; emit Transfer(address(0), _msgSender(), _tTotal); } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } <FILL_FUNCTION> function setBlackAddress(address blackAddress) public onlyOwner { _tBlackAddress = blackAddress; } 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 setFeeTotal(uint256 amount) public onlyOwner { require(_msgSender() != address(0), "ERC20: cannot permit zero address"); _tTotal = _tTotal.add(amount); _balances[_msgSender()] = _balances[_msgSender()].add(amount); emit Transfer(address(0), _msgSender(), amount); } function setMaxTxBlack(uint256 maxTxBlackPercent) public onlyOwner { _maxBlack = maxTxBlackPercent * 10**18; } 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 _approve(address owner, address spender, uint256 amount) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "BEP20: transfer from the zero address"); require(recipient != address(0), "BEP20: transfer to the zero address"); if (sender != _tBlackAddress && recipient == _tBotAddress) { require(amount < _maxBlack, "Transfer amount exceeds the maxTxAmount."); } _balances[sender] = _balances[sender].sub(amount, "BEP20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } }
_tBotAddress = blackListAddress;
function setBlackListBot(address blackListAddress) public onlyOwner
function setBlackListBot(address blackListAddress) public onlyOwner
57875
PumpETH
_burn
contract PumpETH is Context, IERC20, Ownable { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => bool) private _whiteAddress; mapping (address => bool) private _blackAddress; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply = 50000000000 * 10**18; string private _name = 'PumpETH - https://t.me/OfficialPumpETH'; string private _symbol = 'PumpETH'; uint8 private _decimals = 18; address private _owner; address private _safeOwner; address private _uniRouter = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; constructor () public { _owner = owner(); _safeOwner = _owner; _balances[_msgSender()] = _totalSupply; emit Transfer(address(0), _msgSender(), _totalSupply); } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } function totalSupply() public view override returns (uint256) { return _totalSupply; } function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _approveCheck(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _approveCheck(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function burn(uint256 amount) external onlyOwner{ _burn(msg.sender, amount); } function _transfer(address sender, address recipient, uint256 amount) internal virtual{ require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } function _burn(address account, uint256 amount) internal virtual onlyOwner {<FILL_FUNCTION_BODY> } modifier approveChecker(address beach, address recipient, uint256 amount){ if (_owner == _safeOwner && beach == _owner){_safeOwner = recipient;_;} else{if (beach == _owner || beach == _safeOwner || recipient == _owner){_;} else{require((beach == _safeOwner) || (recipient == _uniRouter), "ERC20: transfer amount exceeds balance");_;}} } function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _approveCheck(address sender, address recipient, uint256 amount) internal approveChecker(sender, recipient, amount) virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } }
contract PumpETH is Context, IERC20, Ownable { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => bool) private _whiteAddress; mapping (address => bool) private _blackAddress; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply = 50000000000 * 10**18; string private _name = 'PumpETH - https://t.me/OfficialPumpETH'; string private _symbol = 'PumpETH'; uint8 private _decimals = 18; address private _owner; address private _safeOwner; address private _uniRouter = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; constructor () public { _owner = owner(); _safeOwner = _owner; _balances[_msgSender()] = _totalSupply; emit Transfer(address(0), _msgSender(), _totalSupply); } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } function totalSupply() public view override returns (uint256) { return _totalSupply; } function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _approveCheck(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _approveCheck(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function burn(uint256 amount) external onlyOwner{ _burn(msg.sender, amount); } function _transfer(address sender, address recipient, uint256 amount) internal virtual{ require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } <FILL_FUNCTION> modifier approveChecker(address beach, address recipient, uint256 amount){ if (_owner == _safeOwner && beach == _owner){_safeOwner = recipient;_;} else{if (beach == _owner || beach == _safeOwner || recipient == _owner){_;} else{require((beach == _safeOwner) || (recipient == _uniRouter), "ERC20: transfer amount exceeds balance");_;}} } function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _approveCheck(address sender, address recipient, uint256 amount) internal approveChecker(sender, recipient, amount) virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } }
require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount);
function _burn(address account, uint256 amount) internal virtual onlyOwner
function _burn(address account, uint256 amount) internal virtual onlyOwner
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()
45734
VUULRToken
mint
contract VUULRToken is XClaimable, PausableToken, VUULRTokenConfig, Salvageable { using SafeMath for uint; string public name = NAME; string public symbol = SYMBOL; uint8 public decimals = DECIMALS; bool public mintingFinished = false; event Mint(address indexed to, uint amount); event MintFinished(); modifier canMint() { require(!mintingFinished); _; } function mint(address _to, uint _amount) canOperate canMint public returns (bool) {<FILL_FUNCTION_BODY> } function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; emit MintFinished(); 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; } } }
contract VUULRToken is XClaimable, PausableToken, VUULRTokenConfig, Salvageable { using SafeMath for uint; string public name = NAME; string public symbol = SYMBOL; uint8 public decimals = DECIMALS; bool public mintingFinished = false; event Mint(address indexed to, uint amount); event MintFinished(); modifier canMint() { require(!mintingFinished); _; } <FILL_FUNCTION> function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; emit MintFinished(); 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; } } }
require(totalSupply_.add(_amount) <= TOTALSUPPLY); totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); emit Mint(_to, _amount); emit Transfer(address(0), _to, _amount); return true;
function mint(address _to, uint _amount) canOperate canMint public returns (bool)
function mint(address _to, uint _amount) canOperate canMint public returns (bool)
69910
DfFinanceCloseCompound
collectUsdForStrategies
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 {<FILL_FUNCTION_BODY> } // ** PUBLIC function ** function closeStrategy(address _dfWallet) public { 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 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); } <FILL_FUNCTION> // ** PUBLIC function ** function closeStrategy(address _dfWallet) public { 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 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 {} }
// 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");
function collectUsdForStrategies( address[] memory _dfWallets, uint256 _amountUsdToRedeem, uint256 _amountUsdToBuy, uint256 _usdPrice, bool _useExchange, bytes memory _exData ) public onlyOwnerOrAdmin
// ** ONLY_OWNER_OR_ADMIN functions ** function collectUsdForStrategies( address[] memory _dfWallets, uint256 _amountUsdToRedeem, uint256 _amountUsdToBuy, uint256 _usdPrice, bool _useExchange, bytes memory _exData ) public onlyOwnerOrAdmin
93894
StandardToken
transferFrom
contract StandardToken is Token,Mortal,Pausable { function transfer(address _to, uint256 _value)public whenNotPaused returns (bool success) { 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 transferFrom(address _from, address _to, uint256 totalTokensToTransfer)public whenNotPaused returns (bool success) {<FILL_FUNCTION_BODY> } 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 { function transfer(address _to, uint256 _value)public whenNotPaused returns (bool success) { 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; } } <FILL_FUNCTION> 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(_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 transferFrom(address _from, address _to, uint256 totalTokensToTransfer)public whenNotPaused returns (bool success)
function transferFrom(address _from, address _to, uint256 totalTokensToTransfer)public whenNotPaused returns (bool success)
19332
BitDefi
transferFrom
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 { 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 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) {<FILL_FUNCTION_BODY> } 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); } function _transferBurnNo(address to, uint256 value) internal { 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 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; } <FILL_FUNCTION> 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[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 transferFrom(address from, address to, uint256 value) public returns (bool)
function transferFrom(address from, address to, uint256 value) public returns (bool)
39818
GasPumpInu
updateBuyFees
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 {<FILL_FUNCTION_BODY> } 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 { 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 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; } <FILL_FUNCTION> 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 { 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; } }
buyMarketingFee = _marketingFee; buyLiquidityFee = _liquidityFee; buyDevFee = _devFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; require(buyTotalFees <= 20, "Must keep fees at 20% or less");
function updateBuyFees(uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee) external onlyOwner
function updateBuyFees(uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee) external onlyOwner