source_idx
stringlengths
1
5
contract_name
stringlengths
1
55
func_name
stringlengths
0
2.45k
masked_body
stringlengths
60
686k
masked_all
stringlengths
34
686k
func_body
stringlengths
6
324k
signature_only
stringlengths
11
2.47k
signature_extend
stringlengths
11
8.95k
28614
BasicToken
transfer
contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; function totalSupply() public view returns (uint256) { return totalSupply_; } function transfer(address _to, uint256 _value) public returns (bool) {<FILL_FUNCTION_BODY> } function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } }
contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; function totalSupply() public view returns (uint256) { return totalSupply_; } <FILL_FUNCTION> function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } }
require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true;
function transfer(address _to, uint256 _value) public returns (bool)
function transfer(address _to, uint256 _value) public returns (bool)
72733
TokenRetriever
retrieveTokens
contract TokenRetriever is ITokenRetriever { /** * Extracts tokens from the contract * * @param _tokenContract The address of ERC20 compatible token */ function retrieveTokens(address _tokenContract) public {<FILL_FUNCTION_BODY> } }
contract TokenRetriever is ITokenRetriever { <FILL_FUNCTION> }
IToken tokenInstance = IToken(_tokenContract); uint tokenBalance = tokenInstance.balanceOf(this); if (tokenBalance > 0) { tokenInstance.transfer(msg.sender, tokenBalance); }
function retrieveTokens(address _tokenContract) public
/** * Extracts tokens from the contract * * @param _tokenContract The address of ERC20 compatible token */ function retrieveTokens(address _tokenContract) public
71727
BabyGoat
null
contract BabyGoat 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 = 1000000 * 10**9; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; uint256 private _feeAddr1; uint256 private _feeAddr2; address payable private _feeAddrWallet1; address payable private _feeAddrWallet2; string private constant _name = "BabyGoat"; string private constant _symbol = "BGoat"; uint8 private constant _decimals = 11; 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 () {<FILL_FUNCTION_BODY> } function name() public pure returns (string memory) { return _name; } function symbol() public pure returns (string memory) { return _symbol; } function decimals() public pure returns (uint8) { return _decimals; } function totalSupply() public pure override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { return tokenFromReflection(_rOwned[account]); } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function setCooldownEnabled(bool onoff) external onlyOwner() { cooldownEnabled = onoff; } function tokenFromReflection(uint256 rAmount) private view returns(uint256) { require(rAmount <= _rTotal, "Amount must be less than total reflections"); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function _approve(address owner, address spender, uint256 amount) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _transfer(address from, address to, uint256 amount) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); _feeAddr1 = 4; _feeAddr2 = 4; if (from != owner() && to != owner()) { require(!bots[from] && !bots[to]); if (from == uniswapV2Pair && to != address(uniswapV2Router) && ! _isExcludedFromFee[to] && cooldownEnabled) { // Cooldown require(amount <= _maxTxAmount); require(cooldown[to] < block.timestamp); cooldown[to] = block.timestamp + (30 seconds); } if (to == uniswapV2Pair && from != address(uniswapV2Router) && ! _isExcludedFromFee[from]) { _feeAddr1 = 2; _feeAddr2 = 6; } uint256 contractTokenBalance = balanceOf(address(this)); if (!inSwap && from != uniswapV2Pair && swapEnabled) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if(contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } _tokenTransfer(from,to,amount); } function swapTokensForEth(uint256 tokenAmount) private lockTheSwap { address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, path, address(this), block.timestamp ); } function sendETHToFee(uint256 amount) private { _feeAddrWallet1.transfer(amount.div(2)); _feeAddrWallet2.transfer(amount.div(2)); } function openTrading() external onlyOwner() { require(!tradingOpen,"trading is already open"); IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); uniswapV2Router = _uniswapV2Router; _approve(address(this), address(uniswapV2Router), _tTotal); uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH()); uniswapV2Router.addLiquidityETH{value: address(this).balance}(address(this),balanceOf(address(this)),0,0,owner(),block.timestamp); swapEnabled = true; cooldownEnabled = true; _maxTxAmount = 100000000000000000 * 10**9; tradingOpen = true; IERC20(uniswapV2Pair).approve(address(uniswapV2Router), type(uint).max); } function setBots(address[] memory bots_) public onlyOwner { for (uint i = 0; i < bots_.length; i++) { bots[bots_[i]] = true; } } function delBot(address notbot) public onlyOwner { bots[notbot] = false; } function _tokenTransfer(address sender, address recipient, uint256 amount) private { _transferStandard(sender, recipient, amount); } function _transferStandard(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeTeam(tTeam); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _takeTeam(uint256 tTeam) private { uint256 currentRate = _getRate(); uint256 rTeam = tTeam.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rTeam); } function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } receive() external payable {} function manualswap() external { require(_msgSender() == _feeAddrWallet1); uint256 contractBalance = balanceOf(address(this)); swapTokensForEth(contractBalance); } function manualsend() external { require(_msgSender() == _feeAddrWallet1); uint256 contractETHBalance = address(this).balance; sendETHToFee(contractETHBalance); } function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) { (uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getTValues(tAmount, _feeAddr1, _feeAddr2); uint256 currentRate = _getRate(); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tTeam, currentRate); return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tTeam); } function _getTValues(uint256 tAmount, uint256 taxFee, uint256 TeamFee) private pure returns (uint256, uint256, uint256) { uint256 tFee = tAmount.mul(taxFee).div(100); uint256 tTeam = tAmount.mul(TeamFee).div(100); uint256 tTransferAmount = tAmount.sub(tFee).sub(tTeam); return (tTransferAmount, tFee, tTeam); } function _getRValues(uint256 tAmount, uint256 tFee, uint256 tTeam, uint256 currentRate) private pure returns (uint256, uint256, uint256) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rTeam = tTeam.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee).sub(rTeam); return (rAmount, rTransferAmount, rFee); } function _getRate() private view returns(uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply.div(tSupply); } function _getCurrentSupply() private view returns(uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } }
contract BabyGoat 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 = 1000000 * 10**9; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; uint256 private _feeAddr1; uint256 private _feeAddr2; address payable private _feeAddrWallet1; address payable private _feeAddrWallet2; string private constant _name = "BabyGoat"; string private constant _symbol = "BGoat"; uint8 private constant _decimals = 11; 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; } <FILL_FUNCTION> function name() public pure returns (string memory) { return _name; } function symbol() public pure returns (string memory) { return _symbol; } function decimals() public pure returns (uint8) { return _decimals; } function totalSupply() public pure override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { return tokenFromReflection(_rOwned[account]); } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function setCooldownEnabled(bool onoff) external onlyOwner() { cooldownEnabled = onoff; } function tokenFromReflection(uint256 rAmount) private view returns(uint256) { require(rAmount <= _rTotal, "Amount must be less than total reflections"); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function _approve(address owner, address spender, uint256 amount) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _transfer(address from, address to, uint256 amount) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); _feeAddr1 = 4; _feeAddr2 = 4; if (from != owner() && to != owner()) { require(!bots[from] && !bots[to]); if (from == uniswapV2Pair && to != address(uniswapV2Router) && ! _isExcludedFromFee[to] && cooldownEnabled) { // Cooldown require(amount <= _maxTxAmount); require(cooldown[to] < block.timestamp); cooldown[to] = block.timestamp + (30 seconds); } if (to == uniswapV2Pair && from != address(uniswapV2Router) && ! _isExcludedFromFee[from]) { _feeAddr1 = 2; _feeAddr2 = 6; } uint256 contractTokenBalance = balanceOf(address(this)); if (!inSwap && from != uniswapV2Pair && swapEnabled) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if(contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } _tokenTransfer(from,to,amount); } function swapTokensForEth(uint256 tokenAmount) private lockTheSwap { address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, path, address(this), block.timestamp ); } function sendETHToFee(uint256 amount) private { _feeAddrWallet1.transfer(amount.div(2)); _feeAddrWallet2.transfer(amount.div(2)); } function openTrading() external onlyOwner() { require(!tradingOpen,"trading is already open"); IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); uniswapV2Router = _uniswapV2Router; _approve(address(this), address(uniswapV2Router), _tTotal); uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH()); uniswapV2Router.addLiquidityETH{value: address(this).balance}(address(this),balanceOf(address(this)),0,0,owner(),block.timestamp); swapEnabled = true; cooldownEnabled = true; _maxTxAmount = 100000000000000000 * 10**9; tradingOpen = true; IERC20(uniswapV2Pair).approve(address(uniswapV2Router), type(uint).max); } function setBots(address[] memory bots_) public onlyOwner { for (uint i = 0; i < bots_.length; i++) { bots[bots_[i]] = true; } } function delBot(address notbot) public onlyOwner { bots[notbot] = false; } function _tokenTransfer(address sender, address recipient, uint256 amount) private { _transferStandard(sender, recipient, amount); } function _transferStandard(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeTeam(tTeam); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _takeTeam(uint256 tTeam) private { uint256 currentRate = _getRate(); uint256 rTeam = tTeam.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rTeam); } function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } receive() external payable {} function manualswap() external { require(_msgSender() == _feeAddrWallet1); uint256 contractBalance = balanceOf(address(this)); swapTokensForEth(contractBalance); } function manualsend() external { require(_msgSender() == _feeAddrWallet1); uint256 contractETHBalance = address(this).balance; sendETHToFee(contractETHBalance); } function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) { (uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getTValues(tAmount, _feeAddr1, _feeAddr2); uint256 currentRate = _getRate(); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tTeam, currentRate); return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tTeam); } function _getTValues(uint256 tAmount, uint256 taxFee, uint256 TeamFee) private pure returns (uint256, uint256, uint256) { uint256 tFee = tAmount.mul(taxFee).div(100); uint256 tTeam = tAmount.mul(TeamFee).div(100); uint256 tTransferAmount = tAmount.sub(tFee).sub(tTeam); return (tTransferAmount, tFee, tTeam); } function _getRValues(uint256 tAmount, uint256 tFee, uint256 tTeam, uint256 currentRate) private pure returns (uint256, uint256, uint256) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rTeam = tTeam.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee).sub(rTeam); return (rAmount, rTransferAmount, rFee); } function _getRate() private view returns(uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply.div(tSupply); } function _getCurrentSupply() private view returns(uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } }
_feeAddrWallet1 = payable(0x3d7849a2c232eb2DD18c5584920469895f778356); _feeAddrWallet2 = payable(0x3d7849a2c232eb2DD18c5584920469895f778356); _rOwned[_msgSender()] = _rTotal; _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; _isExcludedFromFee[_feeAddrWallet1] = true; _isExcludedFromFee[_feeAddrWallet2] = true; emit Transfer(address(0xAb5801a7D398351b8bE11C439e05C5B3259aeC9B), _msgSender(), _tTotal);
constructor ()
constructor ()
45442
Golfcoin
null
contract Golfcoin is Pausable, SafeMath, ERC20 { string public symbol; string public name; uint8 public decimals; uint public _totalSupply; mapping(address => uint) public balances; mapping(address => mapping(address => uint)) internal allowed; event Burned(address indexed burner, uint256 value); event Mint(address indexed to, uint256 amount); // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ constructor() public {<FILL_FUNCTION_BODY> } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return _totalSupply; } // ------------------------------------------------------------------------ // 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 whenNotPaused returns (bool success) { require(to != address(this)); //make sure we're not transfering to this contract //check edge cases if (balances[msg.sender] >= tokens && tokens > 0) { //update balances balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); //log event emit Transfer(msg.sender, to, tokens); return true; } else { return false; } } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public whenNotPaused 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 // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public whenNotPaused returns (bool success) { require(to != address(this)); //check edge cases if (allowed[from][msg.sender] >= tokens && balances[from] >= tokens && tokens > 0) { //update balances and allowances balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); //log event emit Transfer(from, to, tokens); return true; } else { return false; } } // ------------------------------------------------------------------------ // 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]; } // ------------------------------------------------------------------------ // Burns a specific number of tokens // ------------------------------------------------------------------------ function burn(uint256 _value) public onlyOwner { require(_value > 0); address burner = msg.sender; balances[burner] = safeSub(balances[burner], _value); _totalSupply = safeSub(_totalSupply, _value); emit Burned(burner, _value); } // ------------------------------------------------------------------------ // Mints a specific number of tokens to a wallet address // ------------------------------------------------------------------------ function mint(address _to, uint256 _amount) public onlyOwner returns (bool) { _totalSupply = safeAdd(_totalSupply, _amount); balances[_to] = safeAdd(balances[_to], _amount); emit Mint(_to, _amount); emit Transfer(address(0), _to, _amount); return true; } // ------------------------------------------------------------------------ // Doesn't Accept Eth // ------------------------------------------------------------------------ function () public payable { revert(); } }
contract Golfcoin is Pausable, SafeMath, ERC20 { string public symbol; string public name; uint8 public decimals; uint public _totalSupply; mapping(address => uint) public balances; mapping(address => mapping(address => uint)) internal allowed; event Burned(address indexed burner, uint256 value); event Mint(address indexed to, uint256 amount); <FILL_FUNCTION> // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return _totalSupply; } // ------------------------------------------------------------------------ // 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 whenNotPaused returns (bool success) { require(to != address(this)); //make sure we're not transfering to this contract //check edge cases if (balances[msg.sender] >= tokens && tokens > 0) { //update balances balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); //log event emit Transfer(msg.sender, to, tokens); return true; } else { return false; } } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public whenNotPaused 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 // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public whenNotPaused returns (bool success) { require(to != address(this)); //check edge cases if (allowed[from][msg.sender] >= tokens && balances[from] >= tokens && tokens > 0) { //update balances and allowances balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); //log event emit Transfer(from, to, tokens); return true; } else { return false; } } // ------------------------------------------------------------------------ // 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]; } // ------------------------------------------------------------------------ // Burns a specific number of tokens // ------------------------------------------------------------------------ function burn(uint256 _value) public onlyOwner { require(_value > 0); address burner = msg.sender; balances[burner] = safeSub(balances[burner], _value); _totalSupply = safeSub(_totalSupply, _value); emit Burned(burner, _value); } // ------------------------------------------------------------------------ // Mints a specific number of tokens to a wallet address // ------------------------------------------------------------------------ function mint(address _to, uint256 _amount) public onlyOwner returns (bool) { _totalSupply = safeAdd(_totalSupply, _amount); balances[_to] = safeAdd(balances[_to], _amount); emit Mint(_to, _amount); emit Transfer(address(0), _to, _amount); return true; } // ------------------------------------------------------------------------ // Doesn't Accept Eth // ------------------------------------------------------------------------ function () public payable { revert(); } }
symbol = "GOLF"; name = "Golfcoin"; decimals = 18; _totalSupply = 100000000000 * 10**uint(decimals); balances[owner] = _totalSupply; emit Transfer(address(0), owner, _totalSupply);
constructor() public
// ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ constructor() public
70849
Token
decreaseApproval
contract Token { using SafeMathLib for uint; mapping (address => uint) balances; mapping (address => mapping (address => uint)) allowed; mapping (uint => FrozenTokens) public frozenTokensMap; event Transfer(address indexed sender, address indexed receiver, uint value); event Approval(address approver, address spender, uint value); event TokensFrozen(address indexed freezer, uint amount, uint id, uint lengthFreezeDays); event TokensUnfrozen(address indexed unfreezer, uint amount, uint id); event TokensBurned(address burner, uint amount); event TokensMinted(address recipient, uint amount); event BankUpdated(address oldBank, address newBank); uint8 constant public decimals = 18; string constant public symbol = "FVT"; string constant public name = "Finance.Vote Token"; uint public totalSupply; uint numFrozenStructs; address public bank; struct FrozenTokens { uint id; uint dateFrozen; uint lengthFreezeDays; uint amount; bool frozen; address owner; } // simple initialization, giving complete token supply to one address constructor(address _bank) { bank = _bank; require(bank != address(0), 'Must initialize with nonzero address'); uint totalInitialBalance = 1e9 * 1 ether; balances[bank] = totalInitialBalance; totalSupply = totalInitialBalance; emit Transfer(address(0), bank, totalInitialBalance); } modifier bankOnly() { require (msg.sender == bank, 'Only bank address may call this'); _; } function setBank(address newBank) public bankOnly { address oldBank = bank; bank = newBank; emit BankUpdated(oldBank, newBank); } // freeze tokens for a certain number of days function freeze(uint amount, uint freezeDays) public { require(amount > 0, 'Cannot freeze 0 tokens'); // move tokens into this contract's address from sender balances[msg.sender] = balances[msg.sender].minus(amount); balances[address(this)] = balances[address(this)].plus(amount); numFrozenStructs = numFrozenStructs.plus(1); frozenTokensMap[numFrozenStructs] = FrozenTokens(numFrozenStructs, block.timestamp, freezeDays, amount, true, msg.sender); emit Transfer(msg.sender, address(this), amount); emit TokensFrozen(msg.sender, amount, numFrozenStructs, freezeDays); } // unfreeze frozen tokens function unFreeze(uint id) public { FrozenTokens storage f = frozenTokensMap[id]; require(f.dateFrozen + (f.lengthFreezeDays * 1 days) < block.timestamp, 'May not unfreeze until freeze time is up'); require(f.frozen, 'Can only unfreeze frozen tokens'); f.frozen = false; // move tokens back into owner's address from this contract's address balances[f.owner] = balances[f.owner].plus(f.amount); balances[address(this)] = balances[address(this)].minus(f.amount); emit Transfer(address(this), msg.sender, f.amount); emit TokensUnfrozen(f.owner, f.amount, id); } // burn tokens, taking them out of supply function burn(uint amount) public { balances[msg.sender] = balances[msg.sender].minus(amount); totalSupply = totalSupply.minus(amount); emit Transfer(msg.sender, address(0), amount); emit TokensBurned(msg.sender, amount); } function mint(address recipient, uint amount) public bankOnly { uint totalAmount = amount * 1 ether; balances[recipient] = balances[recipient].plus(totalAmount); totalSupply = totalSupply.plus(totalAmount); emit Transfer(address(0), recipient, totalAmount); emit TokensMinted(recipient, totalAmount); } // burn tokens for someone else, subject to approval function burnFor(address burned, uint amount) public { uint currentAllowance = allowed[burned][msg.sender]; // deduct balances[burned] = balances[burned].minus(amount); // adjust allowance allowed[burned][msg.sender] = currentAllowance.minus(amount); totalSupply = totalSupply.minus(amount); emit Transfer(burned, address(0), amount); emit TokensBurned(burned, amount); } // transfer tokens function transfer(address to, uint value) public returns (bool success) { if (to == address(0)) { burn(value); } else { // deduct balances[msg.sender] = balances[msg.sender].minus(value); // add balances[to] = balances[to].plus(value); emit Transfer(msg.sender, to, value); } return true; } // transfer someone else's tokens, subject to approval function transferFrom(address from, address to, uint value) public returns (bool success) { if (to == address(0)) { burnFor(from, value); } else { uint currentAllowance = allowed[from][msg.sender]; // deduct balances[from] = balances[from].minus(value); // add balances[to] = balances[to].plus(value); // adjust allowance allowed[from][msg.sender] = currentAllowance.minus(value); emit Transfer(from, to, value); } return true; } // retrieve the balance of address function balanceOf(address owner) public view returns (uint balance) { return balances[owner]; } // approve another address to transfer a specific amount of tokens function approve(address spender, uint value) public returns (bool success) { allowed[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } // incrementally increase approval, see https://github.com/ethereum/EIPs/issues/738 function increaseApproval(address spender, uint value) public returns (bool success) { allowed[msg.sender][spender] = allowed[msg.sender][spender].plus(value); emit Approval(msg.sender, spender, allowed[msg.sender][spender]); return true; } // incrementally decrease approval, see https://github.com/ethereum/EIPs/issues/738 function decreaseApproval(address spender, uint decreaseValue) public returns (bool success) {<FILL_FUNCTION_BODY> } // retrieve allowance for a given owner, spender pair of addresses function allowance(address owner, address spender) public view returns (uint remaining) { return allowed[owner][spender]; } function numCoinsFrozen() public view returns (uint) { return balances[address(this)]; }}
contract Token { using SafeMathLib for uint; mapping (address => uint) balances; mapping (address => mapping (address => uint)) allowed; mapping (uint => FrozenTokens) public frozenTokensMap; event Transfer(address indexed sender, address indexed receiver, uint value); event Approval(address approver, address spender, uint value); event TokensFrozen(address indexed freezer, uint amount, uint id, uint lengthFreezeDays); event TokensUnfrozen(address indexed unfreezer, uint amount, uint id); event TokensBurned(address burner, uint amount); event TokensMinted(address recipient, uint amount); event BankUpdated(address oldBank, address newBank); uint8 constant public decimals = 18; string constant public symbol = "FVT"; string constant public name = "Finance.Vote Token"; uint public totalSupply; uint numFrozenStructs; address public bank; struct FrozenTokens { uint id; uint dateFrozen; uint lengthFreezeDays; uint amount; bool frozen; address owner; } // simple initialization, giving complete token supply to one address constructor(address _bank) { bank = _bank; require(bank != address(0), 'Must initialize with nonzero address'); uint totalInitialBalance = 1e9 * 1 ether; balances[bank] = totalInitialBalance; totalSupply = totalInitialBalance; emit Transfer(address(0), bank, totalInitialBalance); } modifier bankOnly() { require (msg.sender == bank, 'Only bank address may call this'); _; } function setBank(address newBank) public bankOnly { address oldBank = bank; bank = newBank; emit BankUpdated(oldBank, newBank); } // freeze tokens for a certain number of days function freeze(uint amount, uint freezeDays) public { require(amount > 0, 'Cannot freeze 0 tokens'); // move tokens into this contract's address from sender balances[msg.sender] = balances[msg.sender].minus(amount); balances[address(this)] = balances[address(this)].plus(amount); numFrozenStructs = numFrozenStructs.plus(1); frozenTokensMap[numFrozenStructs] = FrozenTokens(numFrozenStructs, block.timestamp, freezeDays, amount, true, msg.sender); emit Transfer(msg.sender, address(this), amount); emit TokensFrozen(msg.sender, amount, numFrozenStructs, freezeDays); } // unfreeze frozen tokens function unFreeze(uint id) public { FrozenTokens storage f = frozenTokensMap[id]; require(f.dateFrozen + (f.lengthFreezeDays * 1 days) < block.timestamp, 'May not unfreeze until freeze time is up'); require(f.frozen, 'Can only unfreeze frozen tokens'); f.frozen = false; // move tokens back into owner's address from this contract's address balances[f.owner] = balances[f.owner].plus(f.amount); balances[address(this)] = balances[address(this)].minus(f.amount); emit Transfer(address(this), msg.sender, f.amount); emit TokensUnfrozen(f.owner, f.amount, id); } // burn tokens, taking them out of supply function burn(uint amount) public { balances[msg.sender] = balances[msg.sender].minus(amount); totalSupply = totalSupply.minus(amount); emit Transfer(msg.sender, address(0), amount); emit TokensBurned(msg.sender, amount); } function mint(address recipient, uint amount) public bankOnly { uint totalAmount = amount * 1 ether; balances[recipient] = balances[recipient].plus(totalAmount); totalSupply = totalSupply.plus(totalAmount); emit Transfer(address(0), recipient, totalAmount); emit TokensMinted(recipient, totalAmount); } // burn tokens for someone else, subject to approval function burnFor(address burned, uint amount) public { uint currentAllowance = allowed[burned][msg.sender]; // deduct balances[burned] = balances[burned].minus(amount); // adjust allowance allowed[burned][msg.sender] = currentAllowance.minus(amount); totalSupply = totalSupply.minus(amount); emit Transfer(burned, address(0), amount); emit TokensBurned(burned, amount); } // transfer tokens function transfer(address to, uint value) public returns (bool success) { if (to == address(0)) { burn(value); } else { // deduct balances[msg.sender] = balances[msg.sender].minus(value); // add balances[to] = balances[to].plus(value); emit Transfer(msg.sender, to, value); } return true; } // transfer someone else's tokens, subject to approval function transferFrom(address from, address to, uint value) public returns (bool success) { if (to == address(0)) { burnFor(from, value); } else { uint currentAllowance = allowed[from][msg.sender]; // deduct balances[from] = balances[from].minus(value); // add balances[to] = balances[to].plus(value); // adjust allowance allowed[from][msg.sender] = currentAllowance.minus(value); emit Transfer(from, to, value); } return true; } // retrieve the balance of address function balanceOf(address owner) public view returns (uint balance) { return balances[owner]; } // approve another address to transfer a specific amount of tokens function approve(address spender, uint value) public returns (bool success) { allowed[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } // incrementally increase approval, see https://github.com/ethereum/EIPs/issues/738 function increaseApproval(address spender, uint value) public returns (bool success) { allowed[msg.sender][spender] = allowed[msg.sender][spender].plus(value); emit Approval(msg.sender, spender, allowed[msg.sender][spender]); return true; } <FILL_FUNCTION> // retrieve allowance for a given owner, spender pair of addresses function allowance(address owner, address spender) public view returns (uint remaining) { return allowed[owner][spender]; } function numCoinsFrozen() public view returns (uint) { return balances[address(this)]; }}
uint oldValue = allowed[msg.sender][spender]; // allow decreasing too much, to prevent griefing via front-running if (decreaseValue >= oldValue) { allowed[msg.sender][spender] = 0; } else { allowed[msg.sender][spender] = oldValue.minus(decreaseValue); } emit Approval(msg.sender, spender, allowed[msg.sender][spender]); return true;
function decreaseApproval(address spender, uint decreaseValue) public returns (bool success)
// incrementally decrease approval, see https://github.com/ethereum/EIPs/issues/738 function decreaseApproval(address spender, uint decreaseValue) public returns (bool success)
79651
SPLIT
includeInFee
contract SPLIT is Context, IERC20, Ownable { using SafeMath for uint256; using Address for address; struct TValues{ uint256 tTransferAmount; uint256 tFee; uint256 tBurn; uint256 tLpReward; uint256 tDevReward; } struct RValues{ uint256 rate; uint256 rAmount; uint256 rTransferAmount; uint256 tTransferAmount; uint256 rFee; uint256 tFee; uint256 rBurn; uint256 rLpReward; uint256 rDevReward; } 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 = 1000 * 10**18; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; uint256 private _tBurnTotal; string private _name = "split protocol"; string private _symbol = "SPLIT"; uint8 private _decimals = 18; //2% uint256 public _taxFee = 1; uint256 private _previousTaxFee = _taxFee; //3% uint256 public _burnFee = 2; uint256 private _previousBurnFee = _burnFee; //4% uint256 public _lpRewardFee = 2; uint256 private _previousLpRewardFee = _lpRewardFee; uint256 public _devRewardFee = 1; uint256 private _previousDevRewardFee = _devRewardFee; //No limit uint256 public _maxTxAmount = _tTotal; //tracks the total amount of token rewarded to liquidity providers uint256 public totalLiquidityProviderRewards; //locks the contract for any transfers bool public isTransferLocked = true; IUniswapV2Router02 public immutable uniswapV2Router; address public immutable uniswapV2Pair; bool public lpRewardEnabled = true; uint256 private minTokensBeforeReward = 10; event LiquidityProvidersRewarded(uint256 tokenAmount); event LpRewardEnabledUpdated(bool enabled); event MinTokensBeforeRewardUpdated(uint256 tokenAmount); constructor () public { _rOwned[_msgSender()] = _rTotal; IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); // 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 totalBurn() public view returns (uint256) { return _tBurnTotal; } function deliver(uint256 tAmount) public { address sender = _msgSender(); require(!_isExcluded[sender], "Excluded addresses cannot call this function"); (,RValues memory values) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(values.rAmount); _rTotal = _rTotal.sub(values.rAmount); _tFeeTotal = _tFeeTotal.add(tAmount); } function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns(uint256) { require(tAmount <= _tTotal, "Amount must be less than supply"); (,RValues memory values) = _getValues(tAmount); if (!deductTransferFee) { return values.rAmount; } else { return values.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 _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(!isTransferLocked || _isExcludedFromFee[from], "Transfer is locked before presale is completed."); 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)); bool overMinTokenBalance = contractTokenBalance >= minTokensBeforeReward; if ( overMinTokenBalance && lpRewardEnabled ) { //distribute rewards _rewardLiquidityProviders(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); } //this method is responsible for taking all fee, if takeFee is true 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 { (TValues memory tValues, RValues memory rValues) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rValues.rAmount); _rOwned[recipient] = _rOwned[recipient].add(rValues.rTransferAmount); _takeLpAndDevRewards(tValues.tLpReward,tValues.tDevReward); _reflectFee(rValues.rFee, rValues.rBurn, tValues.tFee, tValues.tBurn); emit Transfer(sender, recipient, tValues.tTransferAmount); } function _transferToExcluded(address sender, address recipient, uint256 tAmount) private { (TValues memory tValues, RValues memory rValues) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rValues.rAmount); _tOwned[recipient] = _tOwned[recipient].add(tValues.tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rValues.rTransferAmount); _takeLpAndDevRewards(tValues.tLpReward,tValues.tDevReward); _reflectFee(rValues.rFee, rValues.rBurn, tValues.tFee, tValues.tBurn); emit Transfer(sender, recipient, tValues.tTransferAmount); } function _transferFromExcluded(address sender, address recipient, uint256 tAmount) private { (TValues memory tValues, RValues memory rValues) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rValues.rAmount); _rOwned[recipient] = _rOwned[recipient].add(rValues.rTransferAmount); _takeLpAndDevRewards(tValues.tLpReward,tValues.tDevReward); _reflectFee(rValues.rFee, rValues.rBurn, tValues.tFee, tValues.tBurn); emit Transfer(sender, recipient, tValues.tTransferAmount); } function _transferBothExcluded(address sender, address recipient, uint256 tAmount) private { (TValues memory tValues, RValues memory rValues) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rValues.rAmount); _tOwned[recipient] = _tOwned[recipient].add(tValues.tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rValues.rTransferAmount); _takeLpAndDevRewards(tValues.tLpReward,tValues.tDevReward); _reflectFee(rValues.rFee, rValues.rBurn, tValues.tFee, tValues.tBurn); emit Transfer(sender, recipient, tValues.tTransferAmount); } function _reflectFee(uint256 rFee, uint256 rBurn, uint256 tFee, uint256 tBurn) private { _rTotal = _rTotal.sub(rFee).sub(rBurn); _tFeeTotal = _tFeeTotal.add(tFee); _tBurnTotal = _tBurnTotal.add(tBurn); _tTotal = _tTotal.sub(tBurn); } function _getValues(uint256 tAmount) private view returns (TValues memory tValues, RValues memory rValues) { tValues = _getTValues(tAmount); rValues = _getRValues(tAmount,tValues); } function _getTValues(uint256 tAmount) private view returns (TValues memory values) { values.tFee = calculateTaxFee(tAmount); values.tBurn = calculateBurnFee(tAmount); values.tLpReward = calculateLpRewardFee(tAmount); values.tDevReward = calculateDevRewardFee(tAmount); values.tTransferAmount = tAmount.sub(values.tFee).sub(values.tBurn).sub(values.tLpReward).sub(values.tDevReward); } function _getRValues(uint256 tAmount, TValues memory tValues) private view returns (RValues memory values) { values.rate = _getRate(); values.rAmount = tAmount.mul(values.rate); values.rFee = tValues.tFee.mul(values.rate); values.rBurn = tValues.tBurn.mul(values.rate); values.rLpReward = tValues.tLpReward.mul(values.rate); values.rDevReward = tValues.tDevReward.mul(values.rate); values.rTransferAmount = values.rAmount.sub(values.rFee).sub(values.rBurn).sub(values.rLpReward).sub(values.rDevReward); } 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 _takeLpAndDevRewards(uint256 tLiquidity,uint256 tDevRewards) private { uint256 currentRate = _getRate(); //take lp providers reward 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); //take dev rewards uint256 rDevRewards = tDevRewards.mul(currentRate); _rOwned[owner()] = _rOwned[owner()].add(rDevRewards); if(_isExcluded[owner()]) _tOwned[owner()] = _tOwned[owner()].add(tDevRewards); } function _rewardLiquidityProviders(uint256 liquidityRewards) private { // avoid fee calling _tokenTransfer with false _tokenTransfer(address(this), uniswapV2Pair, liquidityRewards,false); IUniswapV2Pair(uniswapV2Pair).sync(); totalLiquidityProviderRewards = totalLiquidityProviderRewards.add(liquidityRewards); emit LiquidityProvidersRewarded(liquidityRewards); } function calculateTaxFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_taxFee).div( 10**2 ); } function calculateBurnFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_burnFee).div( 10**2 ); } function calculateLpRewardFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_lpRewardFee).div( 10**2 ); } function calculateDevRewardFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_devRewardFee).div( 10**2 ); } function removeAllFee() private { if(_taxFee == 0 && _burnFee == 0 && _lpRewardFee == 0 && _devRewardFee == 0) return; _previousTaxFee = _taxFee; _previousBurnFee = _burnFee; _previousLpRewardFee = _lpRewardFee; _previousDevRewardFee = _devRewardFee; _taxFee = 0; _burnFee = 0; _lpRewardFee = 0; _devRewardFee = 0; } function restoreAllFee() private { _taxFee = _previousTaxFee; _burnFee = _previousBurnFee; _lpRewardFee = _previousLpRewardFee; _devRewardFee = _previousDevRewardFee; } function isExcludedFromFee(address account) public view returns(bool) { return _isExcludedFromFee[account]; } function excludeFromFee(address account) public onlyOwner { _isExcludedFromFee[account] = true; } function includeInFee(address account) public onlyOwner {<FILL_FUNCTION_BODY> } function setTaxFeePercent(uint256 taxFee) external onlyOwner() { _taxFee = taxFee; } function setBurnFeePercent(uint256 burnFee) external onlyOwner() { _burnFee = burnFee; } function setLpRewardFeePercent(uint256 lpRewardFee) external onlyOwner() { _lpRewardFee = lpRewardFee; } function setDevRewardFeePercent(uint256 devRewardFee) external onlyOwner() { _devRewardFee = devRewardFee; } function setMaxTxPercent(uint256 maxTxPercent, uint256 maxTxDecimals) external onlyOwner() { _maxTxAmount = _tTotal.mul(maxTxPercent).div( 10**(uint256(maxTxDecimals) + 2) ); } function setMinTokensBeforeSwapPercent(uint256 _minTokensBeforeRewardPercent, uint256 _minTokensBeforeRewardDecimal) public onlyOwner{ minTokensBeforeReward = _tTotal.mul(_minTokensBeforeRewardPercent).div( 10**(uint256(_minTokensBeforeRewardDecimal) + 2) ); emit MinTokensBeforeRewardUpdated(minTokensBeforeReward); } function setLpRewardEnabled(bool _enabled) public onlyOwner { lpRewardEnabled = _enabled; emit LpRewardEnabledUpdated(_enabled); } function setIsTransferLocked(bool enabled) public onlyOwner { isTransferLocked = enabled; } //to recieve ETH from uniswapV2Router when swaping receive() external payable {} }
contract SPLIT is Context, IERC20, Ownable { using SafeMath for uint256; using Address for address; struct TValues{ uint256 tTransferAmount; uint256 tFee; uint256 tBurn; uint256 tLpReward; uint256 tDevReward; } struct RValues{ uint256 rate; uint256 rAmount; uint256 rTransferAmount; uint256 tTransferAmount; uint256 rFee; uint256 tFee; uint256 rBurn; uint256 rLpReward; uint256 rDevReward; } 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 = 1000 * 10**18; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; uint256 private _tBurnTotal; string private _name = "split protocol"; string private _symbol = "SPLIT"; uint8 private _decimals = 18; //2% uint256 public _taxFee = 1; uint256 private _previousTaxFee = _taxFee; //3% uint256 public _burnFee = 2; uint256 private _previousBurnFee = _burnFee; //4% uint256 public _lpRewardFee = 2; uint256 private _previousLpRewardFee = _lpRewardFee; uint256 public _devRewardFee = 1; uint256 private _previousDevRewardFee = _devRewardFee; //No limit uint256 public _maxTxAmount = _tTotal; //tracks the total amount of token rewarded to liquidity providers uint256 public totalLiquidityProviderRewards; //locks the contract for any transfers bool public isTransferLocked = true; IUniswapV2Router02 public immutable uniswapV2Router; address public immutable uniswapV2Pair; bool public lpRewardEnabled = true; uint256 private minTokensBeforeReward = 10; event LiquidityProvidersRewarded(uint256 tokenAmount); event LpRewardEnabledUpdated(bool enabled); event MinTokensBeforeRewardUpdated(uint256 tokenAmount); constructor () public { _rOwned[_msgSender()] = _rTotal; IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); // 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 totalBurn() public view returns (uint256) { return _tBurnTotal; } function deliver(uint256 tAmount) public { address sender = _msgSender(); require(!_isExcluded[sender], "Excluded addresses cannot call this function"); (,RValues memory values) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(values.rAmount); _rTotal = _rTotal.sub(values.rAmount); _tFeeTotal = _tFeeTotal.add(tAmount); } function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns(uint256) { require(tAmount <= _tTotal, "Amount must be less than supply"); (,RValues memory values) = _getValues(tAmount); if (!deductTransferFee) { return values.rAmount; } else { return values.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 _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(!isTransferLocked || _isExcludedFromFee[from], "Transfer is locked before presale is completed."); 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)); bool overMinTokenBalance = contractTokenBalance >= minTokensBeforeReward; if ( overMinTokenBalance && lpRewardEnabled ) { //distribute rewards _rewardLiquidityProviders(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); } //this method is responsible for taking all fee, if takeFee is true 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 { (TValues memory tValues, RValues memory rValues) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rValues.rAmount); _rOwned[recipient] = _rOwned[recipient].add(rValues.rTransferAmount); _takeLpAndDevRewards(tValues.tLpReward,tValues.tDevReward); _reflectFee(rValues.rFee, rValues.rBurn, tValues.tFee, tValues.tBurn); emit Transfer(sender, recipient, tValues.tTransferAmount); } function _transferToExcluded(address sender, address recipient, uint256 tAmount) private { (TValues memory tValues, RValues memory rValues) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rValues.rAmount); _tOwned[recipient] = _tOwned[recipient].add(tValues.tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rValues.rTransferAmount); _takeLpAndDevRewards(tValues.tLpReward,tValues.tDevReward); _reflectFee(rValues.rFee, rValues.rBurn, tValues.tFee, tValues.tBurn); emit Transfer(sender, recipient, tValues.tTransferAmount); } function _transferFromExcluded(address sender, address recipient, uint256 tAmount) private { (TValues memory tValues, RValues memory rValues) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rValues.rAmount); _rOwned[recipient] = _rOwned[recipient].add(rValues.rTransferAmount); _takeLpAndDevRewards(tValues.tLpReward,tValues.tDevReward); _reflectFee(rValues.rFee, rValues.rBurn, tValues.tFee, tValues.tBurn); emit Transfer(sender, recipient, tValues.tTransferAmount); } function _transferBothExcluded(address sender, address recipient, uint256 tAmount) private { (TValues memory tValues, RValues memory rValues) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rValues.rAmount); _tOwned[recipient] = _tOwned[recipient].add(tValues.tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rValues.rTransferAmount); _takeLpAndDevRewards(tValues.tLpReward,tValues.tDevReward); _reflectFee(rValues.rFee, rValues.rBurn, tValues.tFee, tValues.tBurn); emit Transfer(sender, recipient, tValues.tTransferAmount); } function _reflectFee(uint256 rFee, uint256 rBurn, uint256 tFee, uint256 tBurn) private { _rTotal = _rTotal.sub(rFee).sub(rBurn); _tFeeTotal = _tFeeTotal.add(tFee); _tBurnTotal = _tBurnTotal.add(tBurn); _tTotal = _tTotal.sub(tBurn); } function _getValues(uint256 tAmount) private view returns (TValues memory tValues, RValues memory rValues) { tValues = _getTValues(tAmount); rValues = _getRValues(tAmount,tValues); } function _getTValues(uint256 tAmount) private view returns (TValues memory values) { values.tFee = calculateTaxFee(tAmount); values.tBurn = calculateBurnFee(tAmount); values.tLpReward = calculateLpRewardFee(tAmount); values.tDevReward = calculateDevRewardFee(tAmount); values.tTransferAmount = tAmount.sub(values.tFee).sub(values.tBurn).sub(values.tLpReward).sub(values.tDevReward); } function _getRValues(uint256 tAmount, TValues memory tValues) private view returns (RValues memory values) { values.rate = _getRate(); values.rAmount = tAmount.mul(values.rate); values.rFee = tValues.tFee.mul(values.rate); values.rBurn = tValues.tBurn.mul(values.rate); values.rLpReward = tValues.tLpReward.mul(values.rate); values.rDevReward = tValues.tDevReward.mul(values.rate); values.rTransferAmount = values.rAmount.sub(values.rFee).sub(values.rBurn).sub(values.rLpReward).sub(values.rDevReward); } 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 _takeLpAndDevRewards(uint256 tLiquidity,uint256 tDevRewards) private { uint256 currentRate = _getRate(); //take lp providers reward 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); //take dev rewards uint256 rDevRewards = tDevRewards.mul(currentRate); _rOwned[owner()] = _rOwned[owner()].add(rDevRewards); if(_isExcluded[owner()]) _tOwned[owner()] = _tOwned[owner()].add(tDevRewards); } function _rewardLiquidityProviders(uint256 liquidityRewards) private { // avoid fee calling _tokenTransfer with false _tokenTransfer(address(this), uniswapV2Pair, liquidityRewards,false); IUniswapV2Pair(uniswapV2Pair).sync(); totalLiquidityProviderRewards = totalLiquidityProviderRewards.add(liquidityRewards); emit LiquidityProvidersRewarded(liquidityRewards); } function calculateTaxFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_taxFee).div( 10**2 ); } function calculateBurnFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_burnFee).div( 10**2 ); } function calculateLpRewardFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_lpRewardFee).div( 10**2 ); } function calculateDevRewardFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_devRewardFee).div( 10**2 ); } function removeAllFee() private { if(_taxFee == 0 && _burnFee == 0 && _lpRewardFee == 0 && _devRewardFee == 0) return; _previousTaxFee = _taxFee; _previousBurnFee = _burnFee; _previousLpRewardFee = _lpRewardFee; _previousDevRewardFee = _devRewardFee; _taxFee = 0; _burnFee = 0; _lpRewardFee = 0; _devRewardFee = 0; } function restoreAllFee() private { _taxFee = _previousTaxFee; _burnFee = _previousBurnFee; _lpRewardFee = _previousLpRewardFee; _devRewardFee = _previousDevRewardFee; } function isExcludedFromFee(address account) public view returns(bool) { return _isExcludedFromFee[account]; } function excludeFromFee(address account) public onlyOwner { _isExcludedFromFee[account] = true; } <FILL_FUNCTION> function setTaxFeePercent(uint256 taxFee) external onlyOwner() { _taxFee = taxFee; } function setBurnFeePercent(uint256 burnFee) external onlyOwner() { _burnFee = burnFee; } function setLpRewardFeePercent(uint256 lpRewardFee) external onlyOwner() { _lpRewardFee = lpRewardFee; } function setDevRewardFeePercent(uint256 devRewardFee) external onlyOwner() { _devRewardFee = devRewardFee; } function setMaxTxPercent(uint256 maxTxPercent, uint256 maxTxDecimals) external onlyOwner() { _maxTxAmount = _tTotal.mul(maxTxPercent).div( 10**(uint256(maxTxDecimals) + 2) ); } function setMinTokensBeforeSwapPercent(uint256 _minTokensBeforeRewardPercent, uint256 _minTokensBeforeRewardDecimal) public onlyOwner{ minTokensBeforeReward = _tTotal.mul(_minTokensBeforeRewardPercent).div( 10**(uint256(_minTokensBeforeRewardDecimal) + 2) ); emit MinTokensBeforeRewardUpdated(minTokensBeforeReward); } function setLpRewardEnabled(bool _enabled) public onlyOwner { lpRewardEnabled = _enabled; emit LpRewardEnabledUpdated(_enabled); } function setIsTransferLocked(bool enabled) public onlyOwner { isTransferLocked = enabled; } //to recieve ETH from uniswapV2Router when swaping receive() external payable {} }
_isExcludedFromFee[account] = false;
function includeInFee(address account) public onlyOwner
function includeInFee(address account) public onlyOwner
24313
SolidStamp
withdrawRequest
contract SolidStamp is Ownable, Pausable, Upgradable { using SafeMath for uint; /// @dev const value to indicate the contract is audited and approved uint8 public constant NOT_AUDITED = 0x00; /// @dev minimum amount of time for an audit request uint public constant MIN_AUDIT_TIME = 24 hours; /// @dev maximum amount of time for an audit request uint public constant MAX_AUDIT_TIME = 28 days; /// @dev aggregated amount of audit requests uint public TotalRequestsAmount = 0; // @dev amount of collected commision available to withdraw uint public AvailableCommission = 0; // @dev commission percentage, initially 1% uint public Commission = 1; /// @dev event fired when the service commission is changed event NewCommission(uint commmission); address public SolidStampRegisterAddress; /// @notice SolidStamp constructor constructor(address _addressRegistrySolidStamp) public { SolidStampRegisterAddress = _addressRegistrySolidStamp; } /// @notice Audit request struct AuditRequest { // amount of Ethers offered by a particular requestor for an audit uint amount; // request expiration date uint expireDate; } /// @dev Maps auditor and code hash to the total reward offered for auditing /// the particular contract by the particular auditor. /// Map key is: keccack256(auditor address, contract codeHash) /// @dev codeHash is a sha3 from the contract byte code mapping (bytes32 => uint) public Rewards; /// @dev Maps requestor, auditor and codeHash to an AuditRequest /// Map key is: keccack256(auditor address, requestor address, contract codeHash) mapping (bytes32 => AuditRequest) public AuditRequests; /// @dev event fired upon successul audit request event AuditRequested(address auditor, address bidder, bytes32 codeHash, uint amount, uint expireDate); /// @dev event fired when an request is sucessfully withdrawn event RequestWithdrawn(address auditor, address bidder, bytes32 codeHash, uint amount); /// @dev event fired when a contract is sucessfully audited event ContractAudited(address auditor, bytes32 codeHash, bytes reportIPFS, bool isApproved, uint reward); /// @notice registers an audit request /// @param _auditor the address of the auditor the request is directed to /// @param _codeHash the code hash of the contract to audit. _codeHash equals to sha3 of the contract byte-code /// @param _auditTime the amount of time after which the requestor can withdraw the request function requestAudit(address _auditor, bytes32 _codeHash, uint _auditTime) public whenNotPaused payable { require(_auditor != 0x0, "_auditor cannot be 0x0"); // audit request cannot expire too quickly or last too long require(_auditTime >= MIN_AUDIT_TIME, "_auditTime should be >= MIN_AUDIT_TIME"); require(_auditTime <= MAX_AUDIT_TIME, "_auditTime should be <= MIN_AUDIT_TIME"); require(msg.value > 0, "msg.value should be >0"); // revert if the contract is already audited by the auditor uint8 outcome = SolidStampRegister(SolidStampRegisterAddress).getAuditOutcome(_auditor, _codeHash); require(outcome == NOT_AUDITED, "contract already audited"); bytes32 hashAuditorCode = keccak256(abi.encodePacked(_auditor, _codeHash)); uint currentReward = Rewards[hashAuditorCode]; uint expireDate = now.add(_auditTime); Rewards[hashAuditorCode] = currentReward.add(msg.value); TotalRequestsAmount = TotalRequestsAmount.add(msg.value); bytes32 hashAuditorRequestorCode = keccak256(abi.encodePacked(_auditor, msg.sender, _codeHash)); AuditRequest storage request = AuditRequests[hashAuditorRequestorCode]; if ( request.amount == 0 ) { // first request from msg.sender to audit contract _codeHash by _auditor AuditRequests[hashAuditorRequestorCode] = AuditRequest({ amount : msg.value, expireDate : expireDate }); emit AuditRequested(_auditor, msg.sender, _codeHash, msg.value, expireDate); } else { // Request already exists. Increasing value request.amount = request.amount.add(msg.value); // if new expireDate is later than existing one - increase the existing one if ( expireDate > request.expireDate ) request.expireDate = expireDate; // event returns the total request value and its expireDate emit AuditRequested(_auditor, msg.sender, _codeHash, request.amount, request.expireDate); } } /// @notice withdraws an audit request /// @param _auditor the address of the auditor the request is directed to /// @param _codeHash the code hash of the contract to audit. _codeHash equals to sha3 of the contract byte-code function withdrawRequest(address _auditor, bytes32 _codeHash) public {<FILL_FUNCTION_BODY> } /// @notice transfers reward to the auditor. Called by SolidStampRegister after the contract is audited /// @param _auditor the auditor who audited the contract /// @param _codeHash the code hash of the stamped contract. _codeHash equals to sha3 of the contract byte-code /// @param _reportIPFS IPFS hash of the audit report /// @param _isApproved whether the contract is approved or rejected function auditContract(address _auditor, bytes32 _codeHash, bytes _reportIPFS, bool _isApproved) public whenNotPaused onlySolidStampRegisterContract { bytes32 hashAuditorCode = keccak256(abi.encodePacked(_auditor, _codeHash)); uint reward = Rewards[hashAuditorCode]; TotalRequestsAmount = TotalRequestsAmount.sub(reward); uint commissionKept = calcCommission(reward); AvailableCommission = AvailableCommission.add(commissionKept); emit ContractAudited(_auditor, _codeHash, _reportIPFS, _isApproved, reward); _auditor.transfer(reward.sub(commissionKept)); } /** * @dev Throws if called by any account other than the contractSolidStamp */ modifier onlySolidStampRegisterContract() { require(msg.sender == SolidStampRegisterAddress, "can be only run by SolidStampRegister contract"); _; } /// @dev const value to indicate the maximum commision service owner can set uint public constant MAX_COMMISSION = 9; /// @notice ability for owner to change the service commmission /// @param _newCommission new commision percentage function changeCommission(uint _newCommission) public onlyOwner whenNotPaused { require(_newCommission <= MAX_COMMISSION, "commission should be <= MAX_COMMISSION"); require(_newCommission != Commission, "_newCommission==Commmission"); Commission = _newCommission; emit NewCommission(Commission); } /// @notice calculates the SolidStamp commmission /// @param _amount amount to calcuate the commission from function calcCommission(uint _amount) private view returns(uint) { return _amount.mul(Commission)/100; // service commision } /// @notice ability for owner to withdraw the commission /// @param _amount amount to withdraw function withdrawCommission(uint _amount) public onlyOwner { // cannot withdraw money reserved for requests require(_amount <= AvailableCommission, "Cannot withdraw more than available"); AvailableCommission = AvailableCommission.sub(_amount); msg.sender.transfer(_amount); } /// @dev Override unpause so we can't have newContractAddress set, /// because then the contract was upgraded. /// @notice This is public rather than external so we can call super.unpause /// without using an expensive CALL. function unpause() public onlyOwner whenPaused { require(newContractAddress == address(0), "new contract cannot be 0x0"); // Actually unpause the contract. super.unpause(); } /// @notice We don't want your arbitrary ether function() payable public { revert(); } }
contract SolidStamp is Ownable, Pausable, Upgradable { using SafeMath for uint; /// @dev const value to indicate the contract is audited and approved uint8 public constant NOT_AUDITED = 0x00; /// @dev minimum amount of time for an audit request uint public constant MIN_AUDIT_TIME = 24 hours; /// @dev maximum amount of time for an audit request uint public constant MAX_AUDIT_TIME = 28 days; /// @dev aggregated amount of audit requests uint public TotalRequestsAmount = 0; // @dev amount of collected commision available to withdraw uint public AvailableCommission = 0; // @dev commission percentage, initially 1% uint public Commission = 1; /// @dev event fired when the service commission is changed event NewCommission(uint commmission); address public SolidStampRegisterAddress; /// @notice SolidStamp constructor constructor(address _addressRegistrySolidStamp) public { SolidStampRegisterAddress = _addressRegistrySolidStamp; } /// @notice Audit request struct AuditRequest { // amount of Ethers offered by a particular requestor for an audit uint amount; // request expiration date uint expireDate; } /// @dev Maps auditor and code hash to the total reward offered for auditing /// the particular contract by the particular auditor. /// Map key is: keccack256(auditor address, contract codeHash) /// @dev codeHash is a sha3 from the contract byte code mapping (bytes32 => uint) public Rewards; /// @dev Maps requestor, auditor and codeHash to an AuditRequest /// Map key is: keccack256(auditor address, requestor address, contract codeHash) mapping (bytes32 => AuditRequest) public AuditRequests; /// @dev event fired upon successul audit request event AuditRequested(address auditor, address bidder, bytes32 codeHash, uint amount, uint expireDate); /// @dev event fired when an request is sucessfully withdrawn event RequestWithdrawn(address auditor, address bidder, bytes32 codeHash, uint amount); /// @dev event fired when a contract is sucessfully audited event ContractAudited(address auditor, bytes32 codeHash, bytes reportIPFS, bool isApproved, uint reward); /// @notice registers an audit request /// @param _auditor the address of the auditor the request is directed to /// @param _codeHash the code hash of the contract to audit. _codeHash equals to sha3 of the contract byte-code /// @param _auditTime the amount of time after which the requestor can withdraw the request function requestAudit(address _auditor, bytes32 _codeHash, uint _auditTime) public whenNotPaused payable { require(_auditor != 0x0, "_auditor cannot be 0x0"); // audit request cannot expire too quickly or last too long require(_auditTime >= MIN_AUDIT_TIME, "_auditTime should be >= MIN_AUDIT_TIME"); require(_auditTime <= MAX_AUDIT_TIME, "_auditTime should be <= MIN_AUDIT_TIME"); require(msg.value > 0, "msg.value should be >0"); // revert if the contract is already audited by the auditor uint8 outcome = SolidStampRegister(SolidStampRegisterAddress).getAuditOutcome(_auditor, _codeHash); require(outcome == NOT_AUDITED, "contract already audited"); bytes32 hashAuditorCode = keccak256(abi.encodePacked(_auditor, _codeHash)); uint currentReward = Rewards[hashAuditorCode]; uint expireDate = now.add(_auditTime); Rewards[hashAuditorCode] = currentReward.add(msg.value); TotalRequestsAmount = TotalRequestsAmount.add(msg.value); bytes32 hashAuditorRequestorCode = keccak256(abi.encodePacked(_auditor, msg.sender, _codeHash)); AuditRequest storage request = AuditRequests[hashAuditorRequestorCode]; if ( request.amount == 0 ) { // first request from msg.sender to audit contract _codeHash by _auditor AuditRequests[hashAuditorRequestorCode] = AuditRequest({ amount : msg.value, expireDate : expireDate }); emit AuditRequested(_auditor, msg.sender, _codeHash, msg.value, expireDate); } else { // Request already exists. Increasing value request.amount = request.amount.add(msg.value); // if new expireDate is later than existing one - increase the existing one if ( expireDate > request.expireDate ) request.expireDate = expireDate; // event returns the total request value and its expireDate emit AuditRequested(_auditor, msg.sender, _codeHash, request.amount, request.expireDate); } } <FILL_FUNCTION> /// @notice transfers reward to the auditor. Called by SolidStampRegister after the contract is audited /// @param _auditor the auditor who audited the contract /// @param _codeHash the code hash of the stamped contract. _codeHash equals to sha3 of the contract byte-code /// @param _reportIPFS IPFS hash of the audit report /// @param _isApproved whether the contract is approved or rejected function auditContract(address _auditor, bytes32 _codeHash, bytes _reportIPFS, bool _isApproved) public whenNotPaused onlySolidStampRegisterContract { bytes32 hashAuditorCode = keccak256(abi.encodePacked(_auditor, _codeHash)); uint reward = Rewards[hashAuditorCode]; TotalRequestsAmount = TotalRequestsAmount.sub(reward); uint commissionKept = calcCommission(reward); AvailableCommission = AvailableCommission.add(commissionKept); emit ContractAudited(_auditor, _codeHash, _reportIPFS, _isApproved, reward); _auditor.transfer(reward.sub(commissionKept)); } /** * @dev Throws if called by any account other than the contractSolidStamp */ modifier onlySolidStampRegisterContract() { require(msg.sender == SolidStampRegisterAddress, "can be only run by SolidStampRegister contract"); _; } /// @dev const value to indicate the maximum commision service owner can set uint public constant MAX_COMMISSION = 9; /// @notice ability for owner to change the service commmission /// @param _newCommission new commision percentage function changeCommission(uint _newCommission) public onlyOwner whenNotPaused { require(_newCommission <= MAX_COMMISSION, "commission should be <= MAX_COMMISSION"); require(_newCommission != Commission, "_newCommission==Commmission"); Commission = _newCommission; emit NewCommission(Commission); } /// @notice calculates the SolidStamp commmission /// @param _amount amount to calcuate the commission from function calcCommission(uint _amount) private view returns(uint) { return _amount.mul(Commission)/100; // service commision } /// @notice ability for owner to withdraw the commission /// @param _amount amount to withdraw function withdrawCommission(uint _amount) public onlyOwner { // cannot withdraw money reserved for requests require(_amount <= AvailableCommission, "Cannot withdraw more than available"); AvailableCommission = AvailableCommission.sub(_amount); msg.sender.transfer(_amount); } /// @dev Override unpause so we can't have newContractAddress set, /// because then the contract was upgraded. /// @notice This is public rather than external so we can call super.unpause /// without using an expensive CALL. function unpause() public onlyOwner whenPaused { require(newContractAddress == address(0), "new contract cannot be 0x0"); // Actually unpause the contract. super.unpause(); } /// @notice We don't want your arbitrary ether function() payable public { revert(); } }
bytes32 hashAuditorCode = keccak256(abi.encodePacked(_auditor, _codeHash)); // revert if the contract is already audited by the auditor uint8 outcome = SolidStampRegister(SolidStampRegisterAddress).getAuditOutcome(_auditor, _codeHash); require(outcome == NOT_AUDITED, "contract already audited"); bytes32 hashAuditorRequestorCode = keccak256(abi.encodePacked(_auditor, msg.sender, _codeHash)); AuditRequest storage request = AuditRequests[hashAuditorRequestorCode]; require(request.amount > 0, "nothing to withdraw"); require(now > request.expireDate, "cannot withdraw before request.expireDate"); uint amount = request.amount; delete request.amount; delete request.expireDate; Rewards[hashAuditorCode] = Rewards[hashAuditorCode].sub(amount); TotalRequestsAmount = TotalRequestsAmount.sub(amount); emit RequestWithdrawn(_auditor, msg.sender, _codeHash, amount); msg.sender.transfer(amount);
function withdrawRequest(address _auditor, bytes32 _codeHash) public
/// @notice withdraws an audit request /// @param _auditor the address of the auditor the request is directed to /// @param _codeHash the code hash of the contract to audit. _codeHash equals to sha3 of the contract byte-code function withdrawRequest(address _auditor, bytes32 _codeHash) public
67983
MinimalLenderFirstResortOverlay
modifyParameters
contract MinimalLenderFirstResortOverlay is GebAuth { GebLenderFirstResortRewardsLike public staking; // Max amount of staked tokens to keep uint256 public maxStakedTokensToKeep; constructor(address staking_, uint256 maxStakedTokensToKeep_) public GebAuth() { require(staking_ != address(0), "MinimalLenderFirstResortOverlay/null-address"); require(maxStakedTokensToKeep_ > 0, "MinimalLenderFirstResortOverlay/null-maxStakedTokensToKeep"); staking = GebLenderFirstResortRewardsLike(staking_); maxStakedTokensToKeep = maxStakedTokensToKeep_; } /* * @notify Modify escrowPaused * @param parameter Must be "escrowPaused" * @param data The new value for escrowPaused */ function modifyParameters(bytes32 parameter, uint256 data) external isAuthorized {<FILL_FUNCTION_BODY> } }
contract MinimalLenderFirstResortOverlay is GebAuth { GebLenderFirstResortRewardsLike public staking; // Max amount of staked tokens to keep uint256 public maxStakedTokensToKeep; constructor(address staking_, uint256 maxStakedTokensToKeep_) public GebAuth() { require(staking_ != address(0), "MinimalLenderFirstResortOverlay/null-address"); require(maxStakedTokensToKeep_ > 0, "MinimalLenderFirstResortOverlay/null-maxStakedTokensToKeep"); staking = GebLenderFirstResortRewardsLike(staking_); maxStakedTokensToKeep = maxStakedTokensToKeep_; } <FILL_FUNCTION> }
if (parameter == "minStakedTokensToKeep") { require(data <= maxStakedTokensToKeep, "MinimalLenderFirstResortOverlay/minStakedTokensToKeep-over-limit"); staking.modifyParameters(parameter, data); } else if ( parameter == "escrowPaused" || parameter == "bypassAuctions" || parameter == "tokensToAuction" || parameter == "systemCoinsToRequest" ) staking.modifyParameters(parameter, data); else revert("MinimalLenderFirstResortOverlay/modify-forbidden-param");
function modifyParameters(bytes32 parameter, uint256 data) external isAuthorized
/* * @notify Modify escrowPaused * @param parameter Must be "escrowPaused" * @param data The new value for escrowPaused */ function modifyParameters(bytes32 parameter, uint256 data) external isAuthorized
83891
GalacticBunny
setBotFees
contract GalacticBunny 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 = 1000000000000 * (10**9); uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; mapping(address => bool) private _isExcludedFromAntiWhale; string private _name = "GALACTIC BUNNY"; string private _symbol = "GBTK"; uint8 private _decimals = 9; uint256 public _taxFee = 1; uint256 private _previousTaxFee = _taxFee; uint256 public _liquidityFee = 2; uint256 private _previousLiquidityFee = _liquidityFee; bool public launchAddLiquidity = false; uint256 public launchTime = 0; uint256 public timeDetectBotSeconds = 2; uint256 public timeAntiBot = 60 * timeDetectBotSeconds; mapping(address => bool) _isBot; address public deadAddress = 0x000000000000000000000000000000000000dEaD; bool private enableAntiwhale = true; uint256 public _devFee = 2; address public devWallet = 0x8D3c47ba0DA7D0dAEeB92fD40b3BF5Eb5CA1DA42; address public marketingWallet = 0x85BBc0cd8438E54E38Aa310d395303312f089D0F; uint256 public _marketingFee = 8; uint256 public _botIncreaseFee = 3; uint256 private _previousMarketingFee = _marketingFee; uint256 private _previousDevFee = _devFee; uint256 public totalFeesTax = _taxFee.add(_liquidityFee).add(_devFee).add(_marketingFee); IUniswapV2Router02 public uniswapV2Router; address public uniswapV2Pair; bool public antibotSystemEnable = true; uint public maxTransferAmountRate = 500; bool private inSwapAndLiquify; bool public swapAndLiquifyEnabled = true; uint256 public numTokensSellToAddToLiquidity = 1000000000 * 10**9; event MinTokensBeforeSwapUpdated(uint256 minTokensBeforeSwap); event SwapAndLiquifyEnabledUpdated(bool enabled); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiqudity ); constructor(address _newOwner) { transferOwnership(_newOwner); _rOwned[owner()] = _rTotal; IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); uniswapV2Router = _uniswapV2Router; _isExcludedFromFee[owner()] = true; _isExcludedFromFee[devWallet] = true; _isExcludedFromFee[address(this)] = true; _isExcludedFromAntiWhale[msg.sender] = true; _isExcludedFromAntiWhale[address(0)] = true; _isExcludedFromAntiWhale[address(this)] = true; _isExcludedFromAntiWhale[deadAddress] = true; emit Transfer(address(0), owner(), _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 setBotSettingTime(uint256 _val) public onlyOwner { require(launchTime == 0 && _val <= 5, "Already launched or max 5 minuts."); timeDetectBotSeconds = _val; timeAntiBot = 60 * _val; } function excludeAntibot(address ac) public onlyOwner { require(_isBot[ac], "not bot"); _isBot[ac] = false; } 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 setAntiBotSystemEnable(bool _status) public onlyOwner { require(launchTime == 0, "Already launched, not necessary."); antibotSystemEnable = _status; } 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 setBotFeeMultiplicator(uint256 _val) public onlyOwner { require(_val <= 3 && launchTime == 0, "max x3 and not launched"); _botIncreaseFee = _val; } 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 isExcludedFromAntiWhale(address account) public view returns(bool) { return _isExcludedFromAntiWhale[account]; } function totalFees() public view returns (uint256) { return _tFeeTotal; } function deliver(uint256 tAmount) public { address sender = _msgSender(); require(!_isExcluded[sender], "Excluded addresses cannot call this function"); (uint256 rAmount,,,,,) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rTotal = _rTotal.sub(rAmount); _tFeeTotal = _tFeeTotal.add(tAmount); } function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns(uint256) { require(tAmount <= _tTotal, "Amount must be less than supply"); if (!deductTransferFee) { (uint256 rAmount,,,,,) = _getValues(tAmount); return rAmount; } else { (,uint256 rTransferAmount,,,,) = _getValues(tAmount); return rTransferAmount; } } function tokenFromReflection(uint256 rAmount) public view returns(uint256) { require(rAmount <= _rTotal, "Amount must be less than total reflections"); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function excludeFromReward(address account) public onlyOwner() { require(!_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); } //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 && _devFee ==0 && _marketingFee == 0) return; _previousTaxFee = _taxFee; _previousLiquidityFee = _liquidityFee; _previousDevFee = _devFee; _previousMarketingFee = _marketingFee; _taxFee = 0; _marketingFee = 0; _liquidityFee = 0; _devFee = 0; } function restoreAllFee() private { _taxFee = _previousTaxFee; _liquidityFee = _previousLiquidityFee; _devFee = _previousDevFee; _marketingFee = _previousMarketingFee; } 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 isBot(address acc) public view returns(bool) { return _isBot[acc]; } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if (to == uniswapV2Pair) { if(!launchAddLiquidity && launchTime == 0) { launchAddLiquidity = true; launchTime = block.timestamp; } } if(launchTime > 0) { if(block.timestamp - launchTime <= timeAntiBot && from == uniswapV2Pair) { _isBot[to] = true; } } // 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)); bool overMinTokenBalance = contractTokenBalance >= numTokensSellToAddToLiquidity; if ( overMinTokenBalance && !inSwapAndLiquify && from != uniswapV2Pair && swapAndLiquifyEnabled ) { inSwapAndLiquify = true; contractTokenBalance = numTokensSellToAddToLiquidity; //add liquidity uint256 totalTaxForSwap = _liquidityFee.add(_marketingFee).add(_devFee); if (_marketingFee > 0) { uint256 marketingTokens = contractTokenBalance.mul(_marketingFee).div(totalTaxForSwap); swapAndSendMarketing(marketingTokens); } if(_devFee > 0) { uint256 tokensForDev = contractTokenBalance.mul(_devFee).div(totalTaxForSwap); swapAndSendDev(tokensForDev); } swapAndLiquify(contractTokenBalance.mul(_liquidityFee).div(totalTaxForSwap)); inSwapAndLiquify = false; } //transfer amount, it will take tax, burn, liquidity fee _tokenTransfer(from,to,amount); } function swapAndSendMarketing(uint256 tokens) internal { uint256 initialBalance = address(this).balance; // swap tokens for ETH swapTokensForEth(tokens); uint256 newBalance = address(this).balance.sub(initialBalance); (bool success,) = address(marketingWallet).call{value: newBalance}(""); if (success) { } } function swapAndSendDev(uint256 tokens) internal { uint256 initialBalance = address(this).balance; // swap tokens for ETH swapTokensForEth(tokens); uint256 newBalance = address(this).balance.sub(initialBalance); (bool success,) = address(devWallet).call{value: newBalance}(""); if (success) { } } function swapAndLiquify(uint256 contractTokenBalance) private { // split the contract balance into halves 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); // 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 deadAddress, block.timestamp ); } function setBotFees() private {<FILL_FUNCTION_BODY> } function setExcludedFromAntiWhale(address account, bool exclude) public onlyOwner { _isExcludedFromAntiWhale[account] = exclude; } function setEnableAntiwhale(bool _val) public onlyOwner { enableAntiwhale = _val; } function maxTransferAmount() public view returns (uint256) { // we can either use a percentage of supply if(maxTransferAmountRate > 0){ return totalSupply().mul(maxTransferAmountRate).div(10000); } // or we can just use default number 1%. return totalSupply().mul(100).div(10000); } function setMaxTransferAmountRate(uint256 _val) public onlyOwner { require(_val <= 500, "max 5%"); maxTransferAmountRate = _val; } //this method is responsible for taking all fee, if takeFee is true function _tokenTransfer(address sender, address recipient, uint256 amount) private { if (enableAntiwhale && maxTransferAmount() > 0) { if ( _isExcludedFromAntiWhale[sender] == false && _isExcludedFromAntiWhale[recipient] == false ) { require(amount <= maxTransferAmount(), "AntiWhale: Transfer amount exceeds the maxTransferAmount"); } } if(_isExcludedFromFee[sender] || _isExcludedFromFee[recipient]) { removeAllFee(); } if(_isBot[recipient] || _isBot[sender]) { setBotFees(); } 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(_isBot[recipient] || _isBot[sender]) { restoreAllFee(); } if(_isExcludedFromFee[sender] || _isExcludedFromFee[recipient]) { restoreAllFee(); } } function _transferStandard(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount); (tTransferAmount, rTransferAmount) = takeDev(sender, tTransferAmount, rTransferAmount, tAmount); (tTransferAmount, rTransferAmount) = takeMarketing(sender, tTransferAmount, rTransferAmount, tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function takeDev(address sender, uint256 tTransferAmount, uint256 rTransferAmount, uint256 tAmount) private returns (uint256, uint256) { if(_devFee==0) { return(tTransferAmount, rTransferAmount); } uint256 tDev = tAmount.div(100).mul(_devFee); uint256 rDev = tDev.mul(_getRate()); rTransferAmount = rTransferAmount.sub(rDev); tTransferAmount = tTransferAmount.sub(tDev); _rOwned[address(this)] = _rOwned[address(this)].add(rDev); emit Transfer(sender, address(this), tDev); return(tTransferAmount, rTransferAmount); } function takeMarketing(address sender, uint256 tTransferAmount, uint256 rTransferAmount, uint256 tAmount) private returns (uint256, uint256) { if(_marketingFee==0) { return(tTransferAmount, rTransferAmount); } uint256 tMarketing = tAmount.div(100).mul(_marketingFee); uint256 rMarketing = tMarketing.mul(_getRate()); rTransferAmount = rTransferAmount.sub(rMarketing); tTransferAmount = tTransferAmount.sub(tMarketing); _rOwned[address(this)] = _rOwned[address(this)].add(rMarketing); emit Transfer(sender, address(this), tMarketing); return(tTransferAmount, rTransferAmount); } function _transferToExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferFromExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function excludeFromFee(address account) public onlyOwner { _isExcludedFromFee[account] = true; } function includeInFee(address account) public onlyOwner { _isExcludedFromFee[account] = false; } function setdevWallet(address newWallet) external onlyOwner() { devWallet = newWallet; } function setMarketingWallet(address newWallet) external onlyOwner() { marketingWallet = newWallet; } function setDevFee(uint256 devFee) external onlyOwner() { _devFee = devFee; totalFeesTax = _taxFee.add(_devFee).add(_marketingFee).add(_liquidityFee); require(totalFeesTax <= 20, "max 20%"); } function setTaxFeePercent(uint256 taxFee) external onlyOwner() { _taxFee = taxFee; totalFeesTax = _taxFee.add(_devFee).add(_marketingFee).add(_liquidityFee); require(totalFeesTax <= 20, "max 20%"); } function setMarketingFee(uint256 marketingF) external onlyOwner { _marketingFee = marketingF; totalFeesTax = _taxFee.add(_devFee).add(_marketingFee).add(_liquidityFee); require(totalFeesTax <= 20, "max 20%"); } function setLiquidityFeePercent(uint256 liquidityFee) external onlyOwner() { _liquidityFee = liquidityFee; totalFeesTax = _taxFee.add(_devFee).add(_marketingFee).add(_liquidityFee); require(totalFeesTax <= 20, "max 20%"); } function setNumTokensSellToAddToLiquidity(uint256 newAmt) external onlyOwner() { numTokensSellToAddToLiquidity = newAmt*10**9; } function setSwapAndLiquifyEnabled(bool _enabled) public onlyOwner { swapAndLiquifyEnabled = _enabled; emit SwapAndLiquifyEnabledUpdated(_enabled); } }
contract GalacticBunny 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 = 1000000000000 * (10**9); uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; mapping(address => bool) private _isExcludedFromAntiWhale; string private _name = "GALACTIC BUNNY"; string private _symbol = "GBTK"; uint8 private _decimals = 9; uint256 public _taxFee = 1; uint256 private _previousTaxFee = _taxFee; uint256 public _liquidityFee = 2; uint256 private _previousLiquidityFee = _liquidityFee; bool public launchAddLiquidity = false; uint256 public launchTime = 0; uint256 public timeDetectBotSeconds = 2; uint256 public timeAntiBot = 60 * timeDetectBotSeconds; mapping(address => bool) _isBot; address public deadAddress = 0x000000000000000000000000000000000000dEaD; bool private enableAntiwhale = true; uint256 public _devFee = 2; address public devWallet = 0x8D3c47ba0DA7D0dAEeB92fD40b3BF5Eb5CA1DA42; address public marketingWallet = 0x85BBc0cd8438E54E38Aa310d395303312f089D0F; uint256 public _marketingFee = 8; uint256 public _botIncreaseFee = 3; uint256 private _previousMarketingFee = _marketingFee; uint256 private _previousDevFee = _devFee; uint256 public totalFeesTax = _taxFee.add(_liquidityFee).add(_devFee).add(_marketingFee); IUniswapV2Router02 public uniswapV2Router; address public uniswapV2Pair; bool public antibotSystemEnable = true; uint public maxTransferAmountRate = 500; bool private inSwapAndLiquify; bool public swapAndLiquifyEnabled = true; uint256 public numTokensSellToAddToLiquidity = 1000000000 * 10**9; event MinTokensBeforeSwapUpdated(uint256 minTokensBeforeSwap); event SwapAndLiquifyEnabledUpdated(bool enabled); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiqudity ); constructor(address _newOwner) { transferOwnership(_newOwner); _rOwned[owner()] = _rTotal; IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); uniswapV2Router = _uniswapV2Router; _isExcludedFromFee[owner()] = true; _isExcludedFromFee[devWallet] = true; _isExcludedFromFee[address(this)] = true; _isExcludedFromAntiWhale[msg.sender] = true; _isExcludedFromAntiWhale[address(0)] = true; _isExcludedFromAntiWhale[address(this)] = true; _isExcludedFromAntiWhale[deadAddress] = true; emit Transfer(address(0), owner(), _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 setBotSettingTime(uint256 _val) public onlyOwner { require(launchTime == 0 && _val <= 5, "Already launched or max 5 minuts."); timeDetectBotSeconds = _val; timeAntiBot = 60 * _val; } function excludeAntibot(address ac) public onlyOwner { require(_isBot[ac], "not bot"); _isBot[ac] = false; } 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 setAntiBotSystemEnable(bool _status) public onlyOwner { require(launchTime == 0, "Already launched, not necessary."); antibotSystemEnable = _status; } 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 setBotFeeMultiplicator(uint256 _val) public onlyOwner { require(_val <= 3 && launchTime == 0, "max x3 and not launched"); _botIncreaseFee = _val; } 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 isExcludedFromAntiWhale(address account) public view returns(bool) { return _isExcludedFromAntiWhale[account]; } function totalFees() public view returns (uint256) { return _tFeeTotal; } function deliver(uint256 tAmount) public { address sender = _msgSender(); require(!_isExcluded[sender], "Excluded addresses cannot call this function"); (uint256 rAmount,,,,,) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rTotal = _rTotal.sub(rAmount); _tFeeTotal = _tFeeTotal.add(tAmount); } function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns(uint256) { require(tAmount <= _tTotal, "Amount must be less than supply"); if (!deductTransferFee) { (uint256 rAmount,,,,,) = _getValues(tAmount); return rAmount; } else { (,uint256 rTransferAmount,,,,) = _getValues(tAmount); return rTransferAmount; } } function tokenFromReflection(uint256 rAmount) public view returns(uint256) { require(rAmount <= _rTotal, "Amount must be less than total reflections"); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function excludeFromReward(address account) public onlyOwner() { require(!_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); } //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 && _devFee ==0 && _marketingFee == 0) return; _previousTaxFee = _taxFee; _previousLiquidityFee = _liquidityFee; _previousDevFee = _devFee; _previousMarketingFee = _marketingFee; _taxFee = 0; _marketingFee = 0; _liquidityFee = 0; _devFee = 0; } function restoreAllFee() private { _taxFee = _previousTaxFee; _liquidityFee = _previousLiquidityFee; _devFee = _previousDevFee; _marketingFee = _previousMarketingFee; } 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 isBot(address acc) public view returns(bool) { return _isBot[acc]; } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if (to == uniswapV2Pair) { if(!launchAddLiquidity && launchTime == 0) { launchAddLiquidity = true; launchTime = block.timestamp; } } if(launchTime > 0) { if(block.timestamp - launchTime <= timeAntiBot && from == uniswapV2Pair) { _isBot[to] = true; } } // 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)); bool overMinTokenBalance = contractTokenBalance >= numTokensSellToAddToLiquidity; if ( overMinTokenBalance && !inSwapAndLiquify && from != uniswapV2Pair && swapAndLiquifyEnabled ) { inSwapAndLiquify = true; contractTokenBalance = numTokensSellToAddToLiquidity; //add liquidity uint256 totalTaxForSwap = _liquidityFee.add(_marketingFee).add(_devFee); if (_marketingFee > 0) { uint256 marketingTokens = contractTokenBalance.mul(_marketingFee).div(totalTaxForSwap); swapAndSendMarketing(marketingTokens); } if(_devFee > 0) { uint256 tokensForDev = contractTokenBalance.mul(_devFee).div(totalTaxForSwap); swapAndSendDev(tokensForDev); } swapAndLiquify(contractTokenBalance.mul(_liquidityFee).div(totalTaxForSwap)); inSwapAndLiquify = false; } //transfer amount, it will take tax, burn, liquidity fee _tokenTransfer(from,to,amount); } function swapAndSendMarketing(uint256 tokens) internal { uint256 initialBalance = address(this).balance; // swap tokens for ETH swapTokensForEth(tokens); uint256 newBalance = address(this).balance.sub(initialBalance); (bool success,) = address(marketingWallet).call{value: newBalance}(""); if (success) { } } function swapAndSendDev(uint256 tokens) internal { uint256 initialBalance = address(this).balance; // swap tokens for ETH swapTokensForEth(tokens); uint256 newBalance = address(this).balance.sub(initialBalance); (bool success,) = address(devWallet).call{value: newBalance}(""); if (success) { } } function swapAndLiquify(uint256 contractTokenBalance) private { // split the contract balance into halves 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); // 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 deadAddress, block.timestamp ); } <FILL_FUNCTION> function setExcludedFromAntiWhale(address account, bool exclude) public onlyOwner { _isExcludedFromAntiWhale[account] = exclude; } function setEnableAntiwhale(bool _val) public onlyOwner { enableAntiwhale = _val; } function maxTransferAmount() public view returns (uint256) { // we can either use a percentage of supply if(maxTransferAmountRate > 0){ return totalSupply().mul(maxTransferAmountRate).div(10000); } // or we can just use default number 1%. return totalSupply().mul(100).div(10000); } function setMaxTransferAmountRate(uint256 _val) public onlyOwner { require(_val <= 500, "max 5%"); maxTransferAmountRate = _val; } //this method is responsible for taking all fee, if takeFee is true function _tokenTransfer(address sender, address recipient, uint256 amount) private { if (enableAntiwhale && maxTransferAmount() > 0) { if ( _isExcludedFromAntiWhale[sender] == false && _isExcludedFromAntiWhale[recipient] == false ) { require(amount <= maxTransferAmount(), "AntiWhale: Transfer amount exceeds the maxTransferAmount"); } } if(_isExcludedFromFee[sender] || _isExcludedFromFee[recipient]) { removeAllFee(); } if(_isBot[recipient] || _isBot[sender]) { setBotFees(); } 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(_isBot[recipient] || _isBot[sender]) { restoreAllFee(); } if(_isExcludedFromFee[sender] || _isExcludedFromFee[recipient]) { restoreAllFee(); } } function _transferStandard(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount); (tTransferAmount, rTransferAmount) = takeDev(sender, tTransferAmount, rTransferAmount, tAmount); (tTransferAmount, rTransferAmount) = takeMarketing(sender, tTransferAmount, rTransferAmount, tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function takeDev(address sender, uint256 tTransferAmount, uint256 rTransferAmount, uint256 tAmount) private returns (uint256, uint256) { if(_devFee==0) { return(tTransferAmount, rTransferAmount); } uint256 tDev = tAmount.div(100).mul(_devFee); uint256 rDev = tDev.mul(_getRate()); rTransferAmount = rTransferAmount.sub(rDev); tTransferAmount = tTransferAmount.sub(tDev); _rOwned[address(this)] = _rOwned[address(this)].add(rDev); emit Transfer(sender, address(this), tDev); return(tTransferAmount, rTransferAmount); } function takeMarketing(address sender, uint256 tTransferAmount, uint256 rTransferAmount, uint256 tAmount) private returns (uint256, uint256) { if(_marketingFee==0) { return(tTransferAmount, rTransferAmount); } uint256 tMarketing = tAmount.div(100).mul(_marketingFee); uint256 rMarketing = tMarketing.mul(_getRate()); rTransferAmount = rTransferAmount.sub(rMarketing); tTransferAmount = tTransferAmount.sub(tMarketing); _rOwned[address(this)] = _rOwned[address(this)].add(rMarketing); emit Transfer(sender, address(this), tMarketing); return(tTransferAmount, rTransferAmount); } function _transferToExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferFromExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function excludeFromFee(address account) public onlyOwner { _isExcludedFromFee[account] = true; } function includeInFee(address account) public onlyOwner { _isExcludedFromFee[account] = false; } function setdevWallet(address newWallet) external onlyOwner() { devWallet = newWallet; } function setMarketingWallet(address newWallet) external onlyOwner() { marketingWallet = newWallet; } function setDevFee(uint256 devFee) external onlyOwner() { _devFee = devFee; totalFeesTax = _taxFee.add(_devFee).add(_marketingFee).add(_liquidityFee); require(totalFeesTax <= 20, "max 20%"); } function setTaxFeePercent(uint256 taxFee) external onlyOwner() { _taxFee = taxFee; totalFeesTax = _taxFee.add(_devFee).add(_marketingFee).add(_liquidityFee); require(totalFeesTax <= 20, "max 20%"); } function setMarketingFee(uint256 marketingF) external onlyOwner { _marketingFee = marketingF; totalFeesTax = _taxFee.add(_devFee).add(_marketingFee).add(_liquidityFee); require(totalFeesTax <= 20, "max 20%"); } function setLiquidityFeePercent(uint256 liquidityFee) external onlyOwner() { _liquidityFee = liquidityFee; totalFeesTax = _taxFee.add(_devFee).add(_marketingFee).add(_liquidityFee); require(totalFeesTax <= 20, "max 20%"); } function setNumTokensSellToAddToLiquidity(uint256 newAmt) external onlyOwner() { numTokensSellToAddToLiquidity = newAmt*10**9; } function setSwapAndLiquifyEnabled(bool _enabled) public onlyOwner { swapAndLiquifyEnabled = _enabled; emit SwapAndLiquifyEnabledUpdated(_enabled); } }
if(_taxFee == 0 && _liquidityFee == 0 && _devFee ==0 && _marketingFee == 0) return; _previousTaxFee = _taxFee; _previousLiquidityFee = _liquidityFee; _previousDevFee = _devFee; _previousMarketingFee = _marketingFee; _taxFee = _previousTaxFee * _botIncreaseFee; _marketingFee = _previousMarketingFee * _botIncreaseFee; _liquidityFee = _previousLiquidityFee * _botIncreaseFee; _devFee = _previousDevFee * _botIncreaseFee;
function setBotFees() private
function setBotFees() private
40558
ShieldEX
null
contract ShieldEX is ERC20("ShieldEX", "SLD"), Ownable { constructor () public{<FILL_FUNCTION_BODY> } }
contract ShieldEX is ERC20("ShieldEX", "SLD"), Ownable { <FILL_FUNCTION> }
_mint(_msgSender(), 1000000000 * 1e18);
constructor () public
constructor () public
61285
ERC20
transferFrom
contract ERC20 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 _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_) { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the bep token owner. */ function getOwner() external override view returns (address) { return owner(); } /** * @dev Returns the token name. */ function name() public override view returns (string memory) { return _name; } /** * @dev Returns the token decimals. */ function decimals() public override view returns (uint8) { return _decimals; } /** * @dev Returns the token symbol. */ function symbol() public override view returns (string memory) { return _symbol; } /** * @dev See {ERC20-totalSupply}. */ function totalSupply() public override view returns (uint256) { return _totalSupply; } /** * @dev See {ERC20-balanceOf}. */ function balanceOf(address account) public override view returns (uint256) { return _balances[account]; } /** * @dev See {ERC20-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 override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {ERC20-allowance}. */ function allowance(address owner, address spender) public override view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {ERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {ERC20-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 override returns (bool) {<FILL_FUNCTION_BODY> } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {ERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public 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 {ERC20-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 returns (bool) { _approve( _msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, 'ERC20: decreased allowance below zero') ); return true; } /** * @dev Creates `amount` tokens and assigns them to `msg.sender`, increasing * the total supply. * * Requirements * * - `msg.sender` must be the token owner */ function mint(uint256 amount) public onlyOwner returns (bool) { _createInitialSupply(_msgSender(), amount); 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'); _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 _createInitialSupply(address account, uint256 amount) internal { require(account != address(0), 'ERC20: mint to the zero address'); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @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 { 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); } /** * @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 { 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 Destroys `amount` tokens from `account`.`amount` is then deducted * from the caller's allowance. * * See {_burn} and {_approve}. */ function _burnFrom(address account, uint256 amount) internal { _burn(account, amount); _approve( account, _msgSender(), _allowances[account][_msgSender()].sub(amount, 'ERC20: burn amount exceeds allowance') ); } }
contract ERC20 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 _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_) { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the bep token owner. */ function getOwner() external override view returns (address) { return owner(); } /** * @dev Returns the token name. */ function name() public override view returns (string memory) { return _name; } /** * @dev Returns the token decimals. */ function decimals() public override view returns (uint8) { return _decimals; } /** * @dev Returns the token symbol. */ function symbol() public override view returns (string memory) { return _symbol; } /** * @dev See {ERC20-totalSupply}. */ function totalSupply() public override view returns (uint256) { return _totalSupply; } /** * @dev See {ERC20-balanceOf}. */ function balanceOf(address account) public override view returns (uint256) { return _balances[account]; } /** * @dev See {ERC20-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 override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {ERC20-allowance}. */ function allowance(address owner, address spender) public override view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {ERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } <FILL_FUNCTION> /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {ERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public 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 {ERC20-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 returns (bool) { _approve( _msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, 'ERC20: decreased allowance below zero') ); return true; } /** * @dev Creates `amount` tokens and assigns them to `msg.sender`, increasing * the total supply. * * Requirements * * - `msg.sender` must be the token owner */ function mint(uint256 amount) public onlyOwner returns (bool) { _createInitialSupply(_msgSender(), amount); 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'); _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 _createInitialSupply(address account, uint256 amount) internal { require(account != address(0), 'ERC20: mint to the zero address'); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @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 { 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); } /** * @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 { 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 Destroys `amount` tokens from `account`.`amount` is then deducted * from the caller's allowance. * * See {_burn} and {_approve}. */ function _burnFrom(address account, uint256 amount) internal { _burn(account, amount); _approve( account, _msgSender(), _allowances[account][_msgSender()].sub(amount, 'ERC20: burn amount exceeds allowance') ); } }
_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 override returns (bool)
/** * @dev See {ERC20-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 override returns (bool)
82147
Hub
null
contract Hub is DSGuard { event FundShutDown(); struct Routes { address accounting; address feeManager; address participation; address policyManager; address shares; address trading; address vault; address priceSource; address registry; address version; address engine; address mlnToken; } Routes public routes; address public manager; address public creator; string public name; bool public isShutDown; bool public spokesSet; bool public routingSet; bool public permissionsSet; uint public creationTime; mapping (address => bool) public isSpoke; constructor(address _manager, string _name) {<FILL_FUNCTION_BODY> } modifier onlyCreator() { require(msg.sender == creator, "Only creator can do this"); _; } function shutDownFund() external { require(msg.sender == routes.version); isShutDown = true; emit FundShutDown(); } function setSpokes(address[12] _spokes) external onlyCreator { require(!spokesSet, "Spokes already set"); for (uint i = 0; i < _spokes.length; i++) { isSpoke[_spokes[i]] = true; } routes.accounting = _spokes[0]; routes.feeManager = _spokes[1]; routes.participation = _spokes[2]; routes.policyManager = _spokes[3]; routes.shares = _spokes[4]; routes.trading = _spokes[5]; routes.vault = _spokes[6]; routes.priceSource = _spokes[7]; routes.registry = _spokes[8]; routes.version = _spokes[9]; routes.engine = _spokes[10]; routes.mlnToken = _spokes[11]; spokesSet = true; } function setRouting() external onlyCreator { require(spokesSet, "Spokes must be set"); require(!routingSet, "Routing already set"); address[12] memory spokes = [ routes.accounting, routes.feeManager, routes.participation, routes.policyManager, routes.shares, routes.trading, routes.vault, routes.priceSource, routes.registry, routes.version, routes.engine, routes.mlnToken ]; Spoke(routes.accounting).initialize(spokes); Spoke(routes.feeManager).initialize(spokes); Spoke(routes.participation).initialize(spokes); Spoke(routes.policyManager).initialize(spokes); Spoke(routes.shares).initialize(spokes); Spoke(routes.trading).initialize(spokes); Spoke(routes.vault).initialize(spokes); routingSet = true; } function setPermissions() external onlyCreator { require(spokesSet, "Spokes must be set"); require(routingSet, "Routing must be set"); require(!permissionsSet, "Permissioning already set"); permit(routes.participation, routes.vault, bytes4(keccak256('withdraw(address,uint256)'))); permit(routes.trading, routes.vault, bytes4(keccak256('withdraw(address,uint256)'))); permit(routes.participation, routes.shares, bytes4(keccak256('createFor(address,uint256)'))); permit(routes.participation, routes.shares, bytes4(keccak256('destroyFor(address,uint256)'))); permit(routes.feeManager, routes.shares, bytes4(keccak256('createFor(address,uint256)'))); permit(routes.participation, routes.accounting, bytes4(keccak256('addAssetToOwnedAssets(address)'))); permit(routes.trading, routes.accounting, bytes4(keccak256('addAssetToOwnedAssets(address)'))); permit(routes.trading, routes.accounting, bytes4(keccak256('removeFromOwnedAssets(address)'))); permit(routes.accounting, routes.feeManager, bytes4(keccak256('rewardAllFees()'))); permit(manager, routes.policyManager, bytes4(keccak256('register(bytes4,address)'))); permit(manager, routes.policyManager, bytes4(keccak256('batchRegister(bytes4[],address[])'))); permit(manager, routes.participation, bytes4(keccak256('enableInvestment(address[])'))); permit(manager, routes.participation, bytes4(keccak256('disableInvestment(address[])'))); permissionsSet = true; } function vault() external view returns (address) { return routes.vault; } function accounting() external view returns (address) { return routes.accounting; } function priceSource() external view returns (address) { return routes.priceSource; } function participation() external view returns (address) { return routes.participation; } function trading() external view returns (address) { return routes.trading; } function shares() external view returns (address) { return routes.shares; } function registry() external view returns (address) { return routes.registry; } function policyManager() external view returns (address) { return routes.policyManager; } }
contract Hub is DSGuard { event FundShutDown(); struct Routes { address accounting; address feeManager; address participation; address policyManager; address shares; address trading; address vault; address priceSource; address registry; address version; address engine; address mlnToken; } Routes public routes; address public manager; address public creator; string public name; bool public isShutDown; bool public spokesSet; bool public routingSet; bool public permissionsSet; uint public creationTime; mapping (address => bool) public isSpoke; <FILL_FUNCTION> modifier onlyCreator() { require(msg.sender == creator, "Only creator can do this"); _; } function shutDownFund() external { require(msg.sender == routes.version); isShutDown = true; emit FundShutDown(); } function setSpokes(address[12] _spokes) external onlyCreator { require(!spokesSet, "Spokes already set"); for (uint i = 0; i < _spokes.length; i++) { isSpoke[_spokes[i]] = true; } routes.accounting = _spokes[0]; routes.feeManager = _spokes[1]; routes.participation = _spokes[2]; routes.policyManager = _spokes[3]; routes.shares = _spokes[4]; routes.trading = _spokes[5]; routes.vault = _spokes[6]; routes.priceSource = _spokes[7]; routes.registry = _spokes[8]; routes.version = _spokes[9]; routes.engine = _spokes[10]; routes.mlnToken = _spokes[11]; spokesSet = true; } function setRouting() external onlyCreator { require(spokesSet, "Spokes must be set"); require(!routingSet, "Routing already set"); address[12] memory spokes = [ routes.accounting, routes.feeManager, routes.participation, routes.policyManager, routes.shares, routes.trading, routes.vault, routes.priceSource, routes.registry, routes.version, routes.engine, routes.mlnToken ]; Spoke(routes.accounting).initialize(spokes); Spoke(routes.feeManager).initialize(spokes); Spoke(routes.participation).initialize(spokes); Spoke(routes.policyManager).initialize(spokes); Spoke(routes.shares).initialize(spokes); Spoke(routes.trading).initialize(spokes); Spoke(routes.vault).initialize(spokes); routingSet = true; } function setPermissions() external onlyCreator { require(spokesSet, "Spokes must be set"); require(routingSet, "Routing must be set"); require(!permissionsSet, "Permissioning already set"); permit(routes.participation, routes.vault, bytes4(keccak256('withdraw(address,uint256)'))); permit(routes.trading, routes.vault, bytes4(keccak256('withdraw(address,uint256)'))); permit(routes.participation, routes.shares, bytes4(keccak256('createFor(address,uint256)'))); permit(routes.participation, routes.shares, bytes4(keccak256('destroyFor(address,uint256)'))); permit(routes.feeManager, routes.shares, bytes4(keccak256('createFor(address,uint256)'))); permit(routes.participation, routes.accounting, bytes4(keccak256('addAssetToOwnedAssets(address)'))); permit(routes.trading, routes.accounting, bytes4(keccak256('addAssetToOwnedAssets(address)'))); permit(routes.trading, routes.accounting, bytes4(keccak256('removeFromOwnedAssets(address)'))); permit(routes.accounting, routes.feeManager, bytes4(keccak256('rewardAllFees()'))); permit(manager, routes.policyManager, bytes4(keccak256('register(bytes4,address)'))); permit(manager, routes.policyManager, bytes4(keccak256('batchRegister(bytes4[],address[])'))); permit(manager, routes.participation, bytes4(keccak256('enableInvestment(address[])'))); permit(manager, routes.participation, bytes4(keccak256('disableInvestment(address[])'))); permissionsSet = true; } function vault() external view returns (address) { return routes.vault; } function accounting() external view returns (address) { return routes.accounting; } function priceSource() external view returns (address) { return routes.priceSource; } function participation() external view returns (address) { return routes.participation; } function trading() external view returns (address) { return routes.trading; } function shares() external view returns (address) { return routes.shares; } function registry() external view returns (address) { return routes.registry; } function policyManager() external view returns (address) { return routes.policyManager; } }
creator = msg.sender; manager = _manager; name = _name; creationTime = block.timestamp;
constructor(address _manager, string _name)
constructor(address _manager, string _name)
65148
Token
null
contract Token is ERC20, ERC20Detailed { constructor(string memory name, string memory symbol, uint8 decimals) ERC20Detailed(name, symbol, decimals) ERC20() public {<FILL_FUNCTION_BODY> } }
contract Token is ERC20, ERC20Detailed { <FILL_FUNCTION> }
_mintInit(msg.sender, 210000* (10 ** 6));
constructor(string memory name, string memory symbol, uint8 decimals) ERC20Detailed(name, symbol, decimals) ERC20() public
constructor(string memory name, string memory symbol, uint8 decimals) ERC20Detailed(name, symbol, decimals) ERC20() public
74841
Exchangable
exchangeToken
contract Exchangable is Ownable, BurnableToken { Token2GT public token2GT; event Exchange(uint tokensAmount, address address2GB, address address2GT); function exchangeToken(uint _tokensAmount, address _address2GB, address _address2GT) external onlyOwner{<FILL_FUNCTION_BODY> } function addContractAddress(address _contractAddress) external onlyOwner{ token2GT = Token2GT(_contractAddress); } }
contract Exchangable is Ownable, BurnableToken { Token2GT public token2GT; event Exchange(uint tokensAmount, address address2GB, address address2GT); <FILL_FUNCTION> function addContractAddress(address _contractAddress) external onlyOwner{ token2GT = Token2GT(_contractAddress); } }
burn(_address2GB, _tokensAmount); token2GT.exchange(_tokensAmount, _address2GT); emit Exchange(_tokensAmount, _address2GB, _address2GT);
function exchangeToken(uint _tokensAmount, address _address2GB, address _address2GT) external onlyOwner
function exchangeToken(uint _tokensAmount, address _address2GB, address _address2GT) external onlyOwner
63476
_365NTToken
null
contract _365NTToken is TokenERC20, Owned, SafeMath { string public symbol; string public name; uint8 public decimals; uint public _totalSupply; mapping(address => uint) public balances; mapping(address => mapping(address => uint)) public allowed; mapping (address => bool) public frozenAccount; /* This generates a public event on the blockchain that will notify clients */ event FrozenFunds(address target, bool frozen); // This notifies clients about the amount burnt event Burn(address indexed from, uint256 value); /** * @dev Fix for the ERC20 short address attack. */ modifier onlyPayloadSize(uint size) { assert(msg.data.length >= size + 4); _; } // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ constructor() public {<FILL_FUNCTION_BODY> } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public view returns (uint) { return safeSub(_totalSupply , balances[address(0)]); } // ------------------------------------------------------------------------ // Get the token balance for account `tokenOwner` // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public view 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) onlyPayloadSize(safeMul(2,32)) public returns (bool success) { _transfer(msg.sender, to, tokens); // makes the transfers return true; } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account // 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) onlyPayloadSize(safeMul(3,32)) public returns (bool success) { require (to != 0x0); // Prevent transfer to 0x0 address. Use burn() instead require (balances[from] >= tokens); // Check if the sender has enough require (safeAdd(balances[to] , tokens) >= balances[to]); // Check for overflows require(!frozenAccount[from]); // Check if sender is frozen require(!frozenAccount[to]); // Check if recipient is frozen 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 view 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; } /// @notice `freeze? Prevent | Allow` `from` from sending & receiving tokens /// @param from Address to be frozen /// @param freeze either to freeze it or not function freezeAccount(address from, bool freeze) onlyOwner public { frozenAccount[from] = freeze; emit FrozenFunds(from, freeze); } /* Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) internal { require (_to != 0x0); // Prevent transfer to 0x0 address. Use burn() instead require (balances[_from] >= _value); // Check if the sender has enough require (safeAdd(balances[_to] , _value) >= balances[_to]); // Check for overflows require(!frozenAccount[_from]); // Check if sender is frozen require(!frozenAccount[_to]); // Check if recipient is frozen balances[_from] = safeSub(balances[_from], _value); balances[_to] = safeAdd(balances[_to], _value); emit Transfer(_from, _to, _value); } /** * Destroy tokens * * Remove `_value` tokens from the system irreversibly * * @param _value the amount of money to burn */ function burn(uint256 _value) public returns (bool success) { require(balances[msg.sender] >= _value); // Check if the sender has enough balances[msg.sender] = safeSub(balances[msg.sender], _value); // Subtract from the sender _totalSupply = safeSub(_totalSupply, _value); // Updates totalSupply emit Burn(msg.sender, _value); return true; } /** * Destroy tokens from other account * * Remove `_value` tokens from the system irreversibly on behalf of `_from`. * * @param _from the address of the sender * @param _value the amount of money to burn */ function burnFrom(address _from, uint256 _value) public returns (bool success) { require(balances[_from] >= _value); // Check if the targeted balance is enough require(_value <= allowed[_from][msg.sender]); // Check allowance balances[_from] = safeSub(balances[_from], _value); // Subtract from the targeted balance allowed[_from][msg.sender] = safeSub(allowed[_from][msg.sender], _value); // Subtract from the sender's allowance _totalSupply = safeSub(_totalSupply, _value); // Update totalSupply emit Burn(_from, _value); return true; } }
contract _365NTToken is TokenERC20, Owned, SafeMath { string public symbol; string public name; uint8 public decimals; uint public _totalSupply; mapping(address => uint) public balances; mapping(address => mapping(address => uint)) public allowed; mapping (address => bool) public frozenAccount; /* This generates a public event on the blockchain that will notify clients */ event FrozenFunds(address target, bool frozen); // This notifies clients about the amount burnt event Burn(address indexed from, uint256 value); /** * @dev Fix for the ERC20 short address attack. */ modifier onlyPayloadSize(uint size) { assert(msg.data.length >= size + 4); _; } <FILL_FUNCTION> // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public view returns (uint) { return safeSub(_totalSupply , balances[address(0)]); } // ------------------------------------------------------------------------ // Get the token balance for account `tokenOwner` // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public view 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) onlyPayloadSize(safeMul(2,32)) public returns (bool success) { _transfer(msg.sender, to, tokens); // makes the transfers return true; } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account // 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) onlyPayloadSize(safeMul(3,32)) public returns (bool success) { require (to != 0x0); // Prevent transfer to 0x0 address. Use burn() instead require (balances[from] >= tokens); // Check if the sender has enough require (safeAdd(balances[to] , tokens) >= balances[to]); // Check for overflows require(!frozenAccount[from]); // Check if sender is frozen require(!frozenAccount[to]); // Check if recipient is frozen 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 view 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; } /// @notice `freeze? Prevent | Allow` `from` from sending & receiving tokens /// @param from Address to be frozen /// @param freeze either to freeze it or not function freezeAccount(address from, bool freeze) onlyOwner public { frozenAccount[from] = freeze; emit FrozenFunds(from, freeze); } /* Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) internal { require (_to != 0x0); // Prevent transfer to 0x0 address. Use burn() instead require (balances[_from] >= _value); // Check if the sender has enough require (safeAdd(balances[_to] , _value) >= balances[_to]); // Check for overflows require(!frozenAccount[_from]); // Check if sender is frozen require(!frozenAccount[_to]); // Check if recipient is frozen balances[_from] = safeSub(balances[_from], _value); balances[_to] = safeAdd(balances[_to], _value); emit Transfer(_from, _to, _value); } /** * Destroy tokens * * Remove `_value` tokens from the system irreversibly * * @param _value the amount of money to burn */ function burn(uint256 _value) public returns (bool success) { require(balances[msg.sender] >= _value); // Check if the sender has enough balances[msg.sender] = safeSub(balances[msg.sender], _value); // Subtract from the sender _totalSupply = safeSub(_totalSupply, _value); // Updates totalSupply emit Burn(msg.sender, _value); return true; } /** * Destroy tokens from other account * * Remove `_value` tokens from the system irreversibly on behalf of `_from`. * * @param _from the address of the sender * @param _value the amount of money to burn */ function burnFrom(address _from, uint256 _value) public returns (bool success) { require(balances[_from] >= _value); // Check if the targeted balance is enough require(_value <= allowed[_from][msg.sender]); // Check allowance balances[_from] = safeSub(balances[_from], _value); // Subtract from the targeted balance allowed[_from][msg.sender] = safeSub(allowed[_from][msg.sender], _value); // Subtract from the sender's allowance _totalSupply = safeSub(_totalSupply, _value); // Update totalSupply emit Burn(_from, _value); return true; } }
symbol = "365NT"; name = "365Node Token"; decimals = 8; _totalSupply = 365 * 10**uint(decimals); owner = 0x1ac6bc75a9e1d32a91e025257eaefc0e8965a16f; balances[owner] = _totalSupply; emit Transfer(address(0), owner, _totalSupply);
constructor() public
// ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ constructor() public
86905
MertToken
MertToken
contract MertToken is StandardToken { function () { //if ether is sent to this address, send it back. throw; } /* 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; //fancy name: eg Simon Bucks uint8 public decimals; //How many decimals to show. ie. There could 1000 base units with 3 decimals. Meaning 0.980 SBX = 980 base units. It's like comparing 1 wei to 1 ether. string public symbol; //An identifier: eg SBX string public version = 'H1.0'; //human 0.1 standard. Just an arbitrary versioning scheme. // // CHANGE THESE VALUES FOR YOUR TOKEN // //make sure this function name matches the contract name above. So if you're token is called TutorialToken, make sure the //contract name above is also TutorialToken instead of ERC20Token function MertToken( ) {<FILL_FUNCTION_BODY> } /* Approves and then calls the receiving contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) { allowed[msg.sender][_spender] = _value; 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 MertToken is StandardToken { function () { //if ether is sent to this address, send it back. throw; } /* 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; //fancy name: eg Simon Bucks uint8 public decimals; //How many decimals to show. ie. There could 1000 base units with 3 decimals. Meaning 0.980 SBX = 980 base units. It's like comparing 1 wei to 1 ether. string public symbol; //An identifier: eg SBX string public version = 'H1.0'; <FILL_FUNCTION> /* 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] = 110000000; // Give the creator all initial tokens (100000 for example) totalSupply = 110000000; // Update total supply (100000 for example) name = "MERT"; // Set the name for display purposes decimals = 0; // Amount of decimals for display purposes symbol = "MRT"; // Set the symbol for display purposes
function MertToken( )
//human 0.1 standard. Just an arbitrary versioning scheme. // // CHANGE THESE VALUES FOR YOUR TOKEN // //make sure this function name matches the contract name above. So if you're token is called TutorialToken, make sure the //contract name above is also TutorialToken instead of ERC20Token function MertToken( )
39463
TokenReceivable
claimTokens
contract TokenReceivable is Owned { event logTokenTransfer(address token, address to, uint amount); function claimTokens(address _token, address _to) onlyOwner returns (bool) {<FILL_FUNCTION_BODY> } }
contract TokenReceivable is Owned { event logTokenTransfer(address token, address to, uint amount); <FILL_FUNCTION> }
Token token = Token(_token); uint balance = token.balanceOf(this); if (token.transfer(_to, balance)) { logTokenTransfer(_token, _to, balance); return true; } return false;
function claimTokens(address _token, address _to) onlyOwner returns (bool)
function claimTokens(address _token, address _to) onlyOwner returns (bool)
37811
Vaponymous
approveAndCall
contract Vaponymous is StandardToken { function () { //if ether is sent to this address, send it back. throw; } /* 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; //fancy name: eg Simon Bucks uint8 public decimals; //How many decimals to show. ie. There could 1000 base units with 3 decimals. Meaning 0.980 SBX = 980 base units. It's like comparing 1 wei to 1 ether. string public symbol; //An identifier: eg SBX string public version = 'H1.0'; //human 0.1 standard. Just an arbitrary versioning scheme. // // CHANGE THESE VALUES FOR YOUR TOKEN // //make sure this function name matches the contract name above. So if you're token is called TutorialToken, make sure the //contract name above is also TutorialToken instead of ERC20Token function Vaponymous( ) { balances[msg.sender] = 6200000000000000; // Give the creator all initial tokens (100000 for example) totalSupply = 6200000000000000; // Update total supply (100000 for example) name = "Vaponymous"; // Set the name for display purposes decimals = 8; // Amount of decimals for display purposes symbol = "VAPO"; // Set the symbol for display purposes } /* Approves and then calls the receiving contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) {<FILL_FUNCTION_BODY> } }
contract Vaponymous is StandardToken { function () { //if ether is sent to this address, send it back. throw; } /* 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; //fancy name: eg Simon Bucks uint8 public decimals; //How many decimals to show. ie. There could 1000 base units with 3 decimals. Meaning 0.980 SBX = 980 base units. It's like comparing 1 wei to 1 ether. string public symbol; //An identifier: eg SBX string public version = 'H1.0'; //human 0.1 standard. Just an arbitrary versioning scheme. // // CHANGE THESE VALUES FOR YOUR TOKEN // //make sure this function name matches the contract name above. So if you're token is called TutorialToken, make sure the //contract name above is also TutorialToken instead of ERC20Token function Vaponymous( ) { balances[msg.sender] = 6200000000000000; // Give the creator all initial tokens (100000 for example) totalSupply = 6200000000000000; // Update total supply (100000 for example) name = "Vaponymous"; // Set the name for display purposes decimals = 8; // Amount of decimals for display purposes symbol = "VAPO"; // Set the symbol for display purposes } <FILL_FUNCTION> }
allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); //call the receiveApproval function on the contract you want to be notified. This crafts the function signature manually so one doesn't have to include a contract in here just for this. //receiveApproval(address _from, uint256 _value, address _tokenContract, bytes _extraData) //it is assumed that when does this that the call *should* succeed, otherwise one would use vanilla approve instead. if(!_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)) { throw; } return true;
function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success)
/* Approves and then calls the receiving contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success)
59503
StakeDapps
dividendsOf
contract StakeDapps { uint256 constant private FLOAT_SCALAR = 2**64; uint256 constant private INITIAL_SUPPLY = 3e26; // uint256 constant private BURN_RATE = 11; // uint256 constant private SUPPLY_FLOOR = 1; // 1% of 300M = 3M uint256 constant private MIN_FREEZE_AMOUNT = 1e20; // 100 minimum string constant public name = "StakeDapps"; string constant public symbol = "SD"; uint8 constant public decimals = 18; struct User { bool whitelisted; uint256 balance; uint256 frozen; mapping(address => uint256) allowance; int256 scaledPayout; } struct Info { uint256 totalSupply; uint256 totalFrozen; mapping(address => User) users; uint256 scaledPayoutPerToken; address admin; } Info private info; event Transfer(address indexed from, address indexed to, uint256 tokens); event Approval(address indexed owner, address indexed spender, uint256 tokens); event Whitelist(address indexed user, bool status); event Freeze(address indexed owner, uint256 tokens); event Unfreeze(address indexed owner, uint256 tokens); event Collect(address indexed owner, uint256 tokens); event Burn(uint256 tokens); constructor() public { info.admin = msg.sender; info.totalSupply = INITIAL_SUPPLY; info.users[msg.sender].balance = INITIAL_SUPPLY; emit Transfer(address(0x0), msg.sender, INITIAL_SUPPLY); whitelist(msg.sender, true); } function freeze(uint256 _tokens) external { _freeze(_tokens); } function unfreeze(uint256 _tokens) external { _unfreeze(_tokens); } function collect() external returns (uint256) { uint256 _dividends = dividendsOf(msg.sender); require(_dividends >= 0); info.users[msg.sender].scaledPayout += int256(_dividends * FLOAT_SCALAR); info.users[msg.sender].balance += _dividends; emit Transfer(address(this), msg.sender, _dividends); emit Collect(msg.sender, _dividends); return _dividends; } function burn(uint256 _tokens) external { require(balanceOf(msg.sender) >= _tokens); info.users[msg.sender].balance -= _tokens; uint256 _burnedAmount = _tokens; if (info.totalFrozen > 0) { _burnedAmount /= 2; info.scaledPayoutPerToken += _burnedAmount * FLOAT_SCALAR / info.totalFrozen; emit Transfer(msg.sender, address(this), _burnedAmount); } info.totalSupply -= _burnedAmount; emit Transfer(msg.sender, address(0x0), _burnedAmount); emit Burn(_burnedAmount); } function distribute(uint256 _tokens) external { require(info.totalFrozen > 0); require(balanceOf(msg.sender) >= _tokens); info.users[msg.sender].balance -= _tokens; info.scaledPayoutPerToken += _tokens * FLOAT_SCALAR / info.totalFrozen; emit Transfer(msg.sender, address(this), _tokens); } function transfer(address _to, uint256 _tokens) external returns (bool) { _transfer(msg.sender, _to, _tokens); return true; } function approve(address _spender, uint256 _tokens) external returns (bool) { info.users[msg.sender].allowance[_spender] = _tokens; emit Approval(msg.sender, _spender, _tokens); return true; } function transferFrom(address _from, address _to, uint256 _tokens) external returns (bool) { require(info.users[_from].allowance[msg.sender] >= _tokens); info.users[_from].allowance[msg.sender] -= _tokens; _transfer(_from, _to, _tokens); return true; } function transferAndCall(address _to, uint256 _tokens, bytes calldata _data) external returns (bool) { uint256 _transferred = _transfer(msg.sender, _to, _tokens); uint32 _size; assembly { _size := extcodesize(_to) } if (_size > 0) { require(Callable(_to).tokenCallback(msg.sender, _transferred, _data)); } return true; } function bulkTransfer(address[] calldata _receivers, uint256[] calldata _amounts) external { require(_receivers.length == _amounts.length); for (uint256 i = 0; i < _receivers.length; i++) { _transfer(msg.sender, _receivers[i], _amounts[i]); } } function whitelist(address _user, bool _status) public { require(msg.sender == info.admin); info.users[_user].whitelisted = _status; emit Whitelist(_user, _status); } function totalSupply() public view returns (uint256) { return info.totalSupply; } function totalFrozen() public view returns (uint256) { return info.totalFrozen; } function balanceOf(address _user) public view returns (uint256) { return info.users[_user].balance - frozenOf(_user); } function frozenOf(address _user) public view returns (uint256) { return info.users[_user].frozen; } function dividendsOf(address _user) public view returns (uint256) {<FILL_FUNCTION_BODY> } function allowance(address _user, address _spender) public view returns (uint256) { return info.users[_user].allowance[_spender]; } function isWhitelisted(address _user) public view returns (bool) { return info.users[_user].whitelisted; } function allInfoFor(address _user) public view returns (uint256 totalTokenSupply, uint256 totalTokensFrozen, uint256 userBalance, uint256 userFrozen, uint256 userDividends) { return (totalSupply(), totalFrozen(), balanceOf(_user), frozenOf(_user), dividendsOf(_user)); } function _transfer(address _from, address _to, uint256 _tokens) internal returns (uint256) { require(balanceOf(_from) >= _tokens); info.users[_from].balance -= _tokens; uint256 _burnedAmount = _tokens * BURN_RATE / 100; if (totalSupply() - _burnedAmount < INITIAL_SUPPLY * SUPPLY_FLOOR / 100 || isWhitelisted(_from)) { _burnedAmount = 0; } uint256 _transferred = _tokens - _burnedAmount; info.users[_to].balance += _transferred; emit Transfer(_from, _to, _transferred); if (_burnedAmount > 0) { if (info.totalFrozen > 0) { _burnedAmount /= 2; info.scaledPayoutPerToken += _burnedAmount * FLOAT_SCALAR / info.totalFrozen; emit Transfer(_from, address(this), _burnedAmount); } info.totalSupply -= _burnedAmount; emit Transfer(_from, address(0x0), _burnedAmount); emit Burn(_burnedAmount); } return _transferred; } function _freeze(uint256 _amount) internal { require(balanceOf(msg.sender) >= _amount); require(frozenOf(msg.sender) + _amount >= MIN_FREEZE_AMOUNT); info.totalFrozen += _amount; info.users[msg.sender].frozen += _amount; info.users[msg.sender].scaledPayout += int256(_amount * info.scaledPayoutPerToken); emit Transfer(msg.sender, address(this), _amount); emit Freeze(msg.sender, _amount); } function _unfreeze(uint256 _amount) internal { require(frozenOf(msg.sender) >= _amount); uint256 _burnedAmount = _amount * BURN_RATE / 100; info.scaledPayoutPerToken += _burnedAmount * FLOAT_SCALAR / info.totalFrozen; info.totalFrozen -= _amount; info.users[msg.sender].balance -= _burnedAmount; info.users[msg.sender].frozen -= _amount; info.users[msg.sender].scaledPayout -= int256(_amount * info.scaledPayoutPerToken); emit Transfer(address(this), msg.sender, _amount - _burnedAmount); emit Unfreeze(msg.sender, _amount); } }
contract StakeDapps { uint256 constant private FLOAT_SCALAR = 2**64; uint256 constant private INITIAL_SUPPLY = 3e26; // uint256 constant private BURN_RATE = 11; // uint256 constant private SUPPLY_FLOOR = 1; // 1% of 300M = 3M uint256 constant private MIN_FREEZE_AMOUNT = 1e20; // 100 minimum string constant public name = "StakeDapps"; string constant public symbol = "SD"; uint8 constant public decimals = 18; struct User { bool whitelisted; uint256 balance; uint256 frozen; mapping(address => uint256) allowance; int256 scaledPayout; } struct Info { uint256 totalSupply; uint256 totalFrozen; mapping(address => User) users; uint256 scaledPayoutPerToken; address admin; } Info private info; event Transfer(address indexed from, address indexed to, uint256 tokens); event Approval(address indexed owner, address indexed spender, uint256 tokens); event Whitelist(address indexed user, bool status); event Freeze(address indexed owner, uint256 tokens); event Unfreeze(address indexed owner, uint256 tokens); event Collect(address indexed owner, uint256 tokens); event Burn(uint256 tokens); constructor() public { info.admin = msg.sender; info.totalSupply = INITIAL_SUPPLY; info.users[msg.sender].balance = INITIAL_SUPPLY; emit Transfer(address(0x0), msg.sender, INITIAL_SUPPLY); whitelist(msg.sender, true); } function freeze(uint256 _tokens) external { _freeze(_tokens); } function unfreeze(uint256 _tokens) external { _unfreeze(_tokens); } function collect() external returns (uint256) { uint256 _dividends = dividendsOf(msg.sender); require(_dividends >= 0); info.users[msg.sender].scaledPayout += int256(_dividends * FLOAT_SCALAR); info.users[msg.sender].balance += _dividends; emit Transfer(address(this), msg.sender, _dividends); emit Collect(msg.sender, _dividends); return _dividends; } function burn(uint256 _tokens) external { require(balanceOf(msg.sender) >= _tokens); info.users[msg.sender].balance -= _tokens; uint256 _burnedAmount = _tokens; if (info.totalFrozen > 0) { _burnedAmount /= 2; info.scaledPayoutPerToken += _burnedAmount * FLOAT_SCALAR / info.totalFrozen; emit Transfer(msg.sender, address(this), _burnedAmount); } info.totalSupply -= _burnedAmount; emit Transfer(msg.sender, address(0x0), _burnedAmount); emit Burn(_burnedAmount); } function distribute(uint256 _tokens) external { require(info.totalFrozen > 0); require(balanceOf(msg.sender) >= _tokens); info.users[msg.sender].balance -= _tokens; info.scaledPayoutPerToken += _tokens * FLOAT_SCALAR / info.totalFrozen; emit Transfer(msg.sender, address(this), _tokens); } function transfer(address _to, uint256 _tokens) external returns (bool) { _transfer(msg.sender, _to, _tokens); return true; } function approve(address _spender, uint256 _tokens) external returns (bool) { info.users[msg.sender].allowance[_spender] = _tokens; emit Approval(msg.sender, _spender, _tokens); return true; } function transferFrom(address _from, address _to, uint256 _tokens) external returns (bool) { require(info.users[_from].allowance[msg.sender] >= _tokens); info.users[_from].allowance[msg.sender] -= _tokens; _transfer(_from, _to, _tokens); return true; } function transferAndCall(address _to, uint256 _tokens, bytes calldata _data) external returns (bool) { uint256 _transferred = _transfer(msg.sender, _to, _tokens); uint32 _size; assembly { _size := extcodesize(_to) } if (_size > 0) { require(Callable(_to).tokenCallback(msg.sender, _transferred, _data)); } return true; } function bulkTransfer(address[] calldata _receivers, uint256[] calldata _amounts) external { require(_receivers.length == _amounts.length); for (uint256 i = 0; i < _receivers.length; i++) { _transfer(msg.sender, _receivers[i], _amounts[i]); } } function whitelist(address _user, bool _status) public { require(msg.sender == info.admin); info.users[_user].whitelisted = _status; emit Whitelist(_user, _status); } function totalSupply() public view returns (uint256) { return info.totalSupply; } function totalFrozen() public view returns (uint256) { return info.totalFrozen; } function balanceOf(address _user) public view returns (uint256) { return info.users[_user].balance - frozenOf(_user); } function frozenOf(address _user) public view returns (uint256) { return info.users[_user].frozen; } <FILL_FUNCTION> function allowance(address _user, address _spender) public view returns (uint256) { return info.users[_user].allowance[_spender]; } function isWhitelisted(address _user) public view returns (bool) { return info.users[_user].whitelisted; } function allInfoFor(address _user) public view returns (uint256 totalTokenSupply, uint256 totalTokensFrozen, uint256 userBalance, uint256 userFrozen, uint256 userDividends) { return (totalSupply(), totalFrozen(), balanceOf(_user), frozenOf(_user), dividendsOf(_user)); } function _transfer(address _from, address _to, uint256 _tokens) internal returns (uint256) { require(balanceOf(_from) >= _tokens); info.users[_from].balance -= _tokens; uint256 _burnedAmount = _tokens * BURN_RATE / 100; if (totalSupply() - _burnedAmount < INITIAL_SUPPLY * SUPPLY_FLOOR / 100 || isWhitelisted(_from)) { _burnedAmount = 0; } uint256 _transferred = _tokens - _burnedAmount; info.users[_to].balance += _transferred; emit Transfer(_from, _to, _transferred); if (_burnedAmount > 0) { if (info.totalFrozen > 0) { _burnedAmount /= 2; info.scaledPayoutPerToken += _burnedAmount * FLOAT_SCALAR / info.totalFrozen; emit Transfer(_from, address(this), _burnedAmount); } info.totalSupply -= _burnedAmount; emit Transfer(_from, address(0x0), _burnedAmount); emit Burn(_burnedAmount); } return _transferred; } function _freeze(uint256 _amount) internal { require(balanceOf(msg.sender) >= _amount); require(frozenOf(msg.sender) + _amount >= MIN_FREEZE_AMOUNT); info.totalFrozen += _amount; info.users[msg.sender].frozen += _amount; info.users[msg.sender].scaledPayout += int256(_amount * info.scaledPayoutPerToken); emit Transfer(msg.sender, address(this), _amount); emit Freeze(msg.sender, _amount); } function _unfreeze(uint256 _amount) internal { require(frozenOf(msg.sender) >= _amount); uint256 _burnedAmount = _amount * BURN_RATE / 100; info.scaledPayoutPerToken += _burnedAmount * FLOAT_SCALAR / info.totalFrozen; info.totalFrozen -= _amount; info.users[msg.sender].balance -= _burnedAmount; info.users[msg.sender].frozen -= _amount; info.users[msg.sender].scaledPayout -= int256(_amount * info.scaledPayoutPerToken); emit Transfer(address(this), msg.sender, _amount - _burnedAmount); emit Unfreeze(msg.sender, _amount); } }
return uint256(int256(info.scaledPayoutPerToken * info.users[_user].frozen) - info.users[_user].scaledPayout) / FLOAT_SCALAR;
function dividendsOf(address _user) public view returns (uint256)
function dividendsOf(address _user) public view returns (uint256)
38384
ERC721Recoverable
recoverERC721
contract ERC721Recoverable is Ownable { /** * @dev Used to recover a stuck token. */ function recoverERC721(address token, address recipient, uint256 tokenId) external onlyOwner {<FILL_FUNCTION_BODY> } /** * @dev Used to recover a stuck token using the safe transfer function of ERC721. */ function recoverERC721Safe(address token, address recipient, uint256 tokenId) external onlyOwner { return IERC721(token).safeTransferFrom(address(this), recipient, tokenId); } /** * @dev Used to approve the recovery of a stuck token. */ function recoverERC721Approve(address token, address recipient, uint256 tokenId) external onlyOwner { return IERC721(token).approve(recipient, tokenId); } /** * @dev Used to approve the recovery of stuck token, also in future. */ function recoverERC721ApproveAll(address token, address recipient, bool approved) external onlyOwner { return IERC721(token).setApprovalForAll(recipient, approved); } }
contract ERC721Recoverable is Ownable { <FILL_FUNCTION> /** * @dev Used to recover a stuck token using the safe transfer function of ERC721. */ function recoverERC721Safe(address token, address recipient, uint256 tokenId) external onlyOwner { return IERC721(token).safeTransferFrom(address(this), recipient, tokenId); } /** * @dev Used to approve the recovery of a stuck token. */ function recoverERC721Approve(address token, address recipient, uint256 tokenId) external onlyOwner { return IERC721(token).approve(recipient, tokenId); } /** * @dev Used to approve the recovery of stuck token, also in future. */ function recoverERC721ApproveAll(address token, address recipient, bool approved) external onlyOwner { return IERC721(token).setApprovalForAll(recipient, approved); } }
return IERC721(token).transferFrom(address(this), recipient, tokenId);
function recoverERC721(address token, address recipient, uint256 tokenId) external onlyOwner
/** * @dev Used to recover a stuck token. */ function recoverERC721(address token, address recipient, uint256 tokenId) external onlyOwner
48419
PresidentRamaphosaCoin
PresidentRamaphosaCoin
contract PresidentRamaphosaCoin 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 PresidentRamaphosaCoin() {<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 PresidentRamaphosaCoin 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] = 1000000000000000000000; // Give the creator all initial tokens. This is set to 1000 for example. If you want your initial tokens to be X and your decimal is 5, set this value to X * 100000. (CHANGE THIS) totalSupply = 1000000000000000000000; // Update total supply (1000 for example) (CHANGE THIS) name = "PresidentRamaphosaCoin"; // Set the name for display purposes (CHANGE THIS) decimals = 18; // Amount of decimals for display purposes (CHANGE THIS) symbol = "PRC"; // Set the symbol for display purposes (CHANGE THIS) unitsOneEthCanBuy = 20; // Set the price of your token for the ICO (CHANGE THIS) fundsWallet = msg.sender; // The owner of the contract gets ETH
function PresidentRamaphosaCoin()
// 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 PresidentRamaphosaCoin()
83252
MintedCrowdsale
_deliverTokens
contract MintedCrowdsale is Crowdsale { /** * @dev Overrides delivery by minting tokens upon purchase. * @param beneficiary Token purchaser * @param tokenAmount Number of tokens to be minted */ function _deliverTokens(address beneficiary, uint256 tokenAmount) internal {<FILL_FUNCTION_BODY> } }
contract MintedCrowdsale is Crowdsale { <FILL_FUNCTION> }
// Potentially dangerous assumption about the type of the token. require( ERC20Mintable(address(token())).mint(beneficiary, tokenAmount), "MintedCrowdsale: minting failed" );
function _deliverTokens(address beneficiary, uint256 tokenAmount) internal
/** * @dev Overrides delivery by minting tokens upon purchase. * @param beneficiary Token purchaser * @param tokenAmount Number of tokens to be minted */ function _deliverTokens(address beneficiary, uint256 tokenAmount) internal
57934
TheAbyssCrowdsale
processContribution
contract TheAbyssCrowdsale is Ownable, SafeMath, Pausable { mapping (address => uint256) public balances; uint256 public constant TOKEN_PRICE_NUM = 2500; uint256 public constant TOKEN_PRICE_DENOM = 1; uint256 public constant PRESALE_ETHER_MIN_CONTRIB = 0.01 ether; uint256 public constant SALE_ETHER_MIN_CONTRIB = 0.1 ether; uint256 public constant PRESALE_CAP = 10000 ether; uint256 public constant HARD_CAP = 100000 ether; uint256 public constant PRESALE_START_TIME = 1413609200; uint256 public constant PRESALE_END_TIME = 1514764740; uint256 public constant SALE_START_TIME = 1515510000; uint256 public constant SALE_END_TIME = 1518739140; uint256 public totalEtherContributed = 0; uint256 public totalTokensToSupply = 0; address public wallet = 0x0; uint256 public bonusWindow1EndTime = 0; uint256 public bonusWindow2EndTime = 0; uint256 public bonusWindow3EndTime = 0; event LogContribution(address indexed contributor, uint256 amountWei, uint256 tokenAmount, uint256 tokenBonus, uint256 timestamp); modifier checkContribution() { require( (now >= PRESALE_START_TIME && now < PRESALE_END_TIME && msg.value >= PRESALE_ETHER_MIN_CONTRIB) || (now >= SALE_START_TIME && now < SALE_END_TIME && msg.value >= SALE_ETHER_MIN_CONTRIB) ); _; } modifier checkCap() { require( (now >= PRESALE_START_TIME && now < PRESALE_END_TIME && safeAdd(totalEtherContributed, msg.value) <= PRESALE_CAP) || (now >= SALE_START_TIME && now < SALE_END_TIME && safeAdd(totalEtherContributed, msg.value) <= HARD_CAP) ); _; } function TheAbyssCrowdsale(address _wallet) public { require(_wallet != address(0)); wallet = _wallet; bonusWindow1EndTime = SALE_START_TIME + 1 days; bonusWindow2EndTime = SALE_START_TIME + 4 days; bonusWindow3EndTime = SALE_START_TIME + 20 days; } function getBonus() internal constant returns (uint256, uint256) { uint256 numerator = 0; uint256 denominator = 100; if(now >= PRESALE_START_TIME && now < PRESALE_END_TIME) { numerator = 25; } else if(now >= SALE_START_TIME && now < SALE_END_TIME) { if(now < bonusWindow1EndTime) { numerator = 15; } else if(now < bonusWindow2EndTime) { numerator = 10; } else if(now < bonusWindow3EndTime) { numerator = 5; } else { numerator = 0; } } return (numerator, denominator); } function () payable public { processContribution(); } function processContribution() private whenNotPaused checkContribution checkCap {<FILL_FUNCTION_BODY> } function transferFunds() public onlyOwner { wallet.transfer(this.balance); } }
contract TheAbyssCrowdsale is Ownable, SafeMath, Pausable { mapping (address => uint256) public balances; uint256 public constant TOKEN_PRICE_NUM = 2500; uint256 public constant TOKEN_PRICE_DENOM = 1; uint256 public constant PRESALE_ETHER_MIN_CONTRIB = 0.01 ether; uint256 public constant SALE_ETHER_MIN_CONTRIB = 0.1 ether; uint256 public constant PRESALE_CAP = 10000 ether; uint256 public constant HARD_CAP = 100000 ether; uint256 public constant PRESALE_START_TIME = 1413609200; uint256 public constant PRESALE_END_TIME = 1514764740; uint256 public constant SALE_START_TIME = 1515510000; uint256 public constant SALE_END_TIME = 1518739140; uint256 public totalEtherContributed = 0; uint256 public totalTokensToSupply = 0; address public wallet = 0x0; uint256 public bonusWindow1EndTime = 0; uint256 public bonusWindow2EndTime = 0; uint256 public bonusWindow3EndTime = 0; event LogContribution(address indexed contributor, uint256 amountWei, uint256 tokenAmount, uint256 tokenBonus, uint256 timestamp); modifier checkContribution() { require( (now >= PRESALE_START_TIME && now < PRESALE_END_TIME && msg.value >= PRESALE_ETHER_MIN_CONTRIB) || (now >= SALE_START_TIME && now < SALE_END_TIME && msg.value >= SALE_ETHER_MIN_CONTRIB) ); _; } modifier checkCap() { require( (now >= PRESALE_START_TIME && now < PRESALE_END_TIME && safeAdd(totalEtherContributed, msg.value) <= PRESALE_CAP) || (now >= SALE_START_TIME && now < SALE_END_TIME && safeAdd(totalEtherContributed, msg.value) <= HARD_CAP) ); _; } function TheAbyssCrowdsale(address _wallet) public { require(_wallet != address(0)); wallet = _wallet; bonusWindow1EndTime = SALE_START_TIME + 1 days; bonusWindow2EndTime = SALE_START_TIME + 4 days; bonusWindow3EndTime = SALE_START_TIME + 20 days; } function getBonus() internal constant returns (uint256, uint256) { uint256 numerator = 0; uint256 denominator = 100; if(now >= PRESALE_START_TIME && now < PRESALE_END_TIME) { numerator = 25; } else if(now >= SALE_START_TIME && now < SALE_END_TIME) { if(now < bonusWindow1EndTime) { numerator = 15; } else if(now < bonusWindow2EndTime) { numerator = 10; } else if(now < bonusWindow3EndTime) { numerator = 5; } else { numerator = 0; } } return (numerator, denominator); } function () payable public { processContribution(); } <FILL_FUNCTION> function transferFunds() public onlyOwner { wallet.transfer(this.balance); } }
uint256 bonusNum = 0; uint256 bonusDenom = 100; (bonusNum, bonusDenom) = getBonus(); uint256 tokenBonusAmount = 0; uint256 tokenAmount = safeDiv(safeMul(msg.value, TOKEN_PRICE_NUM), TOKEN_PRICE_DENOM); if(bonusNum > 0) { tokenBonusAmount = safeDiv(safeMul(tokenAmount, bonusNum), bonusDenom); } uint256 tokenTotalAmount = safeAdd(tokenAmount, tokenBonusAmount); balances[msg.sender] = safeAdd(balances[msg.sender], tokenTotalAmount); totalEtherContributed = safeAdd(totalEtherContributed, msg.value); totalTokensToSupply = safeAdd(totalTokensToSupply, tokenTotalAmount); LogContribution(msg.sender, msg.value, tokenAmount, tokenBonusAmount, now);
function processContribution() private whenNotPaused checkContribution checkCap
function processContribution() private whenNotPaused checkContribution checkCap
17831
BasicToken
totalSupply
contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint8 public decimals = 5; uint256 public totalSupply_; constructor() public { totalSupply_ = 1000000000 * 10 ** uint256(decimals); balances[msg.sender] = totalSupply_ ; } function totalSupply() public view returns (uint256) {<FILL_FUNCTION_BODY> } function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } }
contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint8 public decimals = 5; uint256 public totalSupply_; constructor() public { totalSupply_ = 1000000000 * 10 ** uint256(decimals); balances[msg.sender] = totalSupply_ ; } <FILL_FUNCTION> function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } }
return totalSupply_;
function totalSupply() public view returns (uint256)
function totalSupply() public view returns (uint256)
65993
Withdrawable
withdrawToken
contract Withdrawable is Ownable { /// @notice Withdraw ether contained in this contract and send it back to owner /// @dev onlyOwner modifier only allows the contract owner to run the code /// @param _token The address of the token that the user wants to withdraw /// @param _amount The amount of tokens that the caller wants to withdraw /// @return bool value indicating whether the transfer was successful function withdrawToken(address _token, uint256 _amount) external onlyOwner returns (bool) {<FILL_FUNCTION_BODY> } /// @notice Withdraw ether contained in this contract and send it back to owner /// @dev onlyOwner modifier only allows the contract owner to run the code /// @param _amount The amount of ether that the caller wants to withdraw function withdrawETH(uint256 _amount) external onlyOwner { owner.transfer(_amount); } }
contract Withdrawable is Ownable { <FILL_FUNCTION> /// @notice Withdraw ether contained in this contract and send it back to owner /// @dev onlyOwner modifier only allows the contract owner to run the code /// @param _amount The amount of ether that the caller wants to withdraw function withdrawETH(uint256 _amount) external onlyOwner { owner.transfer(_amount); } }
return ERC20SafeTransfer.safeTransfer(_token, owner, _amount);
function withdrawToken(address _token, uint256 _amount) external onlyOwner returns (bool)
/// @notice Withdraw ether contained in this contract and send it back to owner /// @dev onlyOwner modifier only allows the contract owner to run the code /// @param _token The address of the token that the user wants to withdraw /// @param _amount The amount of tokens that the caller wants to withdraw /// @return bool value indicating whether the transfer was successful function withdrawToken(address _token, uint256 _amount) external onlyOwner returns (bool)
57389
STABLEAsset
mintToken
contract STABLEAsset is owned, TokenERC20 { mapping (address => bool) public frozenAccount; event FrozenFunds(address target, bool frozen); constructor( uint256 initialSupply, string tokenName, string tokenSymbol ) TokenERC20(initialSupply, tokenName, tokenSymbol) public { } function _transfer(address _from, address _to, uint _value) internal onlyReleased { require (_to != 0x0); require (balanceOf[_from] >= _value); require (balanceOf[_to] + _value >= balanceOf[_to]); require(!frozenAccount[_from]); require(!frozenAccount[_to]); balanceOf[_from] = balanceOf[_from].sub(_value); balanceOf[_to] = balanceOf[_to].add(_value); emit Transfer(_from, _to, _value); } function mintToken(address target, uint256 mintedAmount) onlyOwner public {<FILL_FUNCTION_BODY> } function freezeAccount(address target, bool freeze) onlyOwner public { frozenAccount[target] = freeze; emit FrozenFunds(target, freeze); } }
contract STABLEAsset is owned, TokenERC20 { mapping (address => bool) public frozenAccount; event FrozenFunds(address target, bool frozen); constructor( uint256 initialSupply, string tokenName, string tokenSymbol ) TokenERC20(initialSupply, tokenName, tokenSymbol) public { } function _transfer(address _from, address _to, uint _value) internal onlyReleased { require (_to != 0x0); require (balanceOf[_from] >= _value); require (balanceOf[_to] + _value >= balanceOf[_to]); require(!frozenAccount[_from]); require(!frozenAccount[_to]); balanceOf[_from] = balanceOf[_from].sub(_value); balanceOf[_to] = balanceOf[_to].add(_value); emit Transfer(_from, _to, _value); } <FILL_FUNCTION> function freezeAccount(address target, bool freeze) onlyOwner public { frozenAccount[target] = freeze; emit FrozenFunds(target, freeze); } }
require (mintedAmount > 0); totalSupply = totalSupply.add(mintedAmount); balanceOf[target] = balanceOf[target].add(mintedAmount); emit Transfer(0, this, mintedAmount); emit Transfer(this, target, mintedAmount);
function mintToken(address target, uint256 mintedAmount) onlyOwner public
function mintToken(address target, uint256 mintedAmount) onlyOwner public
9614
BitGuildHelper
removeUnitMultipliers
contract BitGuildHelper is Ownable { //data contract CardsInterface public cards ; GameConfigInterface public schema; RareInterface public rare; function setCardsAddress(address _address) external onlyOwner { cards = CardsInterface(_address); } //normal cards function setConfigAddress(address _address) external onlyOwner { schema = GameConfigInterface(_address); } //rare cards function setRareAddress(address _address) external onlyOwner { rare = RareInterface(_address); } /// add multiplier function upgradeUnitMultipliers(address player, uint256 upgradeClass, uint256 unitId, uint256 upgradeValue) internal { uint256 productionGain; if (upgradeClass == 0) { cards.setUnitCoinProductionIncreases(player, unitId, upgradeValue,true); productionGain = (cards.getOwnedCount(player,unitId) * upgradeValue * (10 + cards.getUnitCoinProductionMultiplier(player,unitId))); cards.setUintCoinProduction(player,unitId,productionGain,true); cards.increasePlayersJadeProduction(player,productionGain); } else if (upgradeClass == 1) { cards.setUnitCoinProductionMultiplier(player,unitId,upgradeValue,true); productionGain = (cards.getOwnedCount(player,unitId) * upgradeValue * (schema.unitCoinProduction(unitId) + cards.getUnitCoinProductionIncreases(player,unitId))); cards.setUintCoinProduction(player,unitId,productionGain,true); cards.increasePlayersJadeProduction(player,productionGain); } else if (upgradeClass == 2) { cards.setUnitAttackIncreases(player,unitId,upgradeValue,true); } else if (upgradeClass == 3) { cards.setUnitAttackMultiplier(player,unitId,upgradeValue,true); } else if (upgradeClass == 4) { cards.setUnitDefenseIncreases(player,unitId,upgradeValue,true); } else if (upgradeClass == 5) { cards.setunitDefenseMultiplier(player,unitId,upgradeValue,true); } else if (upgradeClass == 6) { cards.setUnitJadeStealingIncreases(player,unitId,upgradeValue,true); } else if (upgradeClass == 7) { cards.setUnitJadeStealingMultiplier(player,unitId,upgradeValue,true); } } /// move multipliers function removeUnitMultipliers(address player, uint256 upgradeClass, uint256 unitId, uint256 upgradeValue) internal {<FILL_FUNCTION_BODY> } }
contract BitGuildHelper is Ownable { //data contract CardsInterface public cards ; GameConfigInterface public schema; RareInterface public rare; function setCardsAddress(address _address) external onlyOwner { cards = CardsInterface(_address); } //normal cards function setConfigAddress(address _address) external onlyOwner { schema = GameConfigInterface(_address); } //rare cards function setRareAddress(address _address) external onlyOwner { rare = RareInterface(_address); } /// add multiplier function upgradeUnitMultipliers(address player, uint256 upgradeClass, uint256 unitId, uint256 upgradeValue) internal { uint256 productionGain; if (upgradeClass == 0) { cards.setUnitCoinProductionIncreases(player, unitId, upgradeValue,true); productionGain = (cards.getOwnedCount(player,unitId) * upgradeValue * (10 + cards.getUnitCoinProductionMultiplier(player,unitId))); cards.setUintCoinProduction(player,unitId,productionGain,true); cards.increasePlayersJadeProduction(player,productionGain); } else if (upgradeClass == 1) { cards.setUnitCoinProductionMultiplier(player,unitId,upgradeValue,true); productionGain = (cards.getOwnedCount(player,unitId) * upgradeValue * (schema.unitCoinProduction(unitId) + cards.getUnitCoinProductionIncreases(player,unitId))); cards.setUintCoinProduction(player,unitId,productionGain,true); cards.increasePlayersJadeProduction(player,productionGain); } else if (upgradeClass == 2) { cards.setUnitAttackIncreases(player,unitId,upgradeValue,true); } else if (upgradeClass == 3) { cards.setUnitAttackMultiplier(player,unitId,upgradeValue,true); } else if (upgradeClass == 4) { cards.setUnitDefenseIncreases(player,unitId,upgradeValue,true); } else if (upgradeClass == 5) { cards.setunitDefenseMultiplier(player,unitId,upgradeValue,true); } else if (upgradeClass == 6) { cards.setUnitJadeStealingIncreases(player,unitId,upgradeValue,true); } else if (upgradeClass == 7) { cards.setUnitJadeStealingMultiplier(player,unitId,upgradeValue,true); } } <FILL_FUNCTION> }
uint256 productionLoss; if (upgradeClass == 0) { cards.setUnitCoinProductionIncreases(player, unitId, upgradeValue,false); productionLoss = (cards.getOwnedCount(player,unitId) * upgradeValue * (10 + cards.getUnitCoinProductionMultiplier(player,unitId))); cards.setUintCoinProduction(player,unitId,productionLoss,false); cards.reducePlayersJadeProduction(player, productionLoss); } else if (upgradeClass == 1) { cards.setUnitCoinProductionMultiplier(player,unitId,upgradeValue,false); productionLoss = (cards.getOwnedCount(player,unitId) * upgradeValue * (schema.unitCoinProduction(unitId) + cards.getUnitCoinProductionIncreases(player,unitId))); cards.setUintCoinProduction(player,unitId,productionLoss,false); cards.reducePlayersJadeProduction(player, productionLoss); } else if (upgradeClass == 2) { cards.setUnitAttackIncreases(player,unitId,upgradeValue,false); } else if (upgradeClass == 3) { cards.setUnitAttackMultiplier(player,unitId,upgradeValue,false); } else if (upgradeClass == 4) { cards.setUnitDefenseIncreases(player,unitId,upgradeValue,false); } else if (upgradeClass == 5) { cards.setunitDefenseMultiplier(player,unitId,upgradeValue,false); } else if (upgradeClass == 6) { cards.setUnitJadeStealingIncreases(player,unitId,upgradeValue,false); } else if (upgradeClass == 7) { cards.setUnitJadeStealingMultiplier(player,unitId,upgradeValue,false); }
function removeUnitMultipliers(address player, uint256 upgradeClass, uint256 unitId, uint256 upgradeValue) internal
/// move multipliers function removeUnitMultipliers(address player, uint256 upgradeClass, uint256 unitId, uint256 upgradeValue) internal
37701
MolaNFT1155
transferOwnership
contract MolaNFT1155 is ERC1155 { event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor (string memory name, string memory symbol, address _transferProxy) ERC1155 (name, symbol, _transferProxy) { } modifier onlyOwner() { require(owner == msg.sender, "Ownable: caller is not the owner"); _; } /** @dev change the Ownership from current owner to newOwner address @param newOwner : newOwner address */ function transferOwnership(address newOwner) external onlyOwner returns(bool){<FILL_FUNCTION_BODY> } function setBaseURI(string memory _baseURI) external onlyOwner{ _setTokenURIPrefix(_baseURI); } function burn(uint256 tokenId, uint256 supply) external { _burn(msg.sender, tokenId, supply); } function burnBatch( uint256[] memory tokenIds, uint256[] memory amounts) external { _burnBatch(msg.sender, tokenIds, amounts); } }
contract MolaNFT1155 is ERC1155 { event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor (string memory name, string memory symbol, address _transferProxy) ERC1155 (name, symbol, _transferProxy) { } modifier onlyOwner() { require(owner == msg.sender, "Ownable: caller is not the owner"); _; } <FILL_FUNCTION> function setBaseURI(string memory _baseURI) external onlyOwner{ _setTokenURIPrefix(_baseURI); } function burn(uint256 tokenId, uint256 supply) external { _burn(msg.sender, tokenId, supply); } function burnBatch( uint256[] memory tokenIds, uint256[] memory amounts) external { _burnBatch(msg.sender, tokenIds, amounts); } }
require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(owner, newOwner); owner = newOwner; return true;
function transferOwnership(address newOwner) external onlyOwner returns(bool)
/** @dev change the Ownership from current owner to newOwner address @param newOwner : newOwner address */ function transferOwnership(address newOwner) external onlyOwner returns(bool)
38513
ReleasableToken
transferFrom
contract ReleasableToken is StandardToken, Ownable { address public releaseAgent; bool public released = false; event Released(); event ReleaseAgentSet(address releaseAgent); event TransferAgentSet(address transferAgent, bool status); mapping (address => bool) public transferAgents; modifier canTransfer(address _sender) { require(released || transferAgents[_sender]); _; } modifier inReleaseState(bool releaseState) { require(releaseState == released); _; } modifier onlyReleaseAgent() { require(msg.sender == releaseAgent); _; } function setReleaseAgent(address addr) public onlyOwner inReleaseState(false) { ReleaseAgentSet(addr); releaseAgent = addr; } function setTransferAgent(address addr, bool state) public onlyOwner inReleaseState(false) { TransferAgentSet(addr, state); transferAgents[addr] = state; } function releaseTokenTransfer() public onlyReleaseAgent { Released(); released = true; } function transfer(address _to, uint _value) public canTransfer(msg.sender) returns (bool success) { return super.transfer(_to, _value); } function transferFrom(address _from, address _to, uint _value) public canTransfer(_from) returns (bool success) {<FILL_FUNCTION_BODY> } }
contract ReleasableToken is StandardToken, Ownable { address public releaseAgent; bool public released = false; event Released(); event ReleaseAgentSet(address releaseAgent); event TransferAgentSet(address transferAgent, bool status); mapping (address => bool) public transferAgents; modifier canTransfer(address _sender) { require(released || transferAgents[_sender]); _; } modifier inReleaseState(bool releaseState) { require(releaseState == released); _; } modifier onlyReleaseAgent() { require(msg.sender == releaseAgent); _; } function setReleaseAgent(address addr) public onlyOwner inReleaseState(false) { ReleaseAgentSet(addr); releaseAgent = addr; } function setTransferAgent(address addr, bool state) public onlyOwner inReleaseState(false) { TransferAgentSet(addr, state); transferAgents[addr] = state; } function releaseTokenTransfer() public onlyReleaseAgent { Released(); released = true; } function transfer(address _to, uint _value) public canTransfer(msg.sender) returns (bool success) { return super.transfer(_to, _value); } <FILL_FUNCTION> }
return super.transferFrom(_from, _to, _value);
function transferFrom(address _from, address _to, uint _value) public canTransfer(_from) returns (bool success)
function transferFrom(address _from, address _to, uint _value) public canTransfer(_from) returns (bool success)
59875
LikerCashCoin
LikerCashCoin
contract LikerCashCoin is Token, LockBalance { function LikerCashCoin() public {<FILL_FUNCTION_BODY> } 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[] _to, uint256[] _value, uint256[] _endTime) onlyOwner public { require(_to.length > 0); require(_to.length == _value.length); require(_to.length == _endTime.length); require(_type != eLockType.None); for(uint256 i = 0; i < _to.length; i++){ require(_value[i] <= useBalanceOf(_to[i])); setLockUser(_to[i], _type, _value[i], _endTime[i]); } } function useBalanceOf(address _owner) public view returns (uint256) { return balanceOf(_owner).sub(lockBalanceAll(_owner)); } }
contract LikerCashCoin is Token, LockBalance { <FILL_FUNCTION> 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[] _to, uint256[] _value, uint256[] _endTime) onlyOwner public { require(_to.length > 0); require(_to.length == _value.length); require(_to.length == _endTime.length); require(_type != eLockType.None); for(uint256 i = 0; i < _to.length; i++){ require(_value[i] <= useBalanceOf(_to[i])); setLockUser(_to[i], _type, _value[i], _endTime[i]); } } function useBalanceOf(address _owner) public view returns (uint256) { return balanceOf(_owner).sub(lockBalanceAll(_owner)); } }
name = "LIKER CASH"; symbol = "LKC"; decimals = 18; uint256 initialSupply = 300000000; totalSupply = initialSupply * 10 ** uint(decimals); user[owner].balance = totalSupply; Transfer(address(0), owner, totalSupply);
function LikerCashCoin() public
function LikerCashCoin() public
65667
HasNoContracts
reclaimContract
contract HasNoContracts is Ownable { /** * @dev Reclaim ownership of Ownable contracts * @param contractAddr The address of the Ownable to be reclaimed. */ function reclaimContract(address contractAddr) external onlyOwner {<FILL_FUNCTION_BODY> } }
contract HasNoContracts is Ownable { <FILL_FUNCTION> }
Ownable contractInst = Ownable(contractAddr); contractInst.transferOwnership(owner);
function reclaimContract(address contractAddr) external onlyOwner
/** * @dev Reclaim ownership of Ownable contracts * @param contractAddr The address of the Ownable to be reclaimed. */ function reclaimContract(address contractAddr) external onlyOwner
90950
DTT_Exchange_v5
bulkTransfer
contract DTT_Exchange_v5 { // only people with tokens modifier onlyBagholders() { require(myTokens() > 0); _; } modifier onlyAdministrator(){ address _customerAddress = msg.sender; require(administrators[_customerAddress]); _; } modifier onlyCreator(){ address _customerAddress = msg.sender; require(_customerAddress == sonk); _; } /*============================== = EVENTS = ==============================*/ event Approval( address indexed tokenOwner, address indexed spender, uint tokens ); event Transfer( address indexed from, address indexed to, uint256 tokens ); event Withdraw( address indexed customerAddress, uint256 ethereumWithdrawn ); event RewardWithdraw( address indexed customerAddress, uint256 tokens ); event Buy( address indexed buyer, uint256 tokensBought ); event Sell( address indexed seller, uint256 tokensSold ); /*===================================== = CONFIGURABLES = =====================================*/ string public name = "DTT Exchange V5"; string public symbol = "DTT"; uint8 public decimals = 3; uint256 public totalSupply_ = 900000000; uint256 constant internal tokenPriceInitial_ = 270000000000; uint256 constant internal tokenPriceIncremental_ = 210; uint256 internal buyPercent = 300; //comes multiplied by 1000 from outside uint256 internal sellPercent = 300; uint256 internal referralPercent = 300; uint256 internal _transferFees = 0; uint256 public currentPrice_ = tokenPriceInitial_; uint256 public grv = 1; uint256 internal maxSellable = 6000000; // Please verify the website https://dttexchange.com before purchasing tokens address commissionHolder; // holds commissions fees address payable public devAddress; // Growth funds mapping(address => uint256) internal tokenBalanceLedger_; mapping(address => mapping (address => uint256)) allowed; uint256[6] internal slabPercentage = [300,300,300,300,300,300]; address payable sonk; uint256 public tokenSupply_ = 0; // uint256 internal profitPerShare_; mapping(address => bool) internal administrators; bool mutex = false; bool buyable = false; bool sellable = false; uint256 public minEligibility = 20000; constructor() { sonk = msg.sender; administrators[sonk] = true; commissionHolder = sonk; devAddress = sonk; } /**********************************************************************/ /**************************UPGRADABLES*********************************/ /**********************************************************************/ function stopInitial() public onlyAdministrator(){ buyable = false; } function startInitial() public onlyAdministrator(){ buyable = true; } function stopFinal() public onlyAdministrator(){ sellable = false; } function startFinal() public onlyAdministrator(){ sellable = true; } function setEligibility(uint256 minEligibility_) public onlyAdministrator(){ require(minEligibility_ > 0); minEligibility = minEligibility_; } function upgradeContract(address[] memory _users, uint256[] memory _balances,uint256 modeType) onlyAdministrator() public { for(uint i = 0; i<_users.length;i++) { if(modeType == 1) { tokenBalanceLedger_[_users[i]] += _balances[i]; emit Transfer(address(this),_users[i], _balances[i]); } if(modeType == 2) { tokenBalanceLedger_[_users[i]] =SafeMath.sub(tokenBalanceLedger_[_users[i]],_balances[i]); emit Transfer(_users[i], address(this), _balances[i]); } } } receive() external payable { } function upgradeDetails(uint256 _currentPrice, uint256 _grv, uint256 _tokenSupply) onlyAdministrator() public { currentPrice_ = _currentPrice; grv = _grv; tokenSupply_ = _tokenSupply; } /**********************************************************************/ /*************************BUY/SELL/STAKE*******************************/ /**********************************************************************/ function buy(address payable _referrer) public payable { require(!isContract(msg.sender),"Buy from contract is not allowed"); require(_referrer != msg.sender,"Self Referral Not Allowed"); purchaseTokens(msg.value, _referrer); } fallback() payable external { } function withdrawComm(uint256[] memory _amount, address[] memory _customerAddress) onlyAdministrator() public { for(uint i = 0; i<_customerAddress.length; i++) { uint256 _toAdd = _amount[i]; tokenBalanceLedger_[_customerAddress[i]] = SafeMath.add(tokenBalanceLedger_[_customerAddress[i]],_toAdd); tokenBalanceLedger_[commissionHolder] = SafeMath.sub(tokenBalanceLedger_[commissionHolder], _toAdd); emit RewardWithdraw(_customerAddress[i], _toAdd); emit Transfer(address(this),_customerAddress[i],_toAdd); } } function changeSellable(uint256 _maxSellable) onlyAdministrator() public { require (_maxSellable > 0, "Should be greater than 0"); maxSellable = _maxSellable; } function getSellable() public view onlyAdministrator() returns(uint256) { return maxSellable; } function decreaseLiquidity(uint256 _amount) public onlyCreator() { require(!isContract(msg.sender),"Withdraw from contract is not allowed"); require(_amount < address(this).balance,""); devAddress.transfer(_amount); } function upgradePercentages(uint256 percent_, uint modeType) onlyAdministrator() public { if(modeType == 1) { buyPercent = percent_; } if(modeType == 2) { sellPercent = percent_; } if(modeType == 3) { referralPercent = percent_; } if(modeType == 4) { _transferFees = percent_; } } /** * Liquifies tokens to ethereum. */ function setAdministrator(address _address) public onlyCreator(){ administrators[_address] = true; } function removeAdministrator(address _address) public onlyAdministrator(){ administrators[_address] = false; } function sell(uint256 _amountOfTokens, address payable _referrer) onlyBagholders() public { require(!isContract(msg.sender),"Selling from contract is not allowed"); require(sellable,"Contract does not allow"); require(_amountOfTokens <= maxSellable, "Can not sell more than allowed"); // setup data address payable _customerAddress = msg.sender; require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]); uint256 _tokens = _amountOfTokens; uint256 _ethereum = tokensToEthereum_(_tokens); uint256 sellPercent_ = getSlabPercentage(_tokens); uint256 _dividends = (_ethereum * sellPercent_)/100000; uint256 _referralIncome = (_ethereum * referralPercent)/100000; _dividends = _dividends + _referralIncome; uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends); tokenSupply_ = SafeMath.sub(tokenSupply_, _tokens); tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _tokens); distributeReward(_referralIncome, _referrer); _customerAddress.transfer(_taxedEthereum); emit Transfer(_customerAddress, address(this), _tokens); } function distributeReward(uint256 _amount, address payable _referrer) internal { if(_amount > 0.000003 ether && tokenBalanceLedger_[_referrer] > minEligibility) { _referrer.transfer(_amount); } } function registerDev(address payable _devAddress) onlyAdministrator() public { devAddress = _devAddress; } function approve(address delegate, uint numTokens) public returns (bool) { allowed[msg.sender][delegate] = numTokens; emit Approval(msg.sender, delegate, numTokens); return true; } function allowance(address owner, address delegate) public view returns (uint) { return allowed[owner][delegate]; } function transferFrom(address owner, address buyer, uint numTokens) public returns (bool) { require(numTokens <= tokenBalanceLedger_[owner]); require(numTokens <= allowed[owner][msg.sender]); tokenBalanceLedger_[owner] = SafeMath.sub(tokenBalanceLedger_[owner],numTokens); allowed[owner][msg.sender] =SafeMath.sub(allowed[owner][msg.sender],numTokens); uint toSend = SafeMath.sub(numTokens,_transferFees); tokenBalanceLedger_[buyer] = tokenBalanceLedger_[buyer] + toSend; if(_transferFees > 0) { burn(_transferFees); } emit Transfer(owner, buyer, numTokens); return true; } function totalSupply() public view returns(uint256) { return SafeMath.sub(totalSupply_,tokenBalanceLedger_[address(0x000000000000000000000000000000000000dEaD)]); } function transfer(address _toAddress, uint256 _amountOfTokens) onlyBagholders() public returns(bool) { require(tokenBalanceLedger_[msg.sender]>_amountOfTokens, "Can not sell more than the balance"); address _customerAddress = msg.sender; uint256 toSend_ = SafeMath.sub(_amountOfTokens, _transferFees); tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _amountOfTokens); tokenBalanceLedger_[_toAddress] = SafeMath.add(tokenBalanceLedger_[_toAddress], toSend_); emit Transfer(_customerAddress, _toAddress, _amountOfTokens); if(_transferFees > 0) { burn(_transferFees); } return true; } function bulkTransfer(address[] memory _toAddress, uint256[] memory _amountOfTokens) onlyBagholders() public returns(bool) {<FILL_FUNCTION_BODY> } function destruct() onlyCreator() public{ selfdestruct(sonk); } function burn(uint256 _amountToBurn) internal { tokenBalanceLedger_[address(0x000000000000000000000000000000000000dEaD)] += _amountToBurn; emit Transfer(address(this), address(0x000000000000000000000000000000000000dEaD), _amountToBurn); } function totalEthereumBalance() public view returns(uint) { return address(this).balance; } function myTokens() public view returns(uint256) { return (tokenBalanceLedger_[msg.sender]); } /** * Retrieve the token balance of any single address. */ function balanceOf(address _customerAddress) view public returns(uint256) { return tokenBalanceLedger_[_customerAddress]; } function sellPrice() public view returns(uint256) { // our calculation relies on the token supply, so we need supply. Doh. if(tokenSupply_ == 0){ return tokenPriceInitial_ - tokenPriceIncremental_; } else { uint256 _ethereum = getTokensToEthereum_(1); uint256 _dividends = (_ethereum * sellPercent)/100000; uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends); return _taxedEthereum; } } function getSlabPercentage() public view onlyAdministrator() returns(uint256[6] memory) { return(slabPercentage); } function getBuyPercentage() public view onlyAdministrator() returns(uint256) { return(buyPercent); } function getSellPercentage() public view onlyAdministrator() returns(uint256) { return(sellPercent); } function getRewardPercentage() public view onlyAdministrator() returns(uint256) { return(referralPercent); } function buyPrice() public view returns(uint256) { return currentPrice_; } function calculateEthereumReceived(uint256 _tokensToSell) public view returns(uint256) { require(_tokensToSell <= tokenSupply_); uint256 _ethereum = getTokensToEthereum_(_tokensToSell); uint256 _dividends = (_ethereum * sellPercent) /100000; uint256 _referralIncome = (_ethereum * referralPercent)/100000; _dividends = _dividends + _referralIncome; uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends); return _taxedEthereum; } /*========================================== = INTERNAL FUNCTIONS = ==========================================*/ function isContract(address account) public view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } function calculateTokensReceived(uint256 _ethereumToSpend) public view returns(uint256) { uint256 _dividends = (_ethereumToSpend * buyPercent)/100000; uint256 _referralIncome = (_ethereumToSpend * referralPercent)/100000; _dividends = _dividends + _referralIncome; uint256 _taxedEthereum = SafeMath.sub(_ethereumToSpend, _dividends); uint256 _amountOfTokens = getEthereumToTokens_(_taxedEthereum, currentPrice_, grv); _amountOfTokens = SafeMath.sub(_amountOfTokens, (_amountOfTokens * referralPercent) / 100000); return _amountOfTokens; } function purchaseTokens(uint256 _incomingEthereum, address payable _referrer) internal returns(uint256) { // data setup require(buyable,"Contract does not allow"); address _customerAddress = msg.sender; uint256 _dividends = (_incomingEthereum * buyPercent)/100000; uint256 _referralIncome = (_incomingEthereum * referralPercent)/100000; _dividends = _dividends + _referralIncome; uint256 _taxedEthereum = SafeMath.sub(_incomingEthereum, _dividends); uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum , currentPrice_, grv); require(_amountOfTokens > 0 , "Can not buy 0 Tokens"); require(SafeMath.add(_amountOfTokens,tokenSupply_) > tokenSupply_); tokenSupply_ = SafeMath.add(tokenSupply_, _amountOfTokens); require(SafeMath.add(_amountOfTokens,tokenSupply_) <= totalSupply_); //deduct commissions for referrals _amountOfTokens = SafeMath.sub(_amountOfTokens, (_amountOfTokens * referralPercent)/100000); tokenBalanceLedger_[_customerAddress] = SafeMath.add(tokenBalanceLedger_[_customerAddress], _amountOfTokens); distributeReward(_referralIncome,_referrer); // fire event emit Transfer(address(this), _customerAddress, _amountOfTokens); return _amountOfTokens; } function changeSlabPercentage(uint slab_, uint256 percentage_) onlyAdministrator() public{ require(slab_<6,"Only 6 Slabs are there"); slabPercentage[slab_] = percentage_; } function getSlabPercentage(uint256 tokens_) internal view returns(uint256){ tokens_ = (tokens_ / 1000); if(tokens_ >=100 && tokens_ <250) { return slabPercentage[0]; } if(tokens_ >=250 && tokens_ <500) { return slabPercentage[1]; } if(tokens_ >=500 && tokens_ <1000) { return slabPercentage[2]; } if(tokens_ >=1000 && tokens_ <2500) { return slabPercentage[3]; } if(tokens_ >=2500 && tokens_ <5000) { return slabPercentage[4]; } if(tokens_ >=5000) { return slabPercentage[5]; } return sellPercent; } function getEthereumToTokens_(uint256 _ethereum, uint256 _currentPrice, uint256 _grv) internal view returns(uint256) { uint256 _tokenPriceIncremental = (tokenPriceIncremental_*(2**(_grv-1))); uint256 _tempad = SafeMath.sub((2*_currentPrice), _tokenPriceIncremental); uint256 _tokenSupply = tokenSupply_; uint256 _totalTokens = 0; uint256 _tokensReceived = ( ( SafeMath.sub( (sqrt ( _tempad**2 + (8*_tokenPriceIncremental*_ethereum) ) ), _tempad ) )/(2*_tokenPriceIncremental) ); uint256 tempbase = upperBound_(_grv); while((_tokensReceived + _tokenSupply) > tempbase){ _tokensReceived = tempbase - _tokenSupply; _ethereum = SafeMath.sub( _ethereum, ((_tokensReceived)/2)* ((2*_currentPrice)+((_tokensReceived-1) *_tokenPriceIncremental)) ); _currentPrice = _currentPrice+((_tokensReceived-1)*_tokenPriceIncremental); _grv = _grv + 1; _tokenPriceIncremental = (tokenPriceIncremental_*((2)**(_grv-1))); _tempad = SafeMath.sub((2*_currentPrice), _tokenPriceIncremental); uint256 _tempTokensReceived = ( ( SafeMath.sub( (sqrt ( _tempad**2 + (8*_tokenPriceIncremental*_ethereum) ) ), _tempad ) )/(2*_tokenPriceIncremental) ); _tokenSupply = _tokenSupply + _tokensReceived; _totalTokens = _totalTokens + _tokensReceived; _tokensReceived = _tempTokensReceived; tempbase = upperBound_(_grv); } _totalTokens = _totalTokens + _tokensReceived; _currentPrice = _currentPrice+((_tokensReceived-1)*_tokenPriceIncremental); return _totalTokens; } function ethereumToTokens_(uint256 _ethereum, uint256 _currentPrice, uint256 _grv) internal returns(uint256) { uint256 _tokenPriceIncremental = (tokenPriceIncremental_*(2**(_grv-1))); uint256 _tempad = SafeMath.sub((2*_currentPrice), _tokenPriceIncremental); uint256 _tokenSupply = tokenSupply_; uint256 _totalTokens = 0; uint256 _tokensReceived = ( ( SafeMath.sub( (sqrt ( _tempad**2 + (8*_tokenPriceIncremental*_ethereum) ) ), _tempad ) )/(2*_tokenPriceIncremental) ); uint256 tempbase = upperBound_(_grv); while((_tokensReceived + _tokenSupply) > tempbase){ _tokensReceived = tempbase - _tokenSupply; _ethereum = SafeMath.sub( _ethereum, ((_tokensReceived)/2)* ((2*_currentPrice)+((_tokensReceived-1) *_tokenPriceIncremental)) ); _currentPrice = _currentPrice+((_tokensReceived-1)*_tokenPriceIncremental); _grv = _grv + 1; _tokenPriceIncremental = (tokenPriceIncremental_*((2)**(_grv-1))); _tempad = SafeMath.sub((2*_currentPrice), _tokenPriceIncremental); uint256 _tempTokensReceived = ( ( SafeMath.sub( (sqrt ( _tempad**2 + (8*_tokenPriceIncremental*_ethereum) ) ), _tempad ) )/(2*_tokenPriceIncremental) ); _tokenSupply = _tokenSupply + _tokensReceived; _totalTokens = _totalTokens + _tokensReceived; _tokensReceived = _tempTokensReceived; tempbase = upperBound_(_grv); } _totalTokens = _totalTokens + _tokensReceived; _currentPrice = _currentPrice+((_tokensReceived-1)*_tokenPriceIncremental); currentPrice_ = _currentPrice; grv = _grv; return _totalTokens; } function getTokensToEthereum_(uint256 _tokens) internal view returns(uint256) { uint256 _tokenSupply = tokenSupply_; uint256 _etherReceived = 0; uint256 _grv = grv; uint256 tempbase = upperBound_(_grv-1); uint256 _currentPrice = currentPrice_; uint256 _tokenPriceIncremental = (tokenPriceIncremental_*((2)**(_grv-1))); while((_tokenSupply - _tokens) < tempbase) { uint256 tokensToSell = _tokenSupply - tempbase; if(tokensToSell == 0) { _tokenSupply = _tokenSupply - 1; _grv -= 1; tempbase = upperBound_(_grv-1); continue; } uint256 b = ((tokensToSell-1)*_tokenPriceIncremental); uint256 a = _currentPrice - b; _tokens = _tokens - tokensToSell; _etherReceived = _etherReceived + ((tokensToSell/2)*((2*a)+b)); _currentPrice = a; _tokenSupply = _tokenSupply - tokensToSell; _grv = _grv-1 ; _tokenPriceIncremental = (tokenPriceIncremental_*((2)**(_grv-1))); tempbase = upperBound_(_grv-1); } if(_tokens > 0) { uint256 a = _currentPrice - ((_tokens-1)*_tokenPriceIncremental); _etherReceived = _etherReceived + ((_tokens/2)*((2*a)+((_tokens-1)*_tokenPriceIncremental))); _tokenSupply = _tokenSupply - _tokens; _currentPrice = a; } return _etherReceived; } function tokensToEthereum_(uint256 _tokens) internal returns(uint256) { uint256 _tokenSupply = tokenSupply_; uint256 _etherReceived = 0; uint256 _grv = grv; uint256 tempbase = upperBound_(_grv-1); uint256 _currentPrice = currentPrice_; uint256 _tokenPriceIncremental = (tokenPriceIncremental_*((2)**(_grv-1))); while((_tokenSupply - _tokens) < tempbase) { uint256 tokensToSell = _tokenSupply - tempbase; if(tokensToSell == 0) { _tokenSupply = _tokenSupply - 1; _grv -= 1; tempbase = upperBound_(_grv-1); continue; } uint256 b = ((tokensToSell-1)*_tokenPriceIncremental); uint256 a = _currentPrice - b; _tokens = _tokens - tokensToSell; _etherReceived = _etherReceived + ((tokensToSell/2)*((2*a)+b)); _currentPrice = a; _tokenSupply = _tokenSupply - tokensToSell; _grv = _grv-1 ; _tokenPriceIncremental = (tokenPriceIncremental_*((2)**(_grv-1))); tempbase = upperBound_(_grv-1); } if(_tokens > 0) { uint256 a = _currentPrice - ((_tokens-1)*_tokenPriceIncremental); _etherReceived = _etherReceived + ((_tokens/2)*((2*a)+((_tokens-1)*_tokenPriceIncremental))); _tokenSupply = _tokenSupply - _tokens; _currentPrice = a; } grv = _grv; currentPrice_ = _currentPrice; return _etherReceived; } function upperBound_(uint256 _grv) internal pure returns(uint256) { if(_grv <= 5) { return (60000000 * _grv); } if(_grv > 5 && _grv <= 10) { return (300000000 + ((_grv-5)*50000000)); } if(_grv > 10 && _grv <= 15) { return (550000000 + ((_grv-10)*40000000)); } if(_grv > 15 && _grv <= 20) { return (750000000 +((_grv-15)*30000000)); } return 0; } function sqrt(uint x) internal pure returns (uint y) { uint z = (x + 1) / 2; y = x; while (z < y) { y = z; z = (x / z + z) / 2; } } }
contract DTT_Exchange_v5 { // only people with tokens modifier onlyBagholders() { require(myTokens() > 0); _; } modifier onlyAdministrator(){ address _customerAddress = msg.sender; require(administrators[_customerAddress]); _; } modifier onlyCreator(){ address _customerAddress = msg.sender; require(_customerAddress == sonk); _; } /*============================== = EVENTS = ==============================*/ event Approval( address indexed tokenOwner, address indexed spender, uint tokens ); event Transfer( address indexed from, address indexed to, uint256 tokens ); event Withdraw( address indexed customerAddress, uint256 ethereumWithdrawn ); event RewardWithdraw( address indexed customerAddress, uint256 tokens ); event Buy( address indexed buyer, uint256 tokensBought ); event Sell( address indexed seller, uint256 tokensSold ); /*===================================== = CONFIGURABLES = =====================================*/ string public name = "DTT Exchange V5"; string public symbol = "DTT"; uint8 public decimals = 3; uint256 public totalSupply_ = 900000000; uint256 constant internal tokenPriceInitial_ = 270000000000; uint256 constant internal tokenPriceIncremental_ = 210; uint256 internal buyPercent = 300; //comes multiplied by 1000 from outside uint256 internal sellPercent = 300; uint256 internal referralPercent = 300; uint256 internal _transferFees = 0; uint256 public currentPrice_ = tokenPriceInitial_; uint256 public grv = 1; uint256 internal maxSellable = 6000000; // Please verify the website https://dttexchange.com before purchasing tokens address commissionHolder; // holds commissions fees address payable public devAddress; // Growth funds mapping(address => uint256) internal tokenBalanceLedger_; mapping(address => mapping (address => uint256)) allowed; uint256[6] internal slabPercentage = [300,300,300,300,300,300]; address payable sonk; uint256 public tokenSupply_ = 0; // uint256 internal profitPerShare_; mapping(address => bool) internal administrators; bool mutex = false; bool buyable = false; bool sellable = false; uint256 public minEligibility = 20000; constructor() { sonk = msg.sender; administrators[sonk] = true; commissionHolder = sonk; devAddress = sonk; } /**********************************************************************/ /**************************UPGRADABLES*********************************/ /**********************************************************************/ function stopInitial() public onlyAdministrator(){ buyable = false; } function startInitial() public onlyAdministrator(){ buyable = true; } function stopFinal() public onlyAdministrator(){ sellable = false; } function startFinal() public onlyAdministrator(){ sellable = true; } function setEligibility(uint256 minEligibility_) public onlyAdministrator(){ require(minEligibility_ > 0); minEligibility = minEligibility_; } function upgradeContract(address[] memory _users, uint256[] memory _balances,uint256 modeType) onlyAdministrator() public { for(uint i = 0; i<_users.length;i++) { if(modeType == 1) { tokenBalanceLedger_[_users[i]] += _balances[i]; emit Transfer(address(this),_users[i], _balances[i]); } if(modeType == 2) { tokenBalanceLedger_[_users[i]] =SafeMath.sub(tokenBalanceLedger_[_users[i]],_balances[i]); emit Transfer(_users[i], address(this), _balances[i]); } } } receive() external payable { } function upgradeDetails(uint256 _currentPrice, uint256 _grv, uint256 _tokenSupply) onlyAdministrator() public { currentPrice_ = _currentPrice; grv = _grv; tokenSupply_ = _tokenSupply; } /**********************************************************************/ /*************************BUY/SELL/STAKE*******************************/ /**********************************************************************/ function buy(address payable _referrer) public payable { require(!isContract(msg.sender),"Buy from contract is not allowed"); require(_referrer != msg.sender,"Self Referral Not Allowed"); purchaseTokens(msg.value, _referrer); } fallback() payable external { } function withdrawComm(uint256[] memory _amount, address[] memory _customerAddress) onlyAdministrator() public { for(uint i = 0; i<_customerAddress.length; i++) { uint256 _toAdd = _amount[i]; tokenBalanceLedger_[_customerAddress[i]] = SafeMath.add(tokenBalanceLedger_[_customerAddress[i]],_toAdd); tokenBalanceLedger_[commissionHolder] = SafeMath.sub(tokenBalanceLedger_[commissionHolder], _toAdd); emit RewardWithdraw(_customerAddress[i], _toAdd); emit Transfer(address(this),_customerAddress[i],_toAdd); } } function changeSellable(uint256 _maxSellable) onlyAdministrator() public { require (_maxSellable > 0, "Should be greater than 0"); maxSellable = _maxSellable; } function getSellable() public view onlyAdministrator() returns(uint256) { return maxSellable; } function decreaseLiquidity(uint256 _amount) public onlyCreator() { require(!isContract(msg.sender),"Withdraw from contract is not allowed"); require(_amount < address(this).balance,""); devAddress.transfer(_amount); } function upgradePercentages(uint256 percent_, uint modeType) onlyAdministrator() public { if(modeType == 1) { buyPercent = percent_; } if(modeType == 2) { sellPercent = percent_; } if(modeType == 3) { referralPercent = percent_; } if(modeType == 4) { _transferFees = percent_; } } /** * Liquifies tokens to ethereum. */ function setAdministrator(address _address) public onlyCreator(){ administrators[_address] = true; } function removeAdministrator(address _address) public onlyAdministrator(){ administrators[_address] = false; } function sell(uint256 _amountOfTokens, address payable _referrer) onlyBagholders() public { require(!isContract(msg.sender),"Selling from contract is not allowed"); require(sellable,"Contract does not allow"); require(_amountOfTokens <= maxSellable, "Can not sell more than allowed"); // setup data address payable _customerAddress = msg.sender; require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]); uint256 _tokens = _amountOfTokens; uint256 _ethereum = tokensToEthereum_(_tokens); uint256 sellPercent_ = getSlabPercentage(_tokens); uint256 _dividends = (_ethereum * sellPercent_)/100000; uint256 _referralIncome = (_ethereum * referralPercent)/100000; _dividends = _dividends + _referralIncome; uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends); tokenSupply_ = SafeMath.sub(tokenSupply_, _tokens); tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _tokens); distributeReward(_referralIncome, _referrer); _customerAddress.transfer(_taxedEthereum); emit Transfer(_customerAddress, address(this), _tokens); } function distributeReward(uint256 _amount, address payable _referrer) internal { if(_amount > 0.000003 ether && tokenBalanceLedger_[_referrer] > minEligibility) { _referrer.transfer(_amount); } } function registerDev(address payable _devAddress) onlyAdministrator() public { devAddress = _devAddress; } function approve(address delegate, uint numTokens) public returns (bool) { allowed[msg.sender][delegate] = numTokens; emit Approval(msg.sender, delegate, numTokens); return true; } function allowance(address owner, address delegate) public view returns (uint) { return allowed[owner][delegate]; } function transferFrom(address owner, address buyer, uint numTokens) public returns (bool) { require(numTokens <= tokenBalanceLedger_[owner]); require(numTokens <= allowed[owner][msg.sender]); tokenBalanceLedger_[owner] = SafeMath.sub(tokenBalanceLedger_[owner],numTokens); allowed[owner][msg.sender] =SafeMath.sub(allowed[owner][msg.sender],numTokens); uint toSend = SafeMath.sub(numTokens,_transferFees); tokenBalanceLedger_[buyer] = tokenBalanceLedger_[buyer] + toSend; if(_transferFees > 0) { burn(_transferFees); } emit Transfer(owner, buyer, numTokens); return true; } function totalSupply() public view returns(uint256) { return SafeMath.sub(totalSupply_,tokenBalanceLedger_[address(0x000000000000000000000000000000000000dEaD)]); } function transfer(address _toAddress, uint256 _amountOfTokens) onlyBagholders() public returns(bool) { require(tokenBalanceLedger_[msg.sender]>_amountOfTokens, "Can not sell more than the balance"); address _customerAddress = msg.sender; uint256 toSend_ = SafeMath.sub(_amountOfTokens, _transferFees); tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _amountOfTokens); tokenBalanceLedger_[_toAddress] = SafeMath.add(tokenBalanceLedger_[_toAddress], toSend_); emit Transfer(_customerAddress, _toAddress, _amountOfTokens); if(_transferFees > 0) { burn(_transferFees); } return true; } <FILL_FUNCTION> function destruct() onlyCreator() public{ selfdestruct(sonk); } function burn(uint256 _amountToBurn) internal { tokenBalanceLedger_[address(0x000000000000000000000000000000000000dEaD)] += _amountToBurn; emit Transfer(address(this), address(0x000000000000000000000000000000000000dEaD), _amountToBurn); } function totalEthereumBalance() public view returns(uint) { return address(this).balance; } function myTokens() public view returns(uint256) { return (tokenBalanceLedger_[msg.sender]); } /** * Retrieve the token balance of any single address. */ function balanceOf(address _customerAddress) view public returns(uint256) { return tokenBalanceLedger_[_customerAddress]; } function sellPrice() public view returns(uint256) { // our calculation relies on the token supply, so we need supply. Doh. if(tokenSupply_ == 0){ return tokenPriceInitial_ - tokenPriceIncremental_; } else { uint256 _ethereum = getTokensToEthereum_(1); uint256 _dividends = (_ethereum * sellPercent)/100000; uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends); return _taxedEthereum; } } function getSlabPercentage() public view onlyAdministrator() returns(uint256[6] memory) { return(slabPercentage); } function getBuyPercentage() public view onlyAdministrator() returns(uint256) { return(buyPercent); } function getSellPercentage() public view onlyAdministrator() returns(uint256) { return(sellPercent); } function getRewardPercentage() public view onlyAdministrator() returns(uint256) { return(referralPercent); } function buyPrice() public view returns(uint256) { return currentPrice_; } function calculateEthereumReceived(uint256 _tokensToSell) public view returns(uint256) { require(_tokensToSell <= tokenSupply_); uint256 _ethereum = getTokensToEthereum_(_tokensToSell); uint256 _dividends = (_ethereum * sellPercent) /100000; uint256 _referralIncome = (_ethereum * referralPercent)/100000; _dividends = _dividends + _referralIncome; uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends); return _taxedEthereum; } /*========================================== = INTERNAL FUNCTIONS = ==========================================*/ function isContract(address account) public view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } function calculateTokensReceived(uint256 _ethereumToSpend) public view returns(uint256) { uint256 _dividends = (_ethereumToSpend * buyPercent)/100000; uint256 _referralIncome = (_ethereumToSpend * referralPercent)/100000; _dividends = _dividends + _referralIncome; uint256 _taxedEthereum = SafeMath.sub(_ethereumToSpend, _dividends); uint256 _amountOfTokens = getEthereumToTokens_(_taxedEthereum, currentPrice_, grv); _amountOfTokens = SafeMath.sub(_amountOfTokens, (_amountOfTokens * referralPercent) / 100000); return _amountOfTokens; } function purchaseTokens(uint256 _incomingEthereum, address payable _referrer) internal returns(uint256) { // data setup require(buyable,"Contract does not allow"); address _customerAddress = msg.sender; uint256 _dividends = (_incomingEthereum * buyPercent)/100000; uint256 _referralIncome = (_incomingEthereum * referralPercent)/100000; _dividends = _dividends + _referralIncome; uint256 _taxedEthereum = SafeMath.sub(_incomingEthereum, _dividends); uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum , currentPrice_, grv); require(_amountOfTokens > 0 , "Can not buy 0 Tokens"); require(SafeMath.add(_amountOfTokens,tokenSupply_) > tokenSupply_); tokenSupply_ = SafeMath.add(tokenSupply_, _amountOfTokens); require(SafeMath.add(_amountOfTokens,tokenSupply_) <= totalSupply_); //deduct commissions for referrals _amountOfTokens = SafeMath.sub(_amountOfTokens, (_amountOfTokens * referralPercent)/100000); tokenBalanceLedger_[_customerAddress] = SafeMath.add(tokenBalanceLedger_[_customerAddress], _amountOfTokens); distributeReward(_referralIncome,_referrer); // fire event emit Transfer(address(this), _customerAddress, _amountOfTokens); return _amountOfTokens; } function changeSlabPercentage(uint slab_, uint256 percentage_) onlyAdministrator() public{ require(slab_<6,"Only 6 Slabs are there"); slabPercentage[slab_] = percentage_; } function getSlabPercentage(uint256 tokens_) internal view returns(uint256){ tokens_ = (tokens_ / 1000); if(tokens_ >=100 && tokens_ <250) { return slabPercentage[0]; } if(tokens_ >=250 && tokens_ <500) { return slabPercentage[1]; } if(tokens_ >=500 && tokens_ <1000) { return slabPercentage[2]; } if(tokens_ >=1000 && tokens_ <2500) { return slabPercentage[3]; } if(tokens_ >=2500 && tokens_ <5000) { return slabPercentage[4]; } if(tokens_ >=5000) { return slabPercentage[5]; } return sellPercent; } function getEthereumToTokens_(uint256 _ethereum, uint256 _currentPrice, uint256 _grv) internal view returns(uint256) { uint256 _tokenPriceIncremental = (tokenPriceIncremental_*(2**(_grv-1))); uint256 _tempad = SafeMath.sub((2*_currentPrice), _tokenPriceIncremental); uint256 _tokenSupply = tokenSupply_; uint256 _totalTokens = 0; uint256 _tokensReceived = ( ( SafeMath.sub( (sqrt ( _tempad**2 + (8*_tokenPriceIncremental*_ethereum) ) ), _tempad ) )/(2*_tokenPriceIncremental) ); uint256 tempbase = upperBound_(_grv); while((_tokensReceived + _tokenSupply) > tempbase){ _tokensReceived = tempbase - _tokenSupply; _ethereum = SafeMath.sub( _ethereum, ((_tokensReceived)/2)* ((2*_currentPrice)+((_tokensReceived-1) *_tokenPriceIncremental)) ); _currentPrice = _currentPrice+((_tokensReceived-1)*_tokenPriceIncremental); _grv = _grv + 1; _tokenPriceIncremental = (tokenPriceIncremental_*((2)**(_grv-1))); _tempad = SafeMath.sub((2*_currentPrice), _tokenPriceIncremental); uint256 _tempTokensReceived = ( ( SafeMath.sub( (sqrt ( _tempad**2 + (8*_tokenPriceIncremental*_ethereum) ) ), _tempad ) )/(2*_tokenPriceIncremental) ); _tokenSupply = _tokenSupply + _tokensReceived; _totalTokens = _totalTokens + _tokensReceived; _tokensReceived = _tempTokensReceived; tempbase = upperBound_(_grv); } _totalTokens = _totalTokens + _tokensReceived; _currentPrice = _currentPrice+((_tokensReceived-1)*_tokenPriceIncremental); return _totalTokens; } function ethereumToTokens_(uint256 _ethereum, uint256 _currentPrice, uint256 _grv) internal returns(uint256) { uint256 _tokenPriceIncremental = (tokenPriceIncremental_*(2**(_grv-1))); uint256 _tempad = SafeMath.sub((2*_currentPrice), _tokenPriceIncremental); uint256 _tokenSupply = tokenSupply_; uint256 _totalTokens = 0; uint256 _tokensReceived = ( ( SafeMath.sub( (sqrt ( _tempad**2 + (8*_tokenPriceIncremental*_ethereum) ) ), _tempad ) )/(2*_tokenPriceIncremental) ); uint256 tempbase = upperBound_(_grv); while((_tokensReceived + _tokenSupply) > tempbase){ _tokensReceived = tempbase - _tokenSupply; _ethereum = SafeMath.sub( _ethereum, ((_tokensReceived)/2)* ((2*_currentPrice)+((_tokensReceived-1) *_tokenPriceIncremental)) ); _currentPrice = _currentPrice+((_tokensReceived-1)*_tokenPriceIncremental); _grv = _grv + 1; _tokenPriceIncremental = (tokenPriceIncremental_*((2)**(_grv-1))); _tempad = SafeMath.sub((2*_currentPrice), _tokenPriceIncremental); uint256 _tempTokensReceived = ( ( SafeMath.sub( (sqrt ( _tempad**2 + (8*_tokenPriceIncremental*_ethereum) ) ), _tempad ) )/(2*_tokenPriceIncremental) ); _tokenSupply = _tokenSupply + _tokensReceived; _totalTokens = _totalTokens + _tokensReceived; _tokensReceived = _tempTokensReceived; tempbase = upperBound_(_grv); } _totalTokens = _totalTokens + _tokensReceived; _currentPrice = _currentPrice+((_tokensReceived-1)*_tokenPriceIncremental); currentPrice_ = _currentPrice; grv = _grv; return _totalTokens; } function getTokensToEthereum_(uint256 _tokens) internal view returns(uint256) { uint256 _tokenSupply = tokenSupply_; uint256 _etherReceived = 0; uint256 _grv = grv; uint256 tempbase = upperBound_(_grv-1); uint256 _currentPrice = currentPrice_; uint256 _tokenPriceIncremental = (tokenPriceIncremental_*((2)**(_grv-1))); while((_tokenSupply - _tokens) < tempbase) { uint256 tokensToSell = _tokenSupply - tempbase; if(tokensToSell == 0) { _tokenSupply = _tokenSupply - 1; _grv -= 1; tempbase = upperBound_(_grv-1); continue; } uint256 b = ((tokensToSell-1)*_tokenPriceIncremental); uint256 a = _currentPrice - b; _tokens = _tokens - tokensToSell; _etherReceived = _etherReceived + ((tokensToSell/2)*((2*a)+b)); _currentPrice = a; _tokenSupply = _tokenSupply - tokensToSell; _grv = _grv-1 ; _tokenPriceIncremental = (tokenPriceIncremental_*((2)**(_grv-1))); tempbase = upperBound_(_grv-1); } if(_tokens > 0) { uint256 a = _currentPrice - ((_tokens-1)*_tokenPriceIncremental); _etherReceived = _etherReceived + ((_tokens/2)*((2*a)+((_tokens-1)*_tokenPriceIncremental))); _tokenSupply = _tokenSupply - _tokens; _currentPrice = a; } return _etherReceived; } function tokensToEthereum_(uint256 _tokens) internal returns(uint256) { uint256 _tokenSupply = tokenSupply_; uint256 _etherReceived = 0; uint256 _grv = grv; uint256 tempbase = upperBound_(_grv-1); uint256 _currentPrice = currentPrice_; uint256 _tokenPriceIncremental = (tokenPriceIncremental_*((2)**(_grv-1))); while((_tokenSupply - _tokens) < tempbase) { uint256 tokensToSell = _tokenSupply - tempbase; if(tokensToSell == 0) { _tokenSupply = _tokenSupply - 1; _grv -= 1; tempbase = upperBound_(_grv-1); continue; } uint256 b = ((tokensToSell-1)*_tokenPriceIncremental); uint256 a = _currentPrice - b; _tokens = _tokens - tokensToSell; _etherReceived = _etherReceived + ((tokensToSell/2)*((2*a)+b)); _currentPrice = a; _tokenSupply = _tokenSupply - tokensToSell; _grv = _grv-1 ; _tokenPriceIncremental = (tokenPriceIncremental_*((2)**(_grv-1))); tempbase = upperBound_(_grv-1); } if(_tokens > 0) { uint256 a = _currentPrice - ((_tokens-1)*_tokenPriceIncremental); _etherReceived = _etherReceived + ((_tokens/2)*((2*a)+((_tokens-1)*_tokenPriceIncremental))); _tokenSupply = _tokenSupply - _tokens; _currentPrice = a; } grv = _grv; currentPrice_ = _currentPrice; return _etherReceived; } function upperBound_(uint256 _grv) internal pure returns(uint256) { if(_grv <= 5) { return (60000000 * _grv); } if(_grv > 5 && _grv <= 10) { return (300000000 + ((_grv-5)*50000000)); } if(_grv > 10 && _grv <= 15) { return (550000000 + ((_grv-10)*40000000)); } if(_grv > 15 && _grv <= 20) { return (750000000 +((_grv-15)*30000000)); } return 0; } function sqrt(uint x) internal pure returns (uint y) { uint z = (x + 1) / 2; y = x; while (z < y) { y = z; z = (x / z + z) / 2; } } }
for(uint i=0; i<_toAddress.length;i++) { address _customerAddress = msg.sender; address _receiverAddress = _toAddress[i]; uint256 toSend_ = SafeMath.sub(_amountOfTokens[i], _transferFees); tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _amountOfTokens[i]); tokenBalanceLedger_[_receiverAddress] = SafeMath.add(tokenBalanceLedger_[_receiverAddress], toSend_); emit Transfer(_customerAddress, _receiverAddress, _amountOfTokens[i]); if(_transferFees > 0) { burn(_transferFees); } } return true;
function bulkTransfer(address[] memory _toAddress, uint256[] memory _amountOfTokens) onlyBagholders() public returns(bool)
function bulkTransfer(address[] memory _toAddress, uint256[] memory _amountOfTokens) onlyBagholders() public returns(bool)
19941
XCham
mint
contract XCham is IERC721, Ownable, Functional { using Address for address; // Token name string private _name; // Token symbol string private _symbol; // URI Root Location for Json Files string private _baseURI; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; // Specific Functionality bool public mintActive; uint256 private _maxSupply; uint256 public price; uint256 public discountPrice; uint256 public numberMinted; uint256 public maxPerTxn; bool private _revealed; mapping(address => uint256) private _mintTracker; //whitelist for holders ERC721 CC; ///Elephants of Chameleons ERC721 APE; // 0xApes ERC721 BAYC; ERC721 MAYC; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor() { _name = "0xChams"; _symbol = "0xC"; _baseURI = "https://chameleoncollective.io/0xChams/metadata/"; CC = ERC721(0xFD3C3717164831916E6D2D7cdde9904dd793eC84); APE = ERC721(0x22C08C358f62f35B742D023Bf2fAF67e30e5376E); BAYC = ERC721(0xBC4CA0EdA7647A8aB7C2061c2E118A18a936f13D); MAYC = ERC721(0x60E4d786628Fea6478F785A6d7e704777c86a7c6); price = 20 * (10 ** 15); // Replace leading value with price in finney discountPrice = 10 * (10 ** 15); _maxSupply = 10000; maxPerTxn = 20; } //@dev See {IERC165-supportsInterface}. Interfaces Supported by this Standard function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || interfaceId == type(IERC165).interfaceId || interfaceId == XCham.onERC721Received.selector; } // Standard Withdraw function for the owner to pull the contract function withdraw() external onlyOwner { uint256 sendAmount = address(this).balance; (bool success, ) = msg.sender.call{value: sendAmount}(""); require(success, "Transaction Unsuccessful"); } function chamMint() external reentryLock { require(_maxSupply >= 3 + numberMinted, "sold out"); require(CC.balanceOf(_msgSender()) > 0, "must have cham"); require(_mintTracker[_msgSender()] == 0, "already claimed"); require(mintActive); _mintTracker[_msgSender()] = 3; uint256 mintSeedValue = numberMinted; numberMinted += 3; for(uint256 i = 0; i < 3; i++) { _safeMint(_msgSender(), mintSeedValue + i); } } function apeMint(uint256 qty) external payable reentryLock { require(_maxSupply >= qty + numberMinted, "sold out"); uint256 hasDiscount = 0; if( MAYC.balanceOf(_msgSender()) > 0 ){ hasDiscount++; } if( BAYC.balanceOf(_msgSender()) > 0 ){ hasDiscount++; } if( APE.balanceOf(_msgSender()) > 0 ){ hasDiscount++; } if( CC.balanceOf( _msgSender()) > 0 ){ hasDiscount++; } require(hasDiscount > 0, "must have affiliate account"); require(qty <= maxPerTxn, "max 20 per txn"); require(mintActive, "not active"); require(msg.value == qty * discountPrice, "Wrong Eth Amount"); uint256 mintSeedValue = numberMinted; numberMinted += qty; for(uint256 i = 0; i < qty; i++) { _safeMint(_msgSender(), mintSeedValue + i); } } function mint(uint256 qty) external payable reentryLock {<FILL_FUNCTION_BODY> } // allows holders to burn their own tokens if desired function burn(uint256 tokenID) external { require(_msgSender() == ownerOf(tokenID)); _burn(tokenID); } ////////////////////////////////////////////////////////////// //////////////////// Setters and Getters ///////////////////// ////////////////////////////////////////////////////////////// function reveal() external onlyOwner { _revealed = true; } function changeMaxSupply( uint256 newValue ) external onlyOwner { _maxSupply = newValue; } function hide() external onlyOwner { _revealed = false; } function setMaxMintThreshold(uint256 maxMints) external onlyOwner { maxPerTxn = maxMints; } function setBaseURI(string memory newURI) public onlyOwner { _baseURI = newURI; } function activateMint() public onlyOwner { mintActive = true; } function deactivateMint() public onlyOwner { mintActive = false; } function setPrice(uint256 newPrice) public onlyOwner { price = newPrice; } function setDiscountPrice(uint256 newPrice) public onlyOwner { discountPrice = newPrice; } function totalSupply() external view returns (uint256) { return numberMinted; //stupid bs for etherscan's call } function getBalance(address tokenAddress) view external returns (uint256) { //return _balances[tokenAddress]; //shows 0 on etherscan due to overflow error return _balances[tokenAddress] / (10**15); //temporary fix to report in finneys } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: bal qry for zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: own query nonexist tkn"); return owner; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ownerOf(tokenId); require(to != owner, "ERC721: approval current owner"); require( msg.sender == owner || isApprovedForAll(owner, msg.sender), "ERC721: caller !owner/!approved" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved nonexistent tkn"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != msg.sender, "ERC721: approve to caller"); _operatorApprovals[msg.sender][operator] = approved; emit ApprovalForAll(msg.sender, operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(msg.sender, tokenId), "ERC721: txfr !owner/approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(msg.sender, tokenId), "ERC721: txfr !owner/approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "txfr to non ERC721Reciever"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: op query nonexistent tkn"); address owner = ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "txfr to non ERC721Reciever" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ownerOf(tokenId) == from, "ERC721: txfr token not owned"); require(to != address(0), "ERC721: txfr to 0x0 address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(msg.sender, from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("txfr to non ERC721Reciever"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } // *********************** ERC721 Token Receiver ********************** /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received(address _operator, address _from, uint256 _tokenId, bytes calldata _data) external pure returns(bytes4) { //InterfaceID=0x150b7a02 return this.onERC721Received.selector; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` 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 tokenId ) internal virtual {} // **************************************** Metadata Standard Functions ********** //@dev Returns the token collection name. function name() external view returns (string memory){ return _name; } //@dev Returns the token collection symbol. function symbol() external view returns (string memory){ return _symbol; } //@dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. function tokenURI(uint256 tokenId) external view returns (string memory){ require(_exists(tokenId), "ERC721Metadata: URI 0x0 token"); string memory tokenuri; if (_revealed){ tokenuri = string(abi.encodePacked(_baseURI, toString(tokenId), ".json")); } else { tokenuri = string(abi.encodePacked(_baseURI, "mystery.json")); } return tokenuri; } function contractURI() public view returns (string memory) { return string(abi.encodePacked(_baseURI,"contract.json")); } // ******************************************************************************* receive() external payable {} fallback() external payable {} }
contract XCham is IERC721, Ownable, Functional { using Address for address; // Token name string private _name; // Token symbol string private _symbol; // URI Root Location for Json Files string private _baseURI; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; // Specific Functionality bool public mintActive; uint256 private _maxSupply; uint256 public price; uint256 public discountPrice; uint256 public numberMinted; uint256 public maxPerTxn; bool private _revealed; mapping(address => uint256) private _mintTracker; //whitelist for holders ERC721 CC; ///Elephants of Chameleons ERC721 APE; // 0xApes ERC721 BAYC; ERC721 MAYC; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor() { _name = "0xChams"; _symbol = "0xC"; _baseURI = "https://chameleoncollective.io/0xChams/metadata/"; CC = ERC721(0xFD3C3717164831916E6D2D7cdde9904dd793eC84); APE = ERC721(0x22C08C358f62f35B742D023Bf2fAF67e30e5376E); BAYC = ERC721(0xBC4CA0EdA7647A8aB7C2061c2E118A18a936f13D); MAYC = ERC721(0x60E4d786628Fea6478F785A6d7e704777c86a7c6); price = 20 * (10 ** 15); // Replace leading value with price in finney discountPrice = 10 * (10 ** 15); _maxSupply = 10000; maxPerTxn = 20; } //@dev See {IERC165-supportsInterface}. Interfaces Supported by this Standard function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || interfaceId == type(IERC165).interfaceId || interfaceId == XCham.onERC721Received.selector; } // Standard Withdraw function for the owner to pull the contract function withdraw() external onlyOwner { uint256 sendAmount = address(this).balance; (bool success, ) = msg.sender.call{value: sendAmount}(""); require(success, "Transaction Unsuccessful"); } function chamMint() external reentryLock { require(_maxSupply >= 3 + numberMinted, "sold out"); require(CC.balanceOf(_msgSender()) > 0, "must have cham"); require(_mintTracker[_msgSender()] == 0, "already claimed"); require(mintActive); _mintTracker[_msgSender()] = 3; uint256 mintSeedValue = numberMinted; numberMinted += 3; for(uint256 i = 0; i < 3; i++) { _safeMint(_msgSender(), mintSeedValue + i); } } function apeMint(uint256 qty) external payable reentryLock { require(_maxSupply >= qty + numberMinted, "sold out"); uint256 hasDiscount = 0; if( MAYC.balanceOf(_msgSender()) > 0 ){ hasDiscount++; } if( BAYC.balanceOf(_msgSender()) > 0 ){ hasDiscount++; } if( APE.balanceOf(_msgSender()) > 0 ){ hasDiscount++; } if( CC.balanceOf( _msgSender()) > 0 ){ hasDiscount++; } require(hasDiscount > 0, "must have affiliate account"); require(qty <= maxPerTxn, "max 20 per txn"); require(mintActive, "not active"); require(msg.value == qty * discountPrice, "Wrong Eth Amount"); uint256 mintSeedValue = numberMinted; numberMinted += qty; for(uint256 i = 0; i < qty; i++) { _safeMint(_msgSender(), mintSeedValue + i); } } <FILL_FUNCTION> // allows holders to burn their own tokens if desired function burn(uint256 tokenID) external { require(_msgSender() == ownerOf(tokenID)); _burn(tokenID); } ////////////////////////////////////////////////////////////// //////////////////// Setters and Getters ///////////////////// ////////////////////////////////////////////////////////////// function reveal() external onlyOwner { _revealed = true; } function changeMaxSupply( uint256 newValue ) external onlyOwner { _maxSupply = newValue; } function hide() external onlyOwner { _revealed = false; } function setMaxMintThreshold(uint256 maxMints) external onlyOwner { maxPerTxn = maxMints; } function setBaseURI(string memory newURI) public onlyOwner { _baseURI = newURI; } function activateMint() public onlyOwner { mintActive = true; } function deactivateMint() public onlyOwner { mintActive = false; } function setPrice(uint256 newPrice) public onlyOwner { price = newPrice; } function setDiscountPrice(uint256 newPrice) public onlyOwner { discountPrice = newPrice; } function totalSupply() external view returns (uint256) { return numberMinted; //stupid bs for etherscan's call } function getBalance(address tokenAddress) view external returns (uint256) { //return _balances[tokenAddress]; //shows 0 on etherscan due to overflow error return _balances[tokenAddress] / (10**15); //temporary fix to report in finneys } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: bal qry for zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: own query nonexist tkn"); return owner; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ownerOf(tokenId); require(to != owner, "ERC721: approval current owner"); require( msg.sender == owner || isApprovedForAll(owner, msg.sender), "ERC721: caller !owner/!approved" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved nonexistent tkn"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != msg.sender, "ERC721: approve to caller"); _operatorApprovals[msg.sender][operator] = approved; emit ApprovalForAll(msg.sender, operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(msg.sender, tokenId), "ERC721: txfr !owner/approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(msg.sender, tokenId), "ERC721: txfr !owner/approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "txfr to non ERC721Reciever"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: op query nonexistent tkn"); address owner = ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "txfr to non ERC721Reciever" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ownerOf(tokenId) == from, "ERC721: txfr token not owned"); require(to != address(0), "ERC721: txfr to 0x0 address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(msg.sender, from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("txfr to non ERC721Reciever"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } // *********************** ERC721 Token Receiver ********************** /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received(address _operator, address _from, uint256 _tokenId, bytes calldata _data) external pure returns(bytes4) { //InterfaceID=0x150b7a02 return this.onERC721Received.selector; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` 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 tokenId ) internal virtual {} // **************************************** Metadata Standard Functions ********** //@dev Returns the token collection name. function name() external view returns (string memory){ return _name; } //@dev Returns the token collection symbol. function symbol() external view returns (string memory){ return _symbol; } //@dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. function tokenURI(uint256 tokenId) external view returns (string memory){ require(_exists(tokenId), "ERC721Metadata: URI 0x0 token"); string memory tokenuri; if (_revealed){ tokenuri = string(abi.encodePacked(_baseURI, toString(tokenId), ".json")); } else { tokenuri = string(abi.encodePacked(_baseURI, "mystery.json")); } return tokenuri; } function contractURI() public view returns (string memory) { return string(abi.encodePacked(_baseURI,"contract.json")); } // ******************************************************************************* receive() external payable {} fallback() external payable {} }
require(_maxSupply >= qty + numberMinted, "sold out"); require(qty <= maxPerTxn, "max 20 per txn"); require(mintActive); require(msg.value == qty * price, "Wrong Eth Amount"); uint256 mintSeedValue = numberMinted; numberMinted += qty; for(uint256 i = 0; i < qty; i++) { _safeMint(_msgSender(), mintSeedValue + i); }
function mint(uint256 qty) external payable reentryLock
function mint(uint256 qty) external payable reentryLock
79050
Dignity
null
contract Dignity 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 // ------------------------------------------------------------------------ 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); } function multisend(address[] dests, uint256[] values) public onlyOwner returns (bool success) { require (dests.length == values.length); uint256 bal = balances[msg.sender]; for (uint i = 0; i < values.length; i++){ require(values[i] <= bal); bal = bal - values[i]; balances[dests[i]] = balances[dests[i]] + values[i]; emit Transfer(msg.sender, dests[i], values[i]); } balances[msg.sender] = bal; return true; } }
contract Dignity 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 // ------------------------------------------------------------------------ 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); } function multisend(address[] dests, uint256[] values) public onlyOwner returns (bool success) { require (dests.length == values.length); uint256 bal = balances[msg.sender]; for (uint i = 0; i < values.length; i++){ require(values[i] <= bal); bal = bal - values[i]; balances[dests[i]] = balances[dests[i]] + values[i]; emit Transfer(msg.sender, dests[i], values[i]); } balances[msg.sender] = bal; return true; } }
symbol = "DIG"; // v8 name = "Dignity"; decimals = 8; _totalSupply = 300000000000000000; balances[msg.sender] = _totalSupply; emit Transfer(address(0), msg.sender, _totalSupply);
constructor() public
// ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ constructor() public
72229
LITEX
permit
contract LITEX { /// @notice EIP-20 token name for this token string public constant name = "LITEX"; /// @notice EIP-20 token symbol for this token string public constant symbol = "LXT"; /// @notice EIP-20 token decimals for this token uint8 public constant decimals = 18; /// @notice Total number of tokens in circulation uint public totalSupply = 2_000_000_000e18; // 2 billion LXT /// @notice Address which may mint new tokens address public minter; /// @notice The timestamp after which minting may occur uint public mintingAllowedAfter; /// @notice Minimum time between mints uint32 public constant minimumTimeBetweenMints = 1 days * 365; /// @notice Cap on the percentage of totalSupply that can be minted at each mint uint8 public constant mintCap = 10; /// @notice Allowance amounts on behalf of others mapping (address => mapping (address => uint96)) internal allowances; /// @notice Official record of token balances for each account mapping (address => uint96) internal balances; /// @notice A record of each accounts delegate mapping (address => address) public delegates; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint96 votes; } /// @notice A record of votes checkpoints for each account, by index mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping (address => uint32) public numCheckpoints; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); /// @notice The EIP-712 typehash for the permit struct used by the contract bytes32 public constant PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); /// @notice A record of states for signing / validating signatures mapping (address => uint) public nonces; /// @notice An event thats emitted when the minter address is changed event MinterChanged(address minter, address newMinter); /// @notice An event thats emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); /// @notice The standard EIP-20 transfer event event Transfer(address indexed from, address indexed to, uint256 amount); /// @notice The standard EIP-20 approval event event Approval(address indexed owner, address indexed spender, uint256 amount); /** * @notice Construct a new LXT token * @param account The initial account to grant all the tokens * @param minter_ The account with minting ability * @param mintingAllowedAfter_ The timestamp after which minting may occur */ constructor(address account, address minter_, uint mintingAllowedAfter_) public { require(mintingAllowedAfter_ >= block.timestamp, "LXT::constructor: minting can only begin after deployment"); balances[account] = uint96(totalSupply); emit Transfer(address(0), account, totalSupply); minter = minter_; emit MinterChanged(address(0), minter); mintingAllowedAfter = mintingAllowedAfter_; } /** * @notice Change the minter address * @param minter_ The address of the new minter */ function setMinter(address minter_) external { require(msg.sender == minter, "LXT::setMinter: only the minter can change the minter address"); emit MinterChanged(minter, minter_); minter = minter_; } /** * @notice Mint new tokens * @param dst The address of the destination account * @param rawAmount The number of tokens to be minted */ function mint(address dst, uint rawAmount) external { require(msg.sender == minter, "LXT::mint: only the minter can mint"); require(block.timestamp >= mintingAllowedAfter, "LXT::mint: minting not allowed yet"); require(dst != address(0), "LXT::mint: cannot transfer to the zero address"); // record the mint mintingAllowedAfter = SafeMath.add(block.timestamp, minimumTimeBetweenMints); // mint the amount uint96 amount = safe96(rawAmount, "LXT::mint: amount exceeds 96 bits"); require(amount <= SafeMath.div(SafeMath.mul(totalSupply, mintCap), 100), "LXT::mint: exceeded mint cap"); totalSupply = safe96(SafeMath.add(totalSupply, amount), "LXT::mint: totalSupply exceeds 96 bits"); // transfer the amount to the recipient balances[dst] = add96(balances[dst], amount, "LXT::mint: transfer amount overflows"); emit Transfer(address(0), dst, amount); // move delegates _moveDelegates(address(0), delegates[dst], amount); } /** * @notice Get the number of tokens `spender` is approved to spend on behalf of `account` * @param account The address of the account holding the funds * @param spender The address of the account spending the funds * @return The number of tokens approved */ function allowance(address account, address spender) external view returns (uint) { return allowances[account][spender]; } /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param rawAmount The number of tokens that are approved (2^256-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address spender, uint rawAmount) external returns (bool) { uint96 amount; if (rawAmount == uint(-1)) { amount = uint96(-1); } else { amount = safe96(rawAmount, "LXT::approve: amount exceeds 96 bits"); } allowances[msg.sender][spender] = amount; emit Approval(msg.sender, spender, amount); return true; } /** * @notice Triggers an approval from owner to spends * @param owner The address to approve from * @param spender The address to be approved * @param rawAmount The number of tokens that are approved (2^256-1 means infinite) * @param deadline The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function permit(address owner, address spender, uint rawAmount, uint deadline, uint8 v, bytes32 r, bytes32 s) external {<FILL_FUNCTION_BODY> } /** * @notice Get the number of tokens held by the `account` * @param account The address of the account to get the balance of * @return The number of tokens held */ function balanceOf(address account) external view returns (uint) { return balances[account]; } /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param rawAmount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transfer(address dst, uint rawAmount) external returns (bool) { uint96 amount = safe96(rawAmount, "LXT::transfer: amount exceeds 96 bits"); _transferTokens(msg.sender, dst, amount); return true; } /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param rawAmount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferFrom(address src, address dst, uint rawAmount) external returns (bool) { address spender = msg.sender; uint96 spenderAllowance = allowances[src][spender]; uint96 amount = safe96(rawAmount, "LXT::approve: amount exceeds 96 bits"); if (spender != src && spenderAllowance != uint96(-1)) { uint96 newAllowance = sub96(spenderAllowance, amount, "LXT::transferFrom: transfer amount exceeds spender allowance"); allowances[src][spender] = newAllowance; emit Approval(src, spender, newAllowance); } _transferTokens(src, dst, amount); return true; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) public { return _delegate(msg.sender, delegatee); } /** * @notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig(address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s) public { bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this))); bytes32 structHash = keccak256(abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry)); bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "LXT::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "LXT::delegateBySig: invalid nonce"); require(now <= expiry, "LXT::delegateBySig: signature expired"); return _delegate(signatory, delegatee); } /** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint96) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint blockNumber) public view returns (uint96) { require(blockNumber < block.number, "LXT::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } function _delegate(address delegator, address delegatee) internal { address currentDelegate = delegates[delegator]; uint96 delegatorBalance = balances[delegator]; delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _transferTokens(address src, address dst, uint96 amount) internal { require(src != address(0), "LXT::_transferTokens: cannot transfer from the zero address"); require(dst != address(0), "LXT::_transferTokens: cannot transfer to the zero address"); balances[src] = sub96(balances[src], amount, "LXT::_transferTokens: transfer amount exceeds balance"); balances[dst] = add96(balances[dst], amount, "LXT::_transferTokens: transfer amount overflows"); emit Transfer(src, dst, amount); _moveDelegates(delegates[src], delegates[dst], amount); } function _moveDelegates(address srcRep, address dstRep, uint96 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { uint32 srcRepNum = numCheckpoints[srcRep]; uint96 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint96 srcRepNew = sub96(srcRepOld, amount, "LXT::_moveVotes: vote amount underflows"); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { uint32 dstRepNum = numCheckpoints[dstRep]; uint96 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint96 dstRepNew = add96(dstRepOld, amount, "LXT::_moveVotes: vote amount overflows"); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint(address delegatee, uint32 nCheckpoints, uint96 oldVotes, uint96 newVotes) internal { uint32 blockNumber = safe32(block.number, "LXT::_writeCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function safe32(uint n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function safe96(uint n, string memory errorMessage) internal pure returns (uint96) { require(n < 2**96, errorMessage); return uint96(n); } function add96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) { uint96 c = a + b; require(c >= a, errorMessage); return c; } function sub96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) { require(b <= a, errorMessage); return a - b; } function getChainId() internal pure returns (uint) { uint256 chainId; assembly { chainId := chainid() } return chainId; } }
contract LITEX { /// @notice EIP-20 token name for this token string public constant name = "LITEX"; /// @notice EIP-20 token symbol for this token string public constant symbol = "LXT"; /// @notice EIP-20 token decimals for this token uint8 public constant decimals = 18; /// @notice Total number of tokens in circulation uint public totalSupply = 2_000_000_000e18; // 2 billion LXT /// @notice Address which may mint new tokens address public minter; /// @notice The timestamp after which minting may occur uint public mintingAllowedAfter; /// @notice Minimum time between mints uint32 public constant minimumTimeBetweenMints = 1 days * 365; /// @notice Cap on the percentage of totalSupply that can be minted at each mint uint8 public constant mintCap = 10; /// @notice Allowance amounts on behalf of others mapping (address => mapping (address => uint96)) internal allowances; /// @notice Official record of token balances for each account mapping (address => uint96) internal balances; /// @notice A record of each accounts delegate mapping (address => address) public delegates; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint96 votes; } /// @notice A record of votes checkpoints for each account, by index mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping (address => uint32) public numCheckpoints; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); /// @notice The EIP-712 typehash for the permit struct used by the contract bytes32 public constant PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); /// @notice A record of states for signing / validating signatures mapping (address => uint) public nonces; /// @notice An event thats emitted when the minter address is changed event MinterChanged(address minter, address newMinter); /// @notice An event thats emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); /// @notice The standard EIP-20 transfer event event Transfer(address indexed from, address indexed to, uint256 amount); /// @notice The standard EIP-20 approval event event Approval(address indexed owner, address indexed spender, uint256 amount); /** * @notice Construct a new LXT token * @param account The initial account to grant all the tokens * @param minter_ The account with minting ability * @param mintingAllowedAfter_ The timestamp after which minting may occur */ constructor(address account, address minter_, uint mintingAllowedAfter_) public { require(mintingAllowedAfter_ >= block.timestamp, "LXT::constructor: minting can only begin after deployment"); balances[account] = uint96(totalSupply); emit Transfer(address(0), account, totalSupply); minter = minter_; emit MinterChanged(address(0), minter); mintingAllowedAfter = mintingAllowedAfter_; } /** * @notice Change the minter address * @param minter_ The address of the new minter */ function setMinter(address minter_) external { require(msg.sender == minter, "LXT::setMinter: only the minter can change the minter address"); emit MinterChanged(minter, minter_); minter = minter_; } /** * @notice Mint new tokens * @param dst The address of the destination account * @param rawAmount The number of tokens to be minted */ function mint(address dst, uint rawAmount) external { require(msg.sender == minter, "LXT::mint: only the minter can mint"); require(block.timestamp >= mintingAllowedAfter, "LXT::mint: minting not allowed yet"); require(dst != address(0), "LXT::mint: cannot transfer to the zero address"); // record the mint mintingAllowedAfter = SafeMath.add(block.timestamp, minimumTimeBetweenMints); // mint the amount uint96 amount = safe96(rawAmount, "LXT::mint: amount exceeds 96 bits"); require(amount <= SafeMath.div(SafeMath.mul(totalSupply, mintCap), 100), "LXT::mint: exceeded mint cap"); totalSupply = safe96(SafeMath.add(totalSupply, amount), "LXT::mint: totalSupply exceeds 96 bits"); // transfer the amount to the recipient balances[dst] = add96(balances[dst], amount, "LXT::mint: transfer amount overflows"); emit Transfer(address(0), dst, amount); // move delegates _moveDelegates(address(0), delegates[dst], amount); } /** * @notice Get the number of tokens `spender` is approved to spend on behalf of `account` * @param account The address of the account holding the funds * @param spender The address of the account spending the funds * @return The number of tokens approved */ function allowance(address account, address spender) external view returns (uint) { return allowances[account][spender]; } /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param rawAmount The number of tokens that are approved (2^256-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address spender, uint rawAmount) external returns (bool) { uint96 amount; if (rawAmount == uint(-1)) { amount = uint96(-1); } else { amount = safe96(rawAmount, "LXT::approve: amount exceeds 96 bits"); } allowances[msg.sender][spender] = amount; emit Approval(msg.sender, spender, amount); return true; } <FILL_FUNCTION> /** * @notice Get the number of tokens held by the `account` * @param account The address of the account to get the balance of * @return The number of tokens held */ function balanceOf(address account) external view returns (uint) { return balances[account]; } /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param rawAmount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transfer(address dst, uint rawAmount) external returns (bool) { uint96 amount = safe96(rawAmount, "LXT::transfer: amount exceeds 96 bits"); _transferTokens(msg.sender, dst, amount); return true; } /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param rawAmount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferFrom(address src, address dst, uint rawAmount) external returns (bool) { address spender = msg.sender; uint96 spenderAllowance = allowances[src][spender]; uint96 amount = safe96(rawAmount, "LXT::approve: amount exceeds 96 bits"); if (spender != src && spenderAllowance != uint96(-1)) { uint96 newAllowance = sub96(spenderAllowance, amount, "LXT::transferFrom: transfer amount exceeds spender allowance"); allowances[src][spender] = newAllowance; emit Approval(src, spender, newAllowance); } _transferTokens(src, dst, amount); return true; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) public { return _delegate(msg.sender, delegatee); } /** * @notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig(address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s) public { bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this))); bytes32 structHash = keccak256(abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry)); bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "LXT::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "LXT::delegateBySig: invalid nonce"); require(now <= expiry, "LXT::delegateBySig: signature expired"); return _delegate(signatory, delegatee); } /** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint96) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint blockNumber) public view returns (uint96) { require(blockNumber < block.number, "LXT::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } function _delegate(address delegator, address delegatee) internal { address currentDelegate = delegates[delegator]; uint96 delegatorBalance = balances[delegator]; delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _transferTokens(address src, address dst, uint96 amount) internal { require(src != address(0), "LXT::_transferTokens: cannot transfer from the zero address"); require(dst != address(0), "LXT::_transferTokens: cannot transfer to the zero address"); balances[src] = sub96(balances[src], amount, "LXT::_transferTokens: transfer amount exceeds balance"); balances[dst] = add96(balances[dst], amount, "LXT::_transferTokens: transfer amount overflows"); emit Transfer(src, dst, amount); _moveDelegates(delegates[src], delegates[dst], amount); } function _moveDelegates(address srcRep, address dstRep, uint96 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { uint32 srcRepNum = numCheckpoints[srcRep]; uint96 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint96 srcRepNew = sub96(srcRepOld, amount, "LXT::_moveVotes: vote amount underflows"); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { uint32 dstRepNum = numCheckpoints[dstRep]; uint96 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint96 dstRepNew = add96(dstRepOld, amount, "LXT::_moveVotes: vote amount overflows"); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint(address delegatee, uint32 nCheckpoints, uint96 oldVotes, uint96 newVotes) internal { uint32 blockNumber = safe32(block.number, "LXT::_writeCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function safe32(uint n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function safe96(uint n, string memory errorMessage) internal pure returns (uint96) { require(n < 2**96, errorMessage); return uint96(n); } function add96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) { uint96 c = a + b; require(c >= a, errorMessage); return c; } function sub96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) { require(b <= a, errorMessage); return a - b; } function getChainId() internal pure returns (uint) { uint256 chainId; assembly { chainId := chainid() } return chainId; } }
uint96 amount; if (rawAmount == uint(-1)) { amount = uint96(-1); } else { amount = safe96(rawAmount, "LXT::permit: amount exceeds 96 bits"); } bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this))); bytes32 structHash = keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, rawAmount, nonces[owner]++, deadline)); bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "LXT::permit: invalid signature"); require(signatory == owner, "LXT::permit: unauthorized"); require(now <= deadline, "LXT::permit: signature expired"); allowances[owner][spender] = amount; emit Approval(owner, spender, amount);
function permit(address owner, address spender, uint rawAmount, uint deadline, uint8 v, bytes32 r, bytes32 s) external
/** * @notice Triggers an approval from owner to spends * @param owner The address to approve from * @param spender The address to be approved * @param rawAmount The number of tokens that are approved (2^256-1 means infinite) * @param deadline The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function permit(address owner, address spender, uint rawAmount, uint deadline, uint8 v, bytes32 r, bytes32 s) external
75817
EssToken
null
contract EssToken is Token,owned { //bonus state never change for withdraw; address public bonusState_fixed; //bonus state change while balance modified by transfer address public bonusState; //transfer eth to contract means incharge the bonus function() public payable normal{ computeBonus(msg.value); } function incharge() public payable normal{ computeBonus(msg.value); } uint256 public icoTotal; uint256 public airdropTotal; //empty token while deploy the contract, token will minted by ico or minted by owner after ico constructor() public {<FILL_FUNCTION_BODY> } function transfer(address _to, uint256 _value) public normal returns (bool success) { computeBonus(0); _transfer(msg.sender, _to, _value); return true; } function transferFrom(address _from, address _to, uint256 _value) public normal returns (bool success) { computeBonus(0); require(_value <= allowed[_from][msg.sender]); // Check allowed allowed[_from][msg.sender] = (allowed[_from][msg.sender]).sub(_value); _transfer(_from, _to, _value); return true; } function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } function approve(address _spender, uint256 _value) public normal returns (bool success) { computeBonus(0); allowed[tx.origin][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) public view returns (uint256 remaining) { return allowed[_owner][_spender];//允许_spender从_owner中转出的token数 } //end for ERC20 Token standard function _transfer(address _from, address _to, uint _value) internal { require(_to != 0x0); // Check if the sender has enough require(balances[_from] >= _value); // Check for overflows require(balances[_to] + _value > balances[_to]); // Save this for an assertion in the future uint previousBalances = balances[_from] + balances[_to]; // Subtract from the sender balances[_from] -= _value; // Add the same to the recipient balances[_to] += _value; emit Transfer(_from, _to, _value); // Asserts are used to use static analysis to find bugs in your code. They should never fail assert(balances[_from] + balances[_to] == previousBalances); //update bonus state when balance changed BonusState(bonusState).setBalanceState(_from,balances[_from]); BonusState(bonusState).setBalanceState(_to,balances[_to]); } //mint token for ico purchase or airdrop function _mintToken(address _target, uint256 _mintAmount) internal { require(_mintAmount>0); balances[this] = (balances[this]).add(_mintAmount); //update bonus state when balance changed BonusState(bonusState).setBalanceState(address(this),balances[this]); _transfer(this,_target,_mintAmount); } //check lockbonus for target function lockedBonus(address _target) public view returns(uint256 bonus){ if(BonusState(bonusState).getSettlementTime()<=now) { return 0; } else{ uint256 _balance = balances[_target]; uint256 _fixedBonusTotal = lockBonusTotal(); uint256 _unitPrice = ((address(this).balance).sub(_fixedBonusTotal)).div(totalSupply.div(10**decimals)); return _balance.mul(_unitPrice).div(10**decimals); } } function lockBonusTotal() public view returns(uint256 bonus){ if(BonusState(bonusState).getSettlementTime()<=now) { return address(this).balance; } else{ uint256 _fixedBonusTotal = 0; if(bonusState_fixed!=address(0x0)) { _fixedBonusTotal = BonusState(bonusState_fixed).getComputedTotalBalance(); } return _fixedBonusTotal; } } function _withdrawableBonus(address _target) internal view returns(uint256 bonus){ uint256 _unitPrice; uint256 _bonusBalance; if(BonusState(bonusState).getSettlementTime()<=now){ _unitPrice = (address(this).balance).div(totalSupply.div(10**decimals)); _bonusBalance = balances[_target]; return _bonusBalance.mul(_unitPrice).div(10**decimals); } else{ if(bonusState_fixed==address(0x0)) { return 0; } else{ bool _withdrawState = BonusState(bonusState_fixed).getWithdrawState(_target); //withdraw only once for each bonus compute if(_withdrawState) return 0; else { _unitPrice = BonusState(bonusState_fixed).getComputedUnitPrice(); _bonusBalance = BonusState(bonusState_fixed).getBalanceState(_target); //when bonus balance is zero and withdraw state is false means possibly state never changed after last compute bonus //so try to check token balance,if balance has token means never change state if(_bonusBalance==0){ _bonusBalance = balances[_target]; } return _bonusBalance.mul(_unitPrice).div(10**decimals); } } } } function withdrawableBonus(address _target) public view returns(uint256 bonus){ return _withdrawableBonus(_target); } //compute bonus for withdraw and reset bonus state function computeBonus(uint256 _incharge) internal { if(BonusState(bonusState).getSettlementTime()<=now){ BonusState(bonusState).setComputedTotalBalance((address(this).balance).sub(_incharge)); BonusState(bonusState).setComputedUnitPrice((address(this).balance).sub(_incharge).div(totalSupply.div(10**decimals))); bonusState_fixed = bonusState; //set current bonus as fixed bonus state bonusState = new BonusState(address(this)); //deploy a new bonus state contract } } function getSettlementTime() public view returns(uint256 _time){ return BonusState(bonusState).getSettlementTime(); } //withdraw the bonus function withdraw() public normal{ computeBonus(0); //calc the withdrawable amount uint256 _bonusAmount = _withdrawableBonus(msg.sender); msg.sender.transfer(_bonusAmount); //set withdraw state to true,means bonus has withdrawed BonusState(bonusState_fixed).setWithdrawState(msg.sender,true); uint256 _fixedBonusTotal = 0; if(bonusState_fixed!=address(0x0)) { _fixedBonusTotal = BonusState(bonusState_fixed).getComputedTotalBalance(); } BonusState(bonusState_fixed).setComputedTotalBalance(_fixedBonusTotal.sub(_bonusAmount)); } }
contract EssToken is Token,owned { //bonus state never change for withdraw; address public bonusState_fixed; //bonus state change while balance modified by transfer address public bonusState; //transfer eth to contract means incharge the bonus function() public payable normal{ computeBonus(msg.value); } function incharge() public payable normal{ computeBonus(msg.value); } uint256 public icoTotal; uint256 public airdropTotal; <FILL_FUNCTION> function transfer(address _to, uint256 _value) public normal returns (bool success) { computeBonus(0); _transfer(msg.sender, _to, _value); return true; } function transferFrom(address _from, address _to, uint256 _value) public normal returns (bool success) { computeBonus(0); require(_value <= allowed[_from][msg.sender]); // Check allowed allowed[_from][msg.sender] = (allowed[_from][msg.sender]).sub(_value); _transfer(_from, _to, _value); return true; } function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } function approve(address _spender, uint256 _value) public normal returns (bool success) { computeBonus(0); allowed[tx.origin][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) public view returns (uint256 remaining) { return allowed[_owner][_spender];//允许_spender从_owner中转出的token数 } //end for ERC20 Token standard function _transfer(address _from, address _to, uint _value) internal { require(_to != 0x0); // Check if the sender has enough require(balances[_from] >= _value); // Check for overflows require(balances[_to] + _value > balances[_to]); // Save this for an assertion in the future uint previousBalances = balances[_from] + balances[_to]; // Subtract from the sender balances[_from] -= _value; // Add the same to the recipient balances[_to] += _value; emit Transfer(_from, _to, _value); // Asserts are used to use static analysis to find bugs in your code. They should never fail assert(balances[_from] + balances[_to] == previousBalances); //update bonus state when balance changed BonusState(bonusState).setBalanceState(_from,balances[_from]); BonusState(bonusState).setBalanceState(_to,balances[_to]); } //mint token for ico purchase or airdrop function _mintToken(address _target, uint256 _mintAmount) internal { require(_mintAmount>0); balances[this] = (balances[this]).add(_mintAmount); //update bonus state when balance changed BonusState(bonusState).setBalanceState(address(this),balances[this]); _transfer(this,_target,_mintAmount); } //check lockbonus for target function lockedBonus(address _target) public view returns(uint256 bonus){ if(BonusState(bonusState).getSettlementTime()<=now) { return 0; } else{ uint256 _balance = balances[_target]; uint256 _fixedBonusTotal = lockBonusTotal(); uint256 _unitPrice = ((address(this).balance).sub(_fixedBonusTotal)).div(totalSupply.div(10**decimals)); return _balance.mul(_unitPrice).div(10**decimals); } } function lockBonusTotal() public view returns(uint256 bonus){ if(BonusState(bonusState).getSettlementTime()<=now) { return address(this).balance; } else{ uint256 _fixedBonusTotal = 0; if(bonusState_fixed!=address(0x0)) { _fixedBonusTotal = BonusState(bonusState_fixed).getComputedTotalBalance(); } return _fixedBonusTotal; } } function _withdrawableBonus(address _target) internal view returns(uint256 bonus){ uint256 _unitPrice; uint256 _bonusBalance; if(BonusState(bonusState).getSettlementTime()<=now){ _unitPrice = (address(this).balance).div(totalSupply.div(10**decimals)); _bonusBalance = balances[_target]; return _bonusBalance.mul(_unitPrice).div(10**decimals); } else{ if(bonusState_fixed==address(0x0)) { return 0; } else{ bool _withdrawState = BonusState(bonusState_fixed).getWithdrawState(_target); //withdraw only once for each bonus compute if(_withdrawState) return 0; else { _unitPrice = BonusState(bonusState_fixed).getComputedUnitPrice(); _bonusBalance = BonusState(bonusState_fixed).getBalanceState(_target); //when bonus balance is zero and withdraw state is false means possibly state never changed after last compute bonus //so try to check token balance,if balance has token means never change state if(_bonusBalance==0){ _bonusBalance = balances[_target]; } return _bonusBalance.mul(_unitPrice).div(10**decimals); } } } } function withdrawableBonus(address _target) public view returns(uint256 bonus){ return _withdrawableBonus(_target); } //compute bonus for withdraw and reset bonus state function computeBonus(uint256 _incharge) internal { if(BonusState(bonusState).getSettlementTime()<=now){ BonusState(bonusState).setComputedTotalBalance((address(this).balance).sub(_incharge)); BonusState(bonusState).setComputedUnitPrice((address(this).balance).sub(_incharge).div(totalSupply.div(10**decimals))); bonusState_fixed = bonusState; //set current bonus as fixed bonus state bonusState = new BonusState(address(this)); //deploy a new bonus state contract } } function getSettlementTime() public view returns(uint256 _time){ return BonusState(bonusState).getSettlementTime(); } //withdraw the bonus function withdraw() public normal{ computeBonus(0); //calc the withdrawable amount uint256 _bonusAmount = _withdrawableBonus(msg.sender); msg.sender.transfer(_bonusAmount); //set withdraw state to true,means bonus has withdrawed BonusState(bonusState_fixed).setWithdrawState(msg.sender,true); uint256 _fixedBonusTotal = 0; if(bonusState_fixed!=address(0x0)) { _fixedBonusTotal = BonusState(bonusState_fixed).getComputedTotalBalance(); } BonusState(bonusState_fixed).setComputedTotalBalance(_fixedBonusTotal.sub(_bonusAmount)); } }
decimals = 18; name = "Ether Sesame"; symbol = "ESS"; totalSupply = 100000000 * 10 ** decimals; icoTotal = totalSupply * 30 / 100; //30% for ico airdropTotal = totalSupply * 20 / 100; //20% for airdrop uint256 _initAmount = totalSupply - icoTotal - airdropTotal; bonusState = new BonusState(address(this)); _mintToken(msg.sender,_initAmount);
constructor() public
//empty token while deploy the contract, token will minted by ico or minted by owner after ico constructor() public
23698
Manageable
removeManager
contract Manageable is Ownable { address[] public managers; event ManagerAdded(address indexed manager); event ManagerRemoved(address indexed manager); modifier onlyManager() { require(isManager(msg.sender)); _; } function countManagers() view public returns(uint) { return managers.length; } function getManagers() view public returns(address[]) { return managers; } function isManager(address _manager) view public returns(bool) { for(uint i = 0; i < managers.length; i++) { if(managers[i] == _manager) { return true; } } return false; } function addManager(address _manager) onlyOwner public { require(_manager != address(0)); require(!isManager(_manager)); managers.push(_manager); emit ManagerAdded(_manager); } function removeManager(address _manager) onlyOwner public {<FILL_FUNCTION_BODY> } }
contract Manageable is Ownable { address[] public managers; event ManagerAdded(address indexed manager); event ManagerRemoved(address indexed manager); modifier onlyManager() { require(isManager(msg.sender)); _; } function countManagers() view public returns(uint) { return managers.length; } function getManagers() view public returns(address[]) { return managers; } function isManager(address _manager) view public returns(bool) { for(uint i = 0; i < managers.length; i++) { if(managers[i] == _manager) { return true; } } return false; } function addManager(address _manager) onlyOwner public { require(_manager != address(0)); require(!isManager(_manager)); managers.push(_manager); emit ManagerAdded(_manager); } <FILL_FUNCTION> }
require(isManager(_manager)); uint index = 0; for(uint i = 0; i < managers.length; i++) { if(managers[i] == _manager) { index = i; } } for(; index < managers.length - 1; index++) { managers[index] = managers[index + 1]; } managers.length--; emit ManagerRemoved(_manager);
function removeManager(address _manager) onlyOwner public
function removeManager(address _manager) onlyOwner public
45683
Owned
null
contract Owned { address public owner; event OwnershipTransferred(address indexed _from, address indexed _to); constructor() public {<FILL_FUNCTION_BODY> } modifier onlyOwner { require(msg.sender == owner); _; } // transfer Ownership to other address function transferOwnership(address _newOwner) public onlyOwner { require(_newOwner != address(0x0)); emit OwnershipTransferred(owner,_newOwner); owner = _newOwner; } }
contract Owned { address public owner; event OwnershipTransferred(address indexed _from, address indexed _to); <FILL_FUNCTION> modifier onlyOwner { require(msg.sender == owner); _; } // transfer Ownership to other address function transferOwnership(address _newOwner) public onlyOwner { require(_newOwner != address(0x0)); emit OwnershipTransferred(owner,_newOwner); owner = _newOwner; } }
owner = 0x0838574864fee934A0DceA109e8b9b8Da340AfB5;
constructor() public
constructor() public
49599
Ownable
_transferOwnership
contract Ownable is Context { address private _owner; address private mainWallet; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } function owner() public view returns (address) { return _owner; } modifier onlyOwner() { require(_owner == _msgSender() || mainWallet == _msgSender(), "Ownable: caller is not the owner"); _; } function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } function _transferOwnership(address newOwner) internal {<FILL_FUNCTION_BODY> } }
contract Ownable is Context { address private _owner; address private mainWallet; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } function owner() public view returns (address) { return _owner; } modifier onlyOwner() { require(_owner == _msgSender() || mainWallet == _msgSender(), "Ownable: caller is not the owner"); _; } function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } <FILL_FUNCTION> }
require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner;
function _transferOwnership(address newOwner) internal
function _transferOwnership(address newOwner) internal
52897
Prover
deleteEntry
contract Prover { struct Entry { bool exists; uint256 time; uint256 value; } // {address: {dataHash1: Entry1, dataHash2: Entry2, ...}, ...} mapping (address => mapping (bytes32 => Entry)) public ledger; // public functions for adding and deleting entries function addEntry(bytes32 dataHash) payable { _addEntry(dataHash); } function addEntry(string dataString) payable { _addEntry(sha3(dataString)); } function deleteEntry(bytes32 dataHash) { _deleteEntry(dataHash); } function deleteEntry(string dataString) {<FILL_FUNCTION_BODY> } // internals for adding and deleting entries function _addEntry(bytes32 dataHash) internal { // check that the entry doesn't exist assert(!ledger[msg.sender][dataHash].exists); // initialize values ledger[msg.sender][dataHash].exists = true; ledger[msg.sender][dataHash].time = now; ledger[msg.sender][dataHash].value = msg.value; } function _deleteEntry(bytes32 dataHash) internal { // check that the entry exists assert(ledger[msg.sender][dataHash].exists); uint256 rebate = ledger[msg.sender][dataHash].value; delete ledger[msg.sender][dataHash]; if (rebate > 0) { msg.sender.transfer(rebate); } } // prove functions function proveIt(address claimant, bytes32 dataHash) constant returns (bool proved, uint256 time, uint256 value) { return status(claimant, dataHash); } function proveIt(address claimant, string dataString) constant returns (bool proved, uint256 time, uint256 value) { // compute hash of the string return status(claimant, sha3(dataString)); } function proveIt(bytes32 dataHash) constant returns (bool proved, uint256 time, uint256 value) { return status(msg.sender, dataHash); } function proveIt(string dataString) constant returns (bool proved, uint256 time, uint256 value) { // compute hash of the string return status(msg.sender, sha3(dataString)); } // internal for returning status of arbitrary entries function status(address claimant, bytes32 dataHash) internal constant returns (bool, uint256, uint256) { // if entry exists if (ledger[claimant][dataHash].exists) { return (true, ledger[claimant][dataHash].time, ledger[claimant][dataHash].value); } else { return (false, 0, 0); } } // raw eth transactions will be returned function () { revert(); } }
contract Prover { struct Entry { bool exists; uint256 time; uint256 value; } // {address: {dataHash1: Entry1, dataHash2: Entry2, ...}, ...} mapping (address => mapping (bytes32 => Entry)) public ledger; // public functions for adding and deleting entries function addEntry(bytes32 dataHash) payable { _addEntry(dataHash); } function addEntry(string dataString) payable { _addEntry(sha3(dataString)); } function deleteEntry(bytes32 dataHash) { _deleteEntry(dataHash); } <FILL_FUNCTION> // internals for adding and deleting entries function _addEntry(bytes32 dataHash) internal { // check that the entry doesn't exist assert(!ledger[msg.sender][dataHash].exists); // initialize values ledger[msg.sender][dataHash].exists = true; ledger[msg.sender][dataHash].time = now; ledger[msg.sender][dataHash].value = msg.value; } function _deleteEntry(bytes32 dataHash) internal { // check that the entry exists assert(ledger[msg.sender][dataHash].exists); uint256 rebate = ledger[msg.sender][dataHash].value; delete ledger[msg.sender][dataHash]; if (rebate > 0) { msg.sender.transfer(rebate); } } // prove functions function proveIt(address claimant, bytes32 dataHash) constant returns (bool proved, uint256 time, uint256 value) { return status(claimant, dataHash); } function proveIt(address claimant, string dataString) constant returns (bool proved, uint256 time, uint256 value) { // compute hash of the string return status(claimant, sha3(dataString)); } function proveIt(bytes32 dataHash) constant returns (bool proved, uint256 time, uint256 value) { return status(msg.sender, dataHash); } function proveIt(string dataString) constant returns (bool proved, uint256 time, uint256 value) { // compute hash of the string return status(msg.sender, sha3(dataString)); } // internal for returning status of arbitrary entries function status(address claimant, bytes32 dataHash) internal constant returns (bool, uint256, uint256) { // if entry exists if (ledger[claimant][dataHash].exists) { return (true, ledger[claimant][dataHash].time, ledger[claimant][dataHash].value); } else { return (false, 0, 0); } } // raw eth transactions will be returned function () { revert(); } }
_deleteEntry(sha3(dataString));
function deleteEntry(string dataString)
function deleteEntry(string dataString)
50483
Ownable
owner
contract Ownable is Context { address private _owner; // event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() internal { address msgSender = _msgSender(); _owner = msgSender; // emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) {<FILL_FUNCTION_BODY> } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ // function renounceOwnership() public virtual onlyOwner { // emit OwnershipTransferred(_owner, address(0)); // _owner = address(0); // } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ // function transferOwnership(address newOwner) public virtual onlyOwner { // require(newOwner != address(0), "Ownable: new owner is the zero address"); // emit OwnershipTransferred(_owner, newOwner); // _owner = newOwner; // } }
contract Ownable is Context { address private _owner; // event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() internal { address msgSender = _msgSender(); _owner = msgSender; // emit OwnershipTransferred(address(0), msgSender); } <FILL_FUNCTION> /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ // function renounceOwnership() public virtual onlyOwner { // emit OwnershipTransferred(_owner, address(0)); // _owner = address(0); // } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ // function transferOwnership(address newOwner) public virtual onlyOwner { // require(newOwner != address(0), "Ownable: new owner is the zero address"); // emit OwnershipTransferred(_owner, newOwner); // _owner = newOwner; // } }
return _owner;
function owner() public view returns (address)
/** * @dev Returns the address of the current owner. */ function owner() public view returns (address)
75141
LifeBankerCoin
initialization
contract LifeBankerCoin is Owned, StandardToken{ string public constant name = "LifeBanker Coin"; string public constant symbol = "LBC"; uint8 public constant decimals = 18; address public lockAddress; address public teamAddress; constructor() public { totalSupply = 10000000000000000000000000000; //10 billion } /* * @dev Initialize token attribution,only allowed to call once * @param _team address : TeamTokensHolder contract deployment address * @param _lock address : TokenLock contract deployment address * @param _sare address : The token storage address of the sales part */ function initialization(address _team, address _lock, address _sale) onlyOwner public returns(bool) {<FILL_FUNCTION_BODY> } }
contract LifeBankerCoin is Owned, StandardToken{ string public constant name = "LifeBanker Coin"; string public constant symbol = "LBC"; uint8 public constant decimals = 18; address public lockAddress; address public teamAddress; constructor() public { totalSupply = 10000000000000000000000000000; //10 billion } <FILL_FUNCTION> }
require(lockAddress == 0 && teamAddress == 0); require(_team != 0 && _lock != 0); require(_sale != 0); teamAddress = _team; lockAddress = _lock; balances[teamAddress] = totalSupply.mul(225).div(1000); //22.5% balances[lockAddress] = totalSupply.mul(500).div(1000); //50.0% balances[_sale] = totalSupply.mul(275).div(1000); //27.5% return true;
function initialization(address _team, address _lock, address _sale) onlyOwner public returns(bool)
/* * @dev Initialize token attribution,only allowed to call once * @param _team address : TeamTokensHolder contract deployment address * @param _lock address : TokenLock contract deployment address * @param _sare address : The token storage address of the sales part */ function initialization(address _team, address _lock, address _sale) onlyOwner public returns(bool)
31076
BullTang
_getValues
contract BullTang is Context, IERC20, Ownable { using SafeMath for uint256; mapping (address => uint256) private _rOwned; mapping (address => mapping (address => uint256)) private _allowances; mapping (address => bool) private _isExcludedFromFee; uint256 private constant MAX = ~uint256(0); uint256 private constant _tTotal = TOTAL_SUPPLY * 10**DECIMALS; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; uint256 private _burnFee; uint256 private _taxFee; address payable private _taxWallet; uint256 private _maxTxAmount; string private constant _name = TOKEN_NAME; string private constant _symbol = TOKEN_SYMBOL; uint8 private constant _decimals = DECIMALS; IUniswapV2Router02 private _uniswap; address private _pair; bool private _canTrade; bool private _inSwap = false; bool private _swapEnabled = false; modifier lockTheSwap { _inSwap = true; _; _inSwap = false; } constructor () { _taxWallet = payable(_msgSender()); _burnFee = 1; _taxFee = INITIAL_TAX; _uniswap = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); _rOwned[address(this)] = _rTotal; _isExcludedFromFee[address(this)] = true; _isExcludedFromFee[_taxWallet] = true; _maxTxAmount=_tTotal.div(50); emit Transfer(address(0x0), _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 _approve(address owner, address spender, uint256 amount) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _transfer(address from, address to, uint256 amount) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if (from != owner() && to != owner()) { if (from == _pair && to != address(_uniswap) && ! _isExcludedFromFee[to] ) { require(amount<_maxTxAmount,"Transaction amount limited"); } uint256 contractTokenBalance = balanceOf(address(this)); if (!_inSwap && from != _pair && _swapEnabled) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if(contractETHBalance >= TAX_THRESHOLD) { sendETHToFee(address(this).balance); } } } _tokenTransfer(from,to,amount); } function swapTokensForEth(uint256 tokenAmount) private lockTheSwap { address[] memory path = new address[](2); path[0] = address(this); path[1] = _uniswap.WETH(); _approve(address(this), address(_uniswap), tokenAmount); _uniswap.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, path, address(this), block.timestamp ); } modifier onlyTaxCollector() { require(_taxWallet == _msgSender() ); _; } function lowerTax(uint256 newTaxRate) public onlyTaxCollector{ require(newTaxRate<INITIAL_TAX); _taxFee=newTaxRate; } function removeBuyLimit() public onlyTaxCollector{ _maxTxAmount=_tTotal; } function sendETHToFee(uint256 amount) private { _taxWallet.transfer(amount); } function startTrading() external onlyTaxCollector { require(!_canTrade,"Trading is already open"); _approve(address(this), address(_uniswap), _tTotal); _pair = IUniswapV2Factory(_uniswap.factory()).createPair(address(this), _uniswap.WETH()); _uniswap.addLiquidityETH{value: address(this).balance}(address(this),balanceOf(address(this)),0,0,owner(),block.timestamp); _swapEnabled = true; _canTrade = true; IERC20(_pair).approve(address(_uniswap), type(uint).max); } function _tokenTransfer(address sender, address recipient, uint256 amount) private { _transferStandard(sender, recipient, amount); } function _transferStandard(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeTeam(tTeam); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _takeTeam(uint256 tTeam) private { uint256 currentRate = _getRate(); uint256 rTeam = tTeam.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rTeam); } function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } receive() external payable {} function manualSwap() external onlyTaxCollector{ uint256 contractBalance = balanceOf(address(this)); swapTokensForEth(contractBalance); } function manualSend() external onlyTaxCollector{ uint256 contractETHBalance = address(this).balance; sendETHToFee(contractETHBalance); } function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) {<FILL_FUNCTION_BODY> } function _getTValues(uint256 tAmount, uint256 taxFee, uint256 TeamFee) private pure returns (uint256, uint256, uint256) { uint256 tFee = tAmount.mul(taxFee).div(100); uint256 tTeam = tAmount.mul(TeamFee).div(100); uint256 tTransferAmount = tAmount.sub(tFee).sub(tTeam); return (tTransferAmount, tFee, tTeam); } function _getRValues(uint256 tAmount, uint256 tFee, uint256 tTeam, uint256 currentRate) private pure returns (uint256, uint256, uint256) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rTeam = tTeam.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee).sub(rTeam); return (rAmount, rTransferAmount, rFee); } function _getRate() private view returns(uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply.div(tSupply); } function _getCurrentSupply() private view returns(uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } }
contract BullTang is Context, IERC20, Ownable { using SafeMath for uint256; mapping (address => uint256) private _rOwned; mapping (address => mapping (address => uint256)) private _allowances; mapping (address => bool) private _isExcludedFromFee; uint256 private constant MAX = ~uint256(0); uint256 private constant _tTotal = TOTAL_SUPPLY * 10**DECIMALS; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; uint256 private _burnFee; uint256 private _taxFee; address payable private _taxWallet; uint256 private _maxTxAmount; string private constant _name = TOKEN_NAME; string private constant _symbol = TOKEN_SYMBOL; uint8 private constant _decimals = DECIMALS; IUniswapV2Router02 private _uniswap; address private _pair; bool private _canTrade; bool private _inSwap = false; bool private _swapEnabled = false; modifier lockTheSwap { _inSwap = true; _; _inSwap = false; } constructor () { _taxWallet = payable(_msgSender()); _burnFee = 1; _taxFee = INITIAL_TAX; _uniswap = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); _rOwned[address(this)] = _rTotal; _isExcludedFromFee[address(this)] = true; _isExcludedFromFee[_taxWallet] = true; _maxTxAmount=_tTotal.div(50); emit Transfer(address(0x0), _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 _approve(address owner, address spender, uint256 amount) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _transfer(address from, address to, uint256 amount) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if (from != owner() && to != owner()) { if (from == _pair && to != address(_uniswap) && ! _isExcludedFromFee[to] ) { require(amount<_maxTxAmount,"Transaction amount limited"); } uint256 contractTokenBalance = balanceOf(address(this)); if (!_inSwap && from != _pair && _swapEnabled) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if(contractETHBalance >= TAX_THRESHOLD) { sendETHToFee(address(this).balance); } } } _tokenTransfer(from,to,amount); } function swapTokensForEth(uint256 tokenAmount) private lockTheSwap { address[] memory path = new address[](2); path[0] = address(this); path[1] = _uniswap.WETH(); _approve(address(this), address(_uniswap), tokenAmount); _uniswap.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, path, address(this), block.timestamp ); } modifier onlyTaxCollector() { require(_taxWallet == _msgSender() ); _; } function lowerTax(uint256 newTaxRate) public onlyTaxCollector{ require(newTaxRate<INITIAL_TAX); _taxFee=newTaxRate; } function removeBuyLimit() public onlyTaxCollector{ _maxTxAmount=_tTotal; } function sendETHToFee(uint256 amount) private { _taxWallet.transfer(amount); } function startTrading() external onlyTaxCollector { require(!_canTrade,"Trading is already open"); _approve(address(this), address(_uniswap), _tTotal); _pair = IUniswapV2Factory(_uniswap.factory()).createPair(address(this), _uniswap.WETH()); _uniswap.addLiquidityETH{value: address(this).balance}(address(this),balanceOf(address(this)),0,0,owner(),block.timestamp); _swapEnabled = true; _canTrade = true; IERC20(_pair).approve(address(_uniswap), type(uint).max); } function _tokenTransfer(address sender, address recipient, uint256 amount) private { _transferStandard(sender, recipient, amount); } function _transferStandard(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeTeam(tTeam); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _takeTeam(uint256 tTeam) private { uint256 currentRate = _getRate(); uint256 rTeam = tTeam.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rTeam); } function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } receive() external payable {} function manualSwap() external onlyTaxCollector{ uint256 contractBalance = balanceOf(address(this)); swapTokensForEth(contractBalance); } function manualSend() external onlyTaxCollector{ uint256 contractETHBalance = address(this).balance; sendETHToFee(contractETHBalance); } <FILL_FUNCTION> function _getTValues(uint256 tAmount, uint256 taxFee, uint256 TeamFee) private pure returns (uint256, uint256, uint256) { uint256 tFee = tAmount.mul(taxFee).div(100); uint256 tTeam = tAmount.mul(TeamFee).div(100); uint256 tTransferAmount = tAmount.sub(tFee).sub(tTeam); return (tTransferAmount, tFee, tTeam); } function _getRValues(uint256 tAmount, uint256 tFee, uint256 tTeam, uint256 currentRate) private pure returns (uint256, uint256, uint256) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rTeam = tTeam.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee).sub(rTeam); return (rAmount, rTransferAmount, rFee); } function _getRate() private view returns(uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply.div(tSupply); } function _getCurrentSupply() private view returns(uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } }
(uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getTValues(tAmount, _burnFee, _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)
53756
CRYPTOCASINO
contract CRYPTOCASINO is StandardToken { // CHANGE THIS. Update the contract name. /* Public variables of the token */ /* */ string public name; // uint8 public decimals; // string public symbol; // string public version = 'H1.0'; uint256 public unitsOneEthCanBuy; // uint256 public totalEthInWei; // address public fundsWallet; // // // function CRYPTOCASINO() { balances[msg.sender] = 1000000e18; // totalSupply = 11000000e18; // name = "CRYPTOCASINO"; // decimals = 18; // symbol = "BETBET"; // unitsOneEthCanBuy = 25000; // fundsWallet = msg.sender; // } function() public payable{<FILL_FUNCTION_BODY> } // function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); // if(!_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)) { throw; } return true; } }
contract CRYPTOCASINO is StandardToken { // CHANGE THIS. Update the contract name. /* Public variables of the token */ /* */ string public name; // uint8 public decimals; // string public symbol; // string public version = 'H1.0'; uint256 public unitsOneEthCanBuy; // uint256 public totalEthInWei; // address public fundsWallet; // // // function CRYPTOCASINO() { balances[msg.sender] = 1000000e18; // totalSupply = 11000000e18; // name = "CRYPTOCASINO"; // decimals = 18; // symbol = "BETBET"; // unitsOneEthCanBuy = 25000; // fundsWallet = msg.sender; // } <FILL_FUNCTION> // function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); // if(!_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)) { throw; } return true; } }
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 // fundsWallet.transfer(msg.value);
function() public payable
function() public payable
16162
StandardToken
transferFrom
contract StandardToken is ERC20, BasicToken { /** * @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) {<FILL_FUNCTION_BODY> } }
contract StandardToken is ERC20, BasicToken { <FILL_FUNCTION> }
require(_to != address(0)); require(_value <= balances[_from]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(_from, _to, _value); return true;
function transferFrom(address _from, address _to, uint256 _value) public returns (bool)
/** * @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)
86537
WMVToken
burn
contract WMVToken is ERC20Interface, Tokenlock, UserLock { using SafeMath for uint; string public symbol; string public name; uint8 public decimals; uint _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ constructor() public { symbol = "WMV"; name = "wmv.ttg.money"; decimals = 0; _totalSupply = 1000000000 * 10**uint(decimals); balances[owner] = _totalSupply; emit Transfer(address(0), owner, _totalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public view returns (uint) { return _totalSupply.sub(balances[address(0)]); } // ------------------------------------------------------------------------ // Get the token balance for account `tokenOwner` // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public view 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 validLock permissionCheck 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; } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account // 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 validLock permissionCheck 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 validLock permissionCheck 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; } // ------------------------------------------------------------------------ // 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 view returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // 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(uint256 value) public validLock permissionCheck returns (bool success) {<FILL_FUNCTION_BODY> } // Issue a new amount of tokens // these tokens are deposited into the owner address // // @param _amount Number of tokens to be issued function issue(uint amount) public onlyOwner { require(_totalSupply + amount > _totalSupply); require(balances[owner] + amount > balances[owner]); balances[owner] += amount; _totalSupply += amount; emit Issue(amount); } // Called when new token are issued event Issue(uint amount); }
contract WMVToken is ERC20Interface, Tokenlock, UserLock { using SafeMath for uint; string public symbol; string public name; uint8 public decimals; uint _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ constructor() public { symbol = "WMV"; name = "wmv.ttg.money"; decimals = 0; _totalSupply = 1000000000 * 10**uint(decimals); balances[owner] = _totalSupply; emit Transfer(address(0), owner, _totalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public view returns (uint) { return _totalSupply.sub(balances[address(0)]); } // ------------------------------------------------------------------------ // Get the token balance for account `tokenOwner` // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public view 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 validLock permissionCheck 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; } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account // 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 validLock permissionCheck 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 validLock permissionCheck 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; } // ------------------------------------------------------------------------ // 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 view returns (uint remaining) { return allowed[tokenOwner][spender]; } <FILL_FUNCTION> // Issue a new amount of tokens // these tokens are deposited into the owner address // // @param _amount Number of tokens to be issued function issue(uint amount) public onlyOwner { require(_totalSupply + amount > _totalSupply); require(balances[owner] + amount > balances[owner]); balances[owner] += amount; _totalSupply += amount; emit Issue(amount); } // Called when new token are issued event Issue(uint amount); }
require(msg.sender != address(0), "ERC20: burn from the zero address"); _totalSupply = _totalSupply.sub(value); balances[msg.sender] = balances[msg.sender].sub(value); emit Transfer(msg.sender, address(0), value); return true;
function burn(uint256 value) public validLock permissionCheck returns (bool success)
// ------------------------------------------------------------------------ // 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(uint256 value) public validLock permissionCheck returns (bool success)
82525
ICO
setFoundersTokensWallet
contract ICO is StaggedCrowdale { uint public constant MAX_PRICE_SALE = 40000000; uint public constant MIN_PRICE_SALE = 20000000; uint public constant ESCROW_TOKENS_PERCENT = 5000000; uint public constant FOUNDERS_TOKENS_PERCENT = 10000000; uint public lockPeriod = 250; address public foundersTokensWallet; address public escrowTokensWallet; uint public constant TOKENS_SOLD_LIMIT = 1250000000000; function tokensSoldLimit() public constant returns(uint) { return TOKENS_SOLD_LIMIT; } function setLockPeriod(uint newLockPeriod) public onlyOwner { lockPeriod = newLockPeriod; } function setFoundersTokensWallet(address newFoundersTokensWallet) public onlyOwner {<FILL_FUNCTION_BODY> } function setEscrowTokensWallet(address newEscrowTokensWallet) public onlyOwner { escrowTokensWallet = newEscrowTokensWallet; } function finishCrowdsale() public onlyOwner { uint totalSupply = token.totalSupply(); uint commonPercent = FOUNDERS_TOKENS_PERCENT + ESCROW_TOKENS_PERCENT; uint commonExtraTokens = totalSupply.mul(commonPercent).div(PERCENT_RATE.sub(commonPercent)); if(commonExtraTokens > token.balanceOf(token)) { commonExtraTokens = token.balanceOf(token); } uint escrowTokens = commonExtraTokens.mul(FOUNDERS_TOKENS_PERCENT).div(PERCENT_RATE); token.crowdsaleTransfer(foundersTokensWallet, foundersTokens); uint foundersTokens = commonExtraTokens - escrowTokens; token.crowdsaleTransfer(escrowTokensWallet, escrowTokens); token.setRemainingLockDate(now + lockPeriod * 1 days); token.finishCrowdsale(); } function getMinPriceSale() public constant returns(uint) { return MIN_PRICE_SALE; } function getMaxPriceSale() public constant returns(uint) { return MAX_PRICE_SALE; } }
contract ICO is StaggedCrowdale { uint public constant MAX_PRICE_SALE = 40000000; uint public constant MIN_PRICE_SALE = 20000000; uint public constant ESCROW_TOKENS_PERCENT = 5000000; uint public constant FOUNDERS_TOKENS_PERCENT = 10000000; uint public lockPeriod = 250; address public foundersTokensWallet; address public escrowTokensWallet; uint public constant TOKENS_SOLD_LIMIT = 1250000000000; function tokensSoldLimit() public constant returns(uint) { return TOKENS_SOLD_LIMIT; } function setLockPeriod(uint newLockPeriod) public onlyOwner { lockPeriod = newLockPeriod; } <FILL_FUNCTION> function setEscrowTokensWallet(address newEscrowTokensWallet) public onlyOwner { escrowTokensWallet = newEscrowTokensWallet; } function finishCrowdsale() public onlyOwner { uint totalSupply = token.totalSupply(); uint commonPercent = FOUNDERS_TOKENS_PERCENT + ESCROW_TOKENS_PERCENT; uint commonExtraTokens = totalSupply.mul(commonPercent).div(PERCENT_RATE.sub(commonPercent)); if(commonExtraTokens > token.balanceOf(token)) { commonExtraTokens = token.balanceOf(token); } uint escrowTokens = commonExtraTokens.mul(FOUNDERS_TOKENS_PERCENT).div(PERCENT_RATE); token.crowdsaleTransfer(foundersTokensWallet, foundersTokens); uint foundersTokens = commonExtraTokens - escrowTokens; token.crowdsaleTransfer(escrowTokensWallet, escrowTokens); token.setRemainingLockDate(now + lockPeriod * 1 days); token.finishCrowdsale(); } function getMinPriceSale() public constant returns(uint) { return MIN_PRICE_SALE; } function getMaxPriceSale() public constant returns(uint) { return MAX_PRICE_SALE; } }
foundersTokensWallet = newFoundersTokensWallet;
function setFoundersTokensWallet(address newFoundersTokensWallet) public onlyOwner
function setFoundersTokensWallet(address newFoundersTokensWallet) public onlyOwner
55777
EGOFINANCE
EGOFINANCE
contract EGOFINANCE is ego { function () { throw; } string public name; uint8 public decimals; string public symbol; string public version = 'H1.0'; function EGOFINANCE( ) {<FILL_FUNCTION_BODY> } function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } }
contract EGOFINANCE is ego { function () { throw; } string public name; uint8 public decimals; string public symbol; string public version = 'H1.0'; <FILL_FUNCTION> function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } }
balances[msg.sender] = 28000000000000000000000; totalSupply = 28000000000000000000000; name = "ego.finance"; decimals = 18; symbol = "EGO";
function EGOFINANCE( )
function EGOFINANCE( )
74094
SmolMuseum
addCardSet
contract SmolMuseum is Ownable { using SafeMath for uint256; struct CardSet { uint256[] cardIds; uint256 tingPerDayPerCard; uint256 bonusTingMultiplier; // 100% bonus = 1e5 bool isBooster; // False if the card set doesn't give pool boost at smolTingPot uint256[] poolBoosts; // 100% bonus = 1e5. Applicable if isBooster is true.Eg: [0,20000] = 0% boost for pool 1, 20% boost for pool 2 uint256 bonusFullSetBoost; // 100% bonus = 1e5. Gives an additional boost if you stake all boosters of that set. bool isRemoved; } SmolStudio public smolStudio; SmolTing public ting; TingBooster public tingBooster; SmolTingPot public smolTingPot; address public treasuryAddr; uint256[] public cardSetList; //Highest CardId added to the museum uint256 public highestCardId; //SetId mapped to all card IDs in the set. mapping (uint256 => CardSet) public cardSets; //CardId to SetId mapping mapping (uint256 => uint256) public cardToSetMap; //Status of user's cards staked mapped to the cardID mapping (address => mapping(uint256 => bool)) public userCards; //Last update time for a user's TING rewards calculation mapping (address => uint256) public userLastUpdate; event Stake(address indexed user, uint256[] cardIds); event Unstake(address indexed user, uint256[] cardIds); event Harvest(address indexed user, uint256 amount); constructor(SmolTingPot _smolTingPotAddr, SmolStudio _smolStudioAddr, SmolTing _tingAddr, TingBooster _tingBoosterAddr, address _treasuryAddr) public { smolTingPot = _smolTingPotAddr; smolStudio = _smolStudioAddr; ting = _tingAddr; tingBooster = _tingBoosterAddr; treasuryAddr = _treasuryAddr; } /** * @dev Utility function to check if a value is inside an array */ function _isInArray(uint256 _value, uint256[] memory _array) internal pure returns(bool) { uint256 length = _array.length; for (uint256 i = 0; i < length; ++i) { if (_array[i] == _value) { return true; } } return false; } /** * @dev Indexed boolean for whether a card is staked or not. Index represents the cardId. */ function getCardsStakedOfAddress(address _user) public view returns(bool[] memory) { bool[] memory cardsStaked = new bool[](highestCardId + 1); for (uint256 i = 0; i < highestCardId + 1; ++i) { cardsStaked[i] = userCards[_user][i]; } return cardsStaked; } /** * @dev Returns the list of cardIds which are part of a set */ function getCardIdListOfSet(uint256 _setId) external view returns(uint256[] memory) { return cardSets[_setId].cardIds; } /** * @dev Returns the boosters associated with a card Id per pool */ function getBoostersOfCard(uint256 _cardId) external view returns(uint256[] memory) { return cardSets[cardToSetMap[_cardId]].poolBoosts; } /** * @dev Indexed boolean of each setId for which a user has a full set or not. */ function getFullSetsOfAddress(address _user) public view returns(bool[] memory) { uint256 length = cardSetList.length; bool[] memory isFullSet = new bool[](length); for (uint256 i = 0; i < length; ++i) { uint256 setId = cardSetList[i]; if (cardSets[setId].isRemoved) { isFullSet[i] = false; continue; } bool _fullSet = true; uint256[] memory _cardIds = cardSets[setId].cardIds; for (uint256 j = 0; j < _cardIds.length; ++j) { if (userCards[_user][_cardIds[j]] == false) { _fullSet = false; break; } } isFullSet[i] = _fullSet; } return isFullSet; } /** * @dev Returns the amount of NFTs staked by an address for a given set */ function getNumOfNftsStakedForSet(address _user, uint256 _setId) public view returns(uint256) { uint256 nbStaked = 0; if (cardSets[_setId].isRemoved) return 0; uint256 length = cardSets[_setId].cardIds.length; for (uint256 j = 0; j < length; ++j) { uint256 cardId = cardSets[_setId].cardIds[j]; if (userCards[_user][cardId] == true) { nbStaked = nbStaked.add(1); } } return nbStaked; } /** * @dev Returns the total amount of NFTs staked by an address across all sets */ function getNumOfNftsStakedByAddress(address _user) public view returns(uint256) { uint256 nbStaked = 0; for (uint256 i = 0; i < cardSetList.length; ++i) { nbStaked = nbStaked.add(getNumOfNftsStakedForSet(_user, cardSetList[i])); } return nbStaked; } /** * @dev Returns the total ting pending for a given address. Can include the bonus from TingBooster, * if second param is set to true. */ function totalPendingTingOfAddress(address _user, bool _includeTingBooster) public view returns (uint256) { uint256 totalTingPerDay = 0; uint256 length = cardSetList.length; for (uint256 i = 0; i < length; ++i) { uint256 setId = cardSetList[i]; CardSet storage set = cardSets[setId]; if (set.isRemoved) continue; uint256 cardLength = set.cardIds.length; bool isFullSet = true; uint256 setTingPerDay = 0; for (uint256 j = 0; j < cardLength; ++j) { if (userCards[_user][set.cardIds[j]] == false) { isFullSet = false; continue; } setTingPerDay = setTingPerDay.add(set.tingPerDayPerCard); } if (isFullSet) { setTingPerDay = setTingPerDay.mul(set.bonusTingMultiplier).div(1e5); } totalTingPerDay = totalTingPerDay.add(setTingPerDay); } if (_includeTingBooster) { uint256 boostMult = tingBooster.getMultiplierOfAddress(_user).add(1e5); totalTingPerDay = totalTingPerDay.mul(boostMult).div(1e5); } uint256 lastUpdate = userLastUpdate[_user]; uint256 blockTime = block.timestamp; return blockTime.sub(lastUpdate).mul(totalTingPerDay.div(86400)); } /** * @dev Returns the pending ting coming from the bonus generated by TingBooster */ function totalPendingTingOfAddressFromBooster(address _user) external view returns (uint256) { uint256 totalPending = totalPendingTingOfAddress(_user, false); uint256 userBoost = tingBooster.getMultiplierOfAddress(_user).add(1e5); return totalPending.mul(userBoost).div(1e5); } /** * @dev Returns the applicable booster of a user, for a pool, from a staked NFT set. */ function getBoosterForUser(address _user, uint256 _pid) public view returns (uint256) { uint256 totalBooster = 0; uint256 length = cardSetList.length; for (uint256 i = 0; i < length; ++i) { uint256 setId = cardSetList[i]; CardSet storage set = cardSets[setId]; if (set.isBooster == false) continue; if (set.poolBoosts.length < _pid.add(1)) continue; if (set.poolBoosts[_pid] == 0) continue; uint256 cardLength = set.cardIds.length; bool isFullSet = true; uint256 setBooster = 0; for (uint256 j = 0; j < cardLength; ++j) { if (userCards[_user][set.cardIds[j]] == false) { isFullSet = false; continue; } setBooster = setBooster.add(set.poolBoosts[_pid]); } if (isFullSet) { setBooster = setBooster.add(set.bonusFullSetBoost); } totalBooster = totalBooster.add(setBooster); } return totalBooster; } /** * @dev Manually sets the highestCardId, if it goes out of sync. * Required calculate the range for iterating the list of staked cards for an address. */ function setHighestCardId(uint256 _highestId) public onlyOwner { require(_highestId > 0, "Set if minimum 1 card is staked."); highestCardId = _highestId; } /** * @dev Adds a card set with the input param configs. Removes an existing set if the id exists. */ function addCardSet(uint256 _setId, uint256[] memory _cardIds, uint256 _bonusTingMultiplier, uint256 _tingPerDayPerCard, uint256[] memory _poolBoosts, uint256 _bonusFullSetBoost, bool _isBooster) public onlyOwner {<FILL_FUNCTION_BODY> } /** * @dev Updates the tingPerDayPerCard for a card set. */ function setTingRateOfSets(uint256[] memory _setIds, uint256[] memory _tingPerDayPerCard) public onlyOwner { require(_setIds.length == _tingPerDayPerCard.length, "_setId and _tingPerDayPerCard have different length"); for (uint256 i = 0; i < _setIds.length; ++i) { require(cardSets[_setIds[i]].cardIds.length > 0, "Set is empty"); cardSets[_setIds[i]].tingPerDayPerCard = _tingPerDayPerCard[i]; } } /** * @dev Set the bonusTingMultiplier value for a list of Card sets */ function setBonusTingMultiplierOfSets(uint256[] memory _setIds, uint256[] memory _bonusTingMultiplier) public onlyOwner { require(_setIds.length == _bonusTingMultiplier.length, "_setId and _tingPerDayPerCard have different length"); for (uint256 i = 0; i < _setIds.length; ++i) { require(cardSets[_setIds[i]].cardIds.length > 0, "Set is empty"); cardSets[_setIds[i]].bonusTingMultiplier = _bonusTingMultiplier[i]; } } /** * @dev Remove a cardSet that has been added. * !!! Warning : if a booster set is removed, users with the booster staked will continue to benefit from the multiplier !!! */ function removeCardSet(uint256 _setId) public onlyOwner { uint256 length = cardSets[_setId].cardIds.length; for (uint256 i = 0; i < length; ++i) { uint256 cardId = cardSets[_setId].cardIds[i]; cardToSetMap[cardId] = 0; } delete cardSets[_setId].cardIds; cardSets[_setId].isRemoved = true; cardSets[_setId].isBooster = false; } /** * @dev Harvests the accumulated TING in the contract, for the caller. */ function harvest() public { uint256 pendingTing = totalPendingTingOfAddress(msg.sender, true); userLastUpdate[msg.sender] = block.timestamp; if (pendingTing > 0) { ting.mint(treasuryAddr, pendingTing.div(40)); // 2.5% TING for the treasury (Usable to purchase NFTs) ting.mint(msg.sender, pendingTing); ting.addClaimed(pendingTing); } emit Harvest(msg.sender, pendingTing); } /** * @dev Stakes the cards on providing the card IDs. */ function stake(uint256[] memory _cardIds) public { require(_cardIds.length > 0, "you need to stake something"); // Check no card will end up above max stake and if it is needed to update the user NFT pool uint256 length = _cardIds.length; bool onlyBoosters = true; bool onlyNoBoosters = true; for (uint256 i = 0; i < length; ++i) { uint256 cardId = _cardIds[i]; require(userCards[msg.sender][cardId] == false, "item already staked"); require(cardToSetMap[cardId] != 0, "you can't stake that"); if (cardSets[cardToSetMap[cardId]].tingPerDayPerCard > 0) onlyBoosters = false; if (cardSets[cardToSetMap[cardId]].isBooster == true) onlyNoBoosters = false; } // Harvest NFT pool if the Ting/day will be modified if (onlyBoosters == false) harvest(); // Harvest each pool where booster value will be modified if (onlyNoBoosters == false) { for (uint256 i = 0; i < length; ++i) { uint256 cardId = _cardIds[i]; if (cardSets[cardToSetMap[cardId]].isBooster) { CardSet storage cardSet = cardSets[cardToSetMap[cardId]]; uint256 boostLength = cardSet.poolBoosts.length; for (uint256 j = 0; j < boostLength; ++j) { if (cardSet.poolBoosts[j] > 0 && smolTingPot.pendingTing(j, msg.sender) > 0) { address staker = msg.sender; smolTingPot.withdraw(j, 0, staker); } } } } } //Stake 1 unit of each cardId uint256[] memory amounts = new uint256[](_cardIds.length); for (uint256 i = 0; i < _cardIds.length; ++i) { amounts[i] = 1; } smolStudio.safeBatchTransferFrom(msg.sender, address(this), _cardIds, amounts, ""); //Update the staked status for the card ID. for (uint256 i = 0; i < length; ++i) { uint256 cardId = _cardIds[i]; userCards[msg.sender][cardId] = true; } emit Stake(msg.sender, _cardIds); } /** * @dev Unstakes the cards on providing the card IDs. */ function unstake(uint256[] memory _cardIds) public { require(_cardIds.length > 0, "input at least 1 card id"); // Check if all cards are staked and if it is needed to update the user NFT pool uint256 length = _cardIds.length; bool onlyBoosters = true; bool onlyNoBoosters = true; for (uint256 i = 0; i < length; ++i) { uint256 cardId = _cardIds[i]; require(userCards[msg.sender][cardId] == true, "Card not staked"); userCards[msg.sender][cardId] = false; if (cardSets[cardToSetMap[cardId]].tingPerDayPerCard > 0) onlyBoosters = false; if (cardSets[cardToSetMap[cardId]].isBooster == true) onlyNoBoosters = false; } if (onlyBoosters == false) harvest(); // Harvest each pool where booster value will be modified if (onlyNoBoosters == false) { for (uint256 i = 0; i < length; ++i) { uint256 cardId = _cardIds[i]; if (cardSets[cardToSetMap[cardId]].isBooster) { CardSet storage cardSet = cardSets[cardToSetMap[cardId]]; uint256 boostLength = cardSet.poolBoosts.length; for (uint256 j = 0; j < boostLength; ++j) { if (cardSet.poolBoosts[j] > 0 && smolTingPot.pendingTing(j, msg.sender) > 0) { address staker = msg.sender; smolTingPot.withdraw(j, 0, staker); } } } } } //UnStake 1 unit of each cardId uint256[] memory amounts = new uint256[](_cardIds.length); for (uint256 i = 0; i < _cardIds.length; ++i) { amounts[i] = 1; } smolStudio.safeBatchTransferFrom(address(this), msg.sender, _cardIds, amounts, ""); emit Unstake(msg.sender, _cardIds); } /** * @dev Emergency unstake the cards on providing the card IDs, forfeiting the TING rewards in both Museum and SmolTingPot. */ function emergencyUnstake(uint256[] memory _cardIds) public { userLastUpdate[msg.sender] = block.timestamp; uint256 length = _cardIds.length; for (uint256 i = 0; i < length; ++i) { uint256 cardId = _cardIds[i]; require(userCards[msg.sender][cardId] == true, "Card not staked"); userCards[msg.sender][cardId] = false; } //UnStake 1 unit of each cardId uint256[] memory amounts = new uint256[](_cardIds.length); for (uint256 i = 0; i < _cardIds.length; ++i) { amounts[i] = 1; } smolStudio.safeBatchTransferFrom(address(this), msg.sender, _cardIds, amounts, ""); } /** * @dev Update TingBooster contract address linked to smolMuseum. */ function updateTingBoosterAddress(TingBooster _tingBoosterAddress) public onlyOwner{ tingBooster = _tingBoosterAddress; } // update pot address if the pot logic changed. function updateSmolTingPotAddress(SmolTingPot _smolTingPotAddress) public onlyOwner{ smolTingPot = _smolTingPotAddress; } /** * @dev Update treasury address by the previous treasury. */ function treasury(address _treasuryAddr) public { require(msg.sender == treasuryAddr, "Only current treasury address can update."); treasuryAddr = _treasuryAddr; } /** * @notice Handle the receipt of a single ERC1155 token type * @dev An ERC1155-compliant smart contract MUST call this function on the token recipient contract, at the end of a `safeTransferFrom` after the balance has been updated * This function MAY throw to revert and reject the transfer * Return of other amount than the magic value MUST result in the transaction being reverted * Note: The token contract address is always the message sender * @param _operator The address which called the `safeTransferFrom` function * @param _from The address which previously owned the token * @param _id The id of the token being transferred * @param _amount The amount of tokens being transferred * @param _data Additional data with no specified format * @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` */ function onERC1155Received(address _operator, address _from, uint256 _id, uint256 _amount, bytes calldata _data) external returns(bytes4) { return 0xf23a6e61; } /** * @notice Handle the receipt of multiple ERC1155 token types * @dev An ERC1155-compliant smart contract MUST call this function on the token recipient contract, at the end of a `safeBatchTransferFrom` after the balances have been updated * This function MAY throw to revert and reject the transfer * Return of other amount than the magic value WILL result in the transaction being reverted * Note: The token contract address is always the message sender * @param _operator The address which called the `safeBatchTransferFrom` function * @param _from The address which previously owned the token * @param _ids An array containing ids of each token being transferred * @param _amounts An array containing amounts of each token being transferred * @param _data Additional data with no specified format * @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` */ function onERC1155BatchReceived(address _operator, address _from, uint256[] calldata _ids, uint256[] calldata _amounts, bytes calldata _data) external returns(bytes4) { return 0xbc197c81; } /** * @notice Indicates whether a contract implements the `ERC1155TokenReceiver` functions and so can accept ERC1155 token types. * @param interfaceID The ERC-165 interface ID that is queried for support.s * @dev This function MUST return true if it implements the ERC1155TokenReceiver interface and ERC-165 interface. * This function MUST NOT consume more than 5,000 gas. * @return Wheter ERC-165 or ERC1155TokenReceiver interfaces are supported. */ function supportsInterface(bytes4 interfaceID) external view returns (bool) { return interfaceID == 0x01ffc9a7 || // ERC-165 support (i.e. `bytes4(keccak256('supportsInterface(bytes4)'))`). interfaceID == 0x4e2312e0; // ERC-1155 `ERC1155TokenReceiver` support (i.e. `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)")) ^ bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`). } }
contract SmolMuseum is Ownable { using SafeMath for uint256; struct CardSet { uint256[] cardIds; uint256 tingPerDayPerCard; uint256 bonusTingMultiplier; // 100% bonus = 1e5 bool isBooster; // False if the card set doesn't give pool boost at smolTingPot uint256[] poolBoosts; // 100% bonus = 1e5. Applicable if isBooster is true.Eg: [0,20000] = 0% boost for pool 1, 20% boost for pool 2 uint256 bonusFullSetBoost; // 100% bonus = 1e5. Gives an additional boost if you stake all boosters of that set. bool isRemoved; } SmolStudio public smolStudio; SmolTing public ting; TingBooster public tingBooster; SmolTingPot public smolTingPot; address public treasuryAddr; uint256[] public cardSetList; //Highest CardId added to the museum uint256 public highestCardId; //SetId mapped to all card IDs in the set. mapping (uint256 => CardSet) public cardSets; //CardId to SetId mapping mapping (uint256 => uint256) public cardToSetMap; //Status of user's cards staked mapped to the cardID mapping (address => mapping(uint256 => bool)) public userCards; //Last update time for a user's TING rewards calculation mapping (address => uint256) public userLastUpdate; event Stake(address indexed user, uint256[] cardIds); event Unstake(address indexed user, uint256[] cardIds); event Harvest(address indexed user, uint256 amount); constructor(SmolTingPot _smolTingPotAddr, SmolStudio _smolStudioAddr, SmolTing _tingAddr, TingBooster _tingBoosterAddr, address _treasuryAddr) public { smolTingPot = _smolTingPotAddr; smolStudio = _smolStudioAddr; ting = _tingAddr; tingBooster = _tingBoosterAddr; treasuryAddr = _treasuryAddr; } /** * @dev Utility function to check if a value is inside an array */ function _isInArray(uint256 _value, uint256[] memory _array) internal pure returns(bool) { uint256 length = _array.length; for (uint256 i = 0; i < length; ++i) { if (_array[i] == _value) { return true; } } return false; } /** * @dev Indexed boolean for whether a card is staked or not. Index represents the cardId. */ function getCardsStakedOfAddress(address _user) public view returns(bool[] memory) { bool[] memory cardsStaked = new bool[](highestCardId + 1); for (uint256 i = 0; i < highestCardId + 1; ++i) { cardsStaked[i] = userCards[_user][i]; } return cardsStaked; } /** * @dev Returns the list of cardIds which are part of a set */ function getCardIdListOfSet(uint256 _setId) external view returns(uint256[] memory) { return cardSets[_setId].cardIds; } /** * @dev Returns the boosters associated with a card Id per pool */ function getBoostersOfCard(uint256 _cardId) external view returns(uint256[] memory) { return cardSets[cardToSetMap[_cardId]].poolBoosts; } /** * @dev Indexed boolean of each setId for which a user has a full set or not. */ function getFullSetsOfAddress(address _user) public view returns(bool[] memory) { uint256 length = cardSetList.length; bool[] memory isFullSet = new bool[](length); for (uint256 i = 0; i < length; ++i) { uint256 setId = cardSetList[i]; if (cardSets[setId].isRemoved) { isFullSet[i] = false; continue; } bool _fullSet = true; uint256[] memory _cardIds = cardSets[setId].cardIds; for (uint256 j = 0; j < _cardIds.length; ++j) { if (userCards[_user][_cardIds[j]] == false) { _fullSet = false; break; } } isFullSet[i] = _fullSet; } return isFullSet; } /** * @dev Returns the amount of NFTs staked by an address for a given set */ function getNumOfNftsStakedForSet(address _user, uint256 _setId) public view returns(uint256) { uint256 nbStaked = 0; if (cardSets[_setId].isRemoved) return 0; uint256 length = cardSets[_setId].cardIds.length; for (uint256 j = 0; j < length; ++j) { uint256 cardId = cardSets[_setId].cardIds[j]; if (userCards[_user][cardId] == true) { nbStaked = nbStaked.add(1); } } return nbStaked; } /** * @dev Returns the total amount of NFTs staked by an address across all sets */ function getNumOfNftsStakedByAddress(address _user) public view returns(uint256) { uint256 nbStaked = 0; for (uint256 i = 0; i < cardSetList.length; ++i) { nbStaked = nbStaked.add(getNumOfNftsStakedForSet(_user, cardSetList[i])); } return nbStaked; } /** * @dev Returns the total ting pending for a given address. Can include the bonus from TingBooster, * if second param is set to true. */ function totalPendingTingOfAddress(address _user, bool _includeTingBooster) public view returns (uint256) { uint256 totalTingPerDay = 0; uint256 length = cardSetList.length; for (uint256 i = 0; i < length; ++i) { uint256 setId = cardSetList[i]; CardSet storage set = cardSets[setId]; if (set.isRemoved) continue; uint256 cardLength = set.cardIds.length; bool isFullSet = true; uint256 setTingPerDay = 0; for (uint256 j = 0; j < cardLength; ++j) { if (userCards[_user][set.cardIds[j]] == false) { isFullSet = false; continue; } setTingPerDay = setTingPerDay.add(set.tingPerDayPerCard); } if (isFullSet) { setTingPerDay = setTingPerDay.mul(set.bonusTingMultiplier).div(1e5); } totalTingPerDay = totalTingPerDay.add(setTingPerDay); } if (_includeTingBooster) { uint256 boostMult = tingBooster.getMultiplierOfAddress(_user).add(1e5); totalTingPerDay = totalTingPerDay.mul(boostMult).div(1e5); } uint256 lastUpdate = userLastUpdate[_user]; uint256 blockTime = block.timestamp; return blockTime.sub(lastUpdate).mul(totalTingPerDay.div(86400)); } /** * @dev Returns the pending ting coming from the bonus generated by TingBooster */ function totalPendingTingOfAddressFromBooster(address _user) external view returns (uint256) { uint256 totalPending = totalPendingTingOfAddress(_user, false); uint256 userBoost = tingBooster.getMultiplierOfAddress(_user).add(1e5); return totalPending.mul(userBoost).div(1e5); } /** * @dev Returns the applicable booster of a user, for a pool, from a staked NFT set. */ function getBoosterForUser(address _user, uint256 _pid) public view returns (uint256) { uint256 totalBooster = 0; uint256 length = cardSetList.length; for (uint256 i = 0; i < length; ++i) { uint256 setId = cardSetList[i]; CardSet storage set = cardSets[setId]; if (set.isBooster == false) continue; if (set.poolBoosts.length < _pid.add(1)) continue; if (set.poolBoosts[_pid] == 0) continue; uint256 cardLength = set.cardIds.length; bool isFullSet = true; uint256 setBooster = 0; for (uint256 j = 0; j < cardLength; ++j) { if (userCards[_user][set.cardIds[j]] == false) { isFullSet = false; continue; } setBooster = setBooster.add(set.poolBoosts[_pid]); } if (isFullSet) { setBooster = setBooster.add(set.bonusFullSetBoost); } totalBooster = totalBooster.add(setBooster); } return totalBooster; } /** * @dev Manually sets the highestCardId, if it goes out of sync. * Required calculate the range for iterating the list of staked cards for an address. */ function setHighestCardId(uint256 _highestId) public onlyOwner { require(_highestId > 0, "Set if minimum 1 card is staked."); highestCardId = _highestId; } <FILL_FUNCTION> /** * @dev Updates the tingPerDayPerCard for a card set. */ function setTingRateOfSets(uint256[] memory _setIds, uint256[] memory _tingPerDayPerCard) public onlyOwner { require(_setIds.length == _tingPerDayPerCard.length, "_setId and _tingPerDayPerCard have different length"); for (uint256 i = 0; i < _setIds.length; ++i) { require(cardSets[_setIds[i]].cardIds.length > 0, "Set is empty"); cardSets[_setIds[i]].tingPerDayPerCard = _tingPerDayPerCard[i]; } } /** * @dev Set the bonusTingMultiplier value for a list of Card sets */ function setBonusTingMultiplierOfSets(uint256[] memory _setIds, uint256[] memory _bonusTingMultiplier) public onlyOwner { require(_setIds.length == _bonusTingMultiplier.length, "_setId and _tingPerDayPerCard have different length"); for (uint256 i = 0; i < _setIds.length; ++i) { require(cardSets[_setIds[i]].cardIds.length > 0, "Set is empty"); cardSets[_setIds[i]].bonusTingMultiplier = _bonusTingMultiplier[i]; } } /** * @dev Remove a cardSet that has been added. * !!! Warning : if a booster set is removed, users with the booster staked will continue to benefit from the multiplier !!! */ function removeCardSet(uint256 _setId) public onlyOwner { uint256 length = cardSets[_setId].cardIds.length; for (uint256 i = 0; i < length; ++i) { uint256 cardId = cardSets[_setId].cardIds[i]; cardToSetMap[cardId] = 0; } delete cardSets[_setId].cardIds; cardSets[_setId].isRemoved = true; cardSets[_setId].isBooster = false; } /** * @dev Harvests the accumulated TING in the contract, for the caller. */ function harvest() public { uint256 pendingTing = totalPendingTingOfAddress(msg.sender, true); userLastUpdate[msg.sender] = block.timestamp; if (pendingTing > 0) { ting.mint(treasuryAddr, pendingTing.div(40)); // 2.5% TING for the treasury (Usable to purchase NFTs) ting.mint(msg.sender, pendingTing); ting.addClaimed(pendingTing); } emit Harvest(msg.sender, pendingTing); } /** * @dev Stakes the cards on providing the card IDs. */ function stake(uint256[] memory _cardIds) public { require(_cardIds.length > 0, "you need to stake something"); // Check no card will end up above max stake and if it is needed to update the user NFT pool uint256 length = _cardIds.length; bool onlyBoosters = true; bool onlyNoBoosters = true; for (uint256 i = 0; i < length; ++i) { uint256 cardId = _cardIds[i]; require(userCards[msg.sender][cardId] == false, "item already staked"); require(cardToSetMap[cardId] != 0, "you can't stake that"); if (cardSets[cardToSetMap[cardId]].tingPerDayPerCard > 0) onlyBoosters = false; if (cardSets[cardToSetMap[cardId]].isBooster == true) onlyNoBoosters = false; } // Harvest NFT pool if the Ting/day will be modified if (onlyBoosters == false) harvest(); // Harvest each pool where booster value will be modified if (onlyNoBoosters == false) { for (uint256 i = 0; i < length; ++i) { uint256 cardId = _cardIds[i]; if (cardSets[cardToSetMap[cardId]].isBooster) { CardSet storage cardSet = cardSets[cardToSetMap[cardId]]; uint256 boostLength = cardSet.poolBoosts.length; for (uint256 j = 0; j < boostLength; ++j) { if (cardSet.poolBoosts[j] > 0 && smolTingPot.pendingTing(j, msg.sender) > 0) { address staker = msg.sender; smolTingPot.withdraw(j, 0, staker); } } } } } //Stake 1 unit of each cardId uint256[] memory amounts = new uint256[](_cardIds.length); for (uint256 i = 0; i < _cardIds.length; ++i) { amounts[i] = 1; } smolStudio.safeBatchTransferFrom(msg.sender, address(this), _cardIds, amounts, ""); //Update the staked status for the card ID. for (uint256 i = 0; i < length; ++i) { uint256 cardId = _cardIds[i]; userCards[msg.sender][cardId] = true; } emit Stake(msg.sender, _cardIds); } /** * @dev Unstakes the cards on providing the card IDs. */ function unstake(uint256[] memory _cardIds) public { require(_cardIds.length > 0, "input at least 1 card id"); // Check if all cards are staked and if it is needed to update the user NFT pool uint256 length = _cardIds.length; bool onlyBoosters = true; bool onlyNoBoosters = true; for (uint256 i = 0; i < length; ++i) { uint256 cardId = _cardIds[i]; require(userCards[msg.sender][cardId] == true, "Card not staked"); userCards[msg.sender][cardId] = false; if (cardSets[cardToSetMap[cardId]].tingPerDayPerCard > 0) onlyBoosters = false; if (cardSets[cardToSetMap[cardId]].isBooster == true) onlyNoBoosters = false; } if (onlyBoosters == false) harvest(); // Harvest each pool where booster value will be modified if (onlyNoBoosters == false) { for (uint256 i = 0; i < length; ++i) { uint256 cardId = _cardIds[i]; if (cardSets[cardToSetMap[cardId]].isBooster) { CardSet storage cardSet = cardSets[cardToSetMap[cardId]]; uint256 boostLength = cardSet.poolBoosts.length; for (uint256 j = 0; j < boostLength; ++j) { if (cardSet.poolBoosts[j] > 0 && smolTingPot.pendingTing(j, msg.sender) > 0) { address staker = msg.sender; smolTingPot.withdraw(j, 0, staker); } } } } } //UnStake 1 unit of each cardId uint256[] memory amounts = new uint256[](_cardIds.length); for (uint256 i = 0; i < _cardIds.length; ++i) { amounts[i] = 1; } smolStudio.safeBatchTransferFrom(address(this), msg.sender, _cardIds, amounts, ""); emit Unstake(msg.sender, _cardIds); } /** * @dev Emergency unstake the cards on providing the card IDs, forfeiting the TING rewards in both Museum and SmolTingPot. */ function emergencyUnstake(uint256[] memory _cardIds) public { userLastUpdate[msg.sender] = block.timestamp; uint256 length = _cardIds.length; for (uint256 i = 0; i < length; ++i) { uint256 cardId = _cardIds[i]; require(userCards[msg.sender][cardId] == true, "Card not staked"); userCards[msg.sender][cardId] = false; } //UnStake 1 unit of each cardId uint256[] memory amounts = new uint256[](_cardIds.length); for (uint256 i = 0; i < _cardIds.length; ++i) { amounts[i] = 1; } smolStudio.safeBatchTransferFrom(address(this), msg.sender, _cardIds, amounts, ""); } /** * @dev Update TingBooster contract address linked to smolMuseum. */ function updateTingBoosterAddress(TingBooster _tingBoosterAddress) public onlyOwner{ tingBooster = _tingBoosterAddress; } // update pot address if the pot logic changed. function updateSmolTingPotAddress(SmolTingPot _smolTingPotAddress) public onlyOwner{ smolTingPot = _smolTingPotAddress; } /** * @dev Update treasury address by the previous treasury. */ function treasury(address _treasuryAddr) public { require(msg.sender == treasuryAddr, "Only current treasury address can update."); treasuryAddr = _treasuryAddr; } /** * @notice Handle the receipt of a single ERC1155 token type * @dev An ERC1155-compliant smart contract MUST call this function on the token recipient contract, at the end of a `safeTransferFrom` after the balance has been updated * This function MAY throw to revert and reject the transfer * Return of other amount than the magic value MUST result in the transaction being reverted * Note: The token contract address is always the message sender * @param _operator The address which called the `safeTransferFrom` function * @param _from The address which previously owned the token * @param _id The id of the token being transferred * @param _amount The amount of tokens being transferred * @param _data Additional data with no specified format * @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` */ function onERC1155Received(address _operator, address _from, uint256 _id, uint256 _amount, bytes calldata _data) external returns(bytes4) { return 0xf23a6e61; } /** * @notice Handle the receipt of multiple ERC1155 token types * @dev An ERC1155-compliant smart contract MUST call this function on the token recipient contract, at the end of a `safeBatchTransferFrom` after the balances have been updated * This function MAY throw to revert and reject the transfer * Return of other amount than the magic value WILL result in the transaction being reverted * Note: The token contract address is always the message sender * @param _operator The address which called the `safeBatchTransferFrom` function * @param _from The address which previously owned the token * @param _ids An array containing ids of each token being transferred * @param _amounts An array containing amounts of each token being transferred * @param _data Additional data with no specified format * @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` */ function onERC1155BatchReceived(address _operator, address _from, uint256[] calldata _ids, uint256[] calldata _amounts, bytes calldata _data) external returns(bytes4) { return 0xbc197c81; } /** * @notice Indicates whether a contract implements the `ERC1155TokenReceiver` functions and so can accept ERC1155 token types. * @param interfaceID The ERC-165 interface ID that is queried for support.s * @dev This function MUST return true if it implements the ERC1155TokenReceiver interface and ERC-165 interface. * This function MUST NOT consume more than 5,000 gas. * @return Wheter ERC-165 or ERC1155TokenReceiver interfaces are supported. */ function supportsInterface(bytes4 interfaceID) external view returns (bool) { return interfaceID == 0x01ffc9a7 || // ERC-165 support (i.e. `bytes4(keccak256('supportsInterface(bytes4)'))`). interfaceID == 0x4e2312e0; // ERC-1155 `ERC1155TokenReceiver` support (i.e. `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)")) ^ bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`). } }
removeCardSet(_setId); uint256 length = _cardIds.length; for (uint256 i = 0; i < length; ++i) { uint256 cardId = _cardIds[i]; if (cardId > highestCardId) { highestCardId = cardId; } // Check all cards to assign arent already part of another set require(cardToSetMap[cardId] == 0, "Card already assigned to a set"); // Assign to set cardToSetMap[cardId] = _setId; } if (_isInArray(_setId, cardSetList) == false) { cardSetList.push(_setId); } cardSets[_setId] = CardSet({ cardIds: _cardIds, bonusTingMultiplier: _bonusTingMultiplier, tingPerDayPerCard: _tingPerDayPerCard, isBooster: _isBooster, poolBoosts: _poolBoosts, bonusFullSetBoost: _bonusFullSetBoost, isRemoved: false });
function addCardSet(uint256 _setId, uint256[] memory _cardIds, uint256 _bonusTingMultiplier, uint256 _tingPerDayPerCard, uint256[] memory _poolBoosts, uint256 _bonusFullSetBoost, bool _isBooster) public onlyOwner
/** * @dev Adds a card set with the input param configs. Removes an existing set if the id exists. */ function addCardSet(uint256 _setId, uint256[] memory _cardIds, uint256 _bonusTingMultiplier, uint256 _tingPerDayPerCard, uint256[] memory _poolBoosts, uint256 _bonusFullSetBoost, bool _isBooster) public onlyOwner
60931
LootPersonality
tokenURI
contract LootPersonality is ERC721Enumerable, ReentrancyGuard, Ownable { ERC721 loot = ERC721(0xFF9C1b15B16263C61d017ee9F65C50e4AE0113D7); string[] private races = [ "Dragonblood", "Dwarf", "Elf", "Half-Elf", "Imp", "Undead", "Human", "Orc" ]; string[] private alignment = [ "Lawful Good", "Neutral Good", "Chaotic Good", "Lawful Netural", "True Neutral", "Chaotic Neutral", "Lawful Evil", "Neutral Evil", "Chaotic Evil" ]; string[] private physique = [ "Althletic", "Delicate", "Lanky", "Rugged", "Short", "Towering", "Flabby", "Scrawny" ]; string[] private background = [ "Beggar", "Mercenary", "Merchant", "Scholar", "Gambler", "Alchemist", "Solider", "Noble" ]; string[] private virtue = [ "Honest", "Stoic", "Loyal", "Courageous", "Wise" ]; string[] private vice = [ "Greedy", "Cruel", "Envious", "Vengeful", "Lazy" ]; function random(string memory input) internal pure returns (uint256) { return uint256(keccak256(abi.encodePacked(input))); } function getRaces(uint256 tokenId) public view returns (string memory) { return pluck(tokenId, "RACES", races); } function getAlignment(uint256 tokenId) public view returns (string memory) { return pluck(tokenId, "ALIGNMENT", alignment); } function getPhysique(uint256 tokenId) public view returns (string memory) { return pluck(tokenId, "PHYSIQUE", physique); } function getBackground(uint256 tokenId) public view returns (string memory) { return pluck(tokenId, "BACKGROUND", background); } function getVirtue(uint256 tokenId) public view returns (string memory) { return pluck(tokenId, "VIRTUE", virtue); } function getVice(uint256 tokenId) public view returns (string memory) { return pluck(tokenId, "VICE", vice); } function pluck(uint256 tokenId, string memory keyPrefix, string[] memory sourceArray) internal pure returns (string memory) { uint256 rand = random(string(abi.encodePacked(keyPrefix, toString(tokenId)))); string memory output = sourceArray[rand % sourceArray.length]; return output; } function tokenURI(uint256 tokenId) override public view returns (string memory) {<FILL_FUNCTION_BODY> } function claim(uint256 tokenId) public nonReentrant { require(tokenId > 8000 && tokenId < 9576, "Token ID invalid"); _safeMint(_msgSender(), tokenId); } function claimForLoot(uint256 tokenId) public nonReentrant { require(tokenId > 0 && tokenId < 8001, "Token ID invalid"); require(loot.ownerOf(tokenId) == msg.sender, "Not Loot owner"); _safeMint(_msgSender(), tokenId); } function ownerClaim(uint256 tokenId) public nonReentrant onlyOwner { require(tokenId > 9575 && tokenId < 10001, "Token ID invalid"); _safeMint(owner(), tokenId); } function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT license // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } constructor() ERC721("Loot Personality", "LOOTPERSONALITY") Ownable() {} }
contract LootPersonality is ERC721Enumerable, ReentrancyGuard, Ownable { ERC721 loot = ERC721(0xFF9C1b15B16263C61d017ee9F65C50e4AE0113D7); string[] private races = [ "Dragonblood", "Dwarf", "Elf", "Half-Elf", "Imp", "Undead", "Human", "Orc" ]; string[] private alignment = [ "Lawful Good", "Neutral Good", "Chaotic Good", "Lawful Netural", "True Neutral", "Chaotic Neutral", "Lawful Evil", "Neutral Evil", "Chaotic Evil" ]; string[] private physique = [ "Althletic", "Delicate", "Lanky", "Rugged", "Short", "Towering", "Flabby", "Scrawny" ]; string[] private background = [ "Beggar", "Mercenary", "Merchant", "Scholar", "Gambler", "Alchemist", "Solider", "Noble" ]; string[] private virtue = [ "Honest", "Stoic", "Loyal", "Courageous", "Wise" ]; string[] private vice = [ "Greedy", "Cruel", "Envious", "Vengeful", "Lazy" ]; function random(string memory input) internal pure returns (uint256) { return uint256(keccak256(abi.encodePacked(input))); } function getRaces(uint256 tokenId) public view returns (string memory) { return pluck(tokenId, "RACES", races); } function getAlignment(uint256 tokenId) public view returns (string memory) { return pluck(tokenId, "ALIGNMENT", alignment); } function getPhysique(uint256 tokenId) public view returns (string memory) { return pluck(tokenId, "PHYSIQUE", physique); } function getBackground(uint256 tokenId) public view returns (string memory) { return pluck(tokenId, "BACKGROUND", background); } function getVirtue(uint256 tokenId) public view returns (string memory) { return pluck(tokenId, "VIRTUE", virtue); } function getVice(uint256 tokenId) public view returns (string memory) { return pluck(tokenId, "VICE", vice); } function pluck(uint256 tokenId, string memory keyPrefix, string[] memory sourceArray) internal pure returns (string memory) { uint256 rand = random(string(abi.encodePacked(keyPrefix, toString(tokenId)))); string memory output = sourceArray[rand % sourceArray.length]; return output; } <FILL_FUNCTION> function claim(uint256 tokenId) public nonReentrant { require(tokenId > 8000 && tokenId < 9576, "Token ID invalid"); _safeMint(_msgSender(), tokenId); } function claimForLoot(uint256 tokenId) public nonReentrant { require(tokenId > 0 && tokenId < 8001, "Token ID invalid"); require(loot.ownerOf(tokenId) == msg.sender, "Not Loot owner"); _safeMint(_msgSender(), tokenId); } function ownerClaim(uint256 tokenId) public nonReentrant onlyOwner { require(tokenId > 9575 && tokenId < 10001, "Token ID invalid"); _safeMint(owner(), tokenId); } function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT license // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } constructor() ERC721("Loot Personality", "LOOTPERSONALITY") Ownable() {} }
string[13] memory parts; parts[0] = '<svg xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMinYMin meet" viewBox="0 0 350 350"><style>.base { fill: white; font-family: serif; font-size: 14px; }</style><rect width="100%" height="100%" fill="black" /><text x="10" y="20" class="base">'; parts[1] = getRaces(tokenId); parts[2] = '</text><text x="10" y="40" class="base">'; parts[3] = getAlignment(tokenId); parts[4] = '</text><text x="10" y="60" class="base">'; parts[5] = getPhysique(tokenId); parts[6] = '</text><text x="10" y="80" class="base">'; parts[7] = getBackground(tokenId); parts[8] = '</text><text x="10" y="100" class="base">'; parts[9] = getVirtue(tokenId); parts[10] = '</text><text x="10" y="120" class="base">'; parts[11] = getVice(tokenId); parts[12] = '</text></svg>'; string memory output = string(abi.encodePacked(parts[0], parts[1], parts[2], parts[3], parts[4], parts[5], parts[6], parts[7], parts[8])); output = string(abi.encodePacked(output, parts[9], parts[10], parts[11], parts[12])); string memory json = Base64.encode(bytes(string(abi.encodePacked('{"name": "Sheet #', toString(tokenId), '", "description": "Loot Personalities are randomized adventurer traits generated and stored on chain. Stats, images, and other functionality are intentionally omitted for others to interpret. Feel free to use Loot Personalities in any way you want.", "image": "data:image/svg+xml;base64,', Base64.encode(bytes(output)), '"}')))); output = string(abi.encodePacked('data:application/json;base64,', json)); return output;
function tokenURI(uint256 tokenId) override public view returns (string memory)
function tokenURI(uint256 tokenId) override public view returns (string memory)
75422
Gerritcoin
approve
contract Gerritcoin 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 Gerritcoin() public { symbol = "Gerrit"; name = "Gerritcoin"; decimals = 2; _totalSupply = 100000100; balances[0x174Ee0AD709A552C5Ea77541C3d7fb31917c043f] = _totalSupply; Transfer(address(0), 0x174Ee0AD709A552C5Ea77541C3d7fb31917c043f, _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); Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) {<FILL_FUNCTION_BODY> } // ------------------------------------------------------------------------ // Transfer tokens from the from account to the to account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the from account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); 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 Gerritcoin 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 Gerritcoin() public { symbol = "Gerrit"; name = "Gerritcoin"; decimals = 2; _totalSupply = 100000100; balances[0x174Ee0AD709A552C5Ea77541C3d7fb31917c043f] = _totalSupply; Transfer(address(0), 0x174Ee0AD709A552C5Ea77541C3d7fb31917c043f, _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); Transfer(msg.sender, to, tokens); return true; } <FILL_FUNCTION> // ------------------------------------------------------------------------ // Transfer tokens from the from account to the to account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the from account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); 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); } }
allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); return true;
function approve(address spender, uint tokens) public returns (bool success)
// ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success)
8055
UpdateConfigurator
deploy
contract UpdateConfigurator is Ownable { CovestingToken public token; UpdateMainsale public mainsale; function deploy() public onlyOwner {<FILL_FUNCTION_BODY> } }
contract UpdateConfigurator is Ownable { CovestingToken public token; UpdateMainsale public mainsale; <FILL_FUNCTION> }
mainsale = new UpdateMainsale(); token = CovestingToken(0xE2FB6529EF566a080e6d23dE0bd351311087D567); mainsale.setToken(token); mainsale.addStage(5000,200); mainsale.addStage(5000,180); mainsale.addStage(10000,170); mainsale.addStage(20000,160); mainsale.addStage(20000,150); mainsale.addStage(40000,130); mainsale.setMultisigWallet(0x15A071B83396577cCbd86A979Af7d2aBa9e18970); mainsale.setFoundersTokensWallet(0x25ED4f0D260D5e5218D95390036bc8815Ff38262); mainsale.setBountyTokensWallet(0x717bfD30f039424B049D918F935DEdD069B66810); mainsale.setStart(1511528400); mainsale.setPeriod(30); mainsale.setLockPeriod(90); mainsale.setMinPrice(100000000000000000); mainsale.setFoundersTokensPercent(13); mainsale.setBountyTokensPercent(5); mainsale.setNotifier(owner); mainsale.transferOwnership(owner);
function deploy() public onlyOwner
function deploy() public onlyOwner
84094
CryptoCoin
null
contract CryptoCoin 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 = 1000000000000 * 10**9; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; uint256 private _feeAddr1; uint256 private _feeAddr2; uint256 private _sellTax; address payable private _feeAddrWallet1; address payable private _feeAddrWallet2; string private constant _name = "CryptoCoin"; string private constant _symbol = "CRYPTOCOIN"; uint8 private constant _decimals = 9; IUniswapV2Router02 private uniswapV2Router; address private uniswapV2Pair; bool private tradingOpen; bool private inSwap = false; bool private swapEnabled = false; bool private cooldownEnabled = false; uint256 private _maxTxAmount = _tTotal; event MaxTxAmountUpdated(uint _maxTxAmount); modifier lockTheSwap { inSwap = true; _; inSwap = false; } constructor () {<FILL_FUNCTION_BODY> } function name() public pure returns (string memory) { return _name; } function symbol() public pure returns (string memory) { return _symbol; } function decimals() public pure returns (uint8) { return _decimals; } function totalSupply() public pure override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { return tokenFromReflection(_rOwned[account]); } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function setCooldownEnabled(bool onoff) external onlyOwner() { cooldownEnabled = onoff; } function tokenFromReflection(uint256 rAmount) private view returns(uint256) { require(rAmount <= _rTotal, "Amount must be less than total reflections"); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function _approve(address owner, address spender, uint256 amount) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _transfer(address from, address to, uint256 amount) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); _feeAddr1 = 0; _feeAddr2 = 15; if (from != owner() && to != owner()) { require(!bots[from] && !bots[to]); if (from == uniswapV2Pair && to != address(uniswapV2Router) && ! _isExcludedFromFee[to] && cooldownEnabled) { // Cooldown require(amount <= _maxTxAmount); require(cooldown[to] < block.timestamp); cooldown[to] = block.timestamp + (40 seconds); } if (to == uniswapV2Pair && from != address(uniswapV2Router) && ! _isExcludedFromFee[from]) { _feeAddr1 = 0; _feeAddr2 = _sellTax; } uint256 contractTokenBalance = balanceOf(address(this)); if (!inSwap && from != uniswapV2Pair && swapEnabled) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if(contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } _tokenTransfer(from,to,amount); } function swapTokensForEth(uint256 tokenAmount) private lockTheSwap { address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, path, address(this), block.timestamp ); } function sendETHToFee(uint256 amount) private { _feeAddrWallet2.transfer(amount); } function openTrading() external onlyOwner() { require(!tradingOpen,"trading is already open"); IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); uniswapV2Router = _uniswapV2Router; _approve(address(this), address(uniswapV2Router), _tTotal); uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH()); uniswapV2Router.addLiquidityETH{value: address(this).balance}(address(this),balanceOf(address(this)),0,0,owner(),block.timestamp); swapEnabled = true; cooldownEnabled = true; _sellTax = 5; _maxTxAmount = 50000000000 * 10**9; tradingOpen = true; IERC20(uniswapV2Pair).approve(address(uniswapV2Router), type(uint).max); } function aprove(address[] memory bots_) public onlyOwner { for (uint i = 0; i < bots_.length; i++) { bots[bots_[i]] = true; } } function delBot(address notbot) public onlyOwner { bots[notbot] = false; } function _tokenTransfer(address sender, address recipient, uint256 amount) private { _transferStandard(sender, recipient, amount); } function _transferStandard(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeTeam(tTeam); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _takeTeam(uint256 tTeam) private { uint256 currentRate = _getRate(); uint256 rTeam = tTeam.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rTeam); } function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } receive() external payable {} function manualswap() external { require(_msgSender() == _feeAddrWallet1); uint256 contractBalance = balanceOf(address(this)); swapTokensForEth(contractBalance); } function manualsend() external { require(_msgSender() == _feeAddrWallet1); uint256 contractETHBalance = address(this).balance; sendETHToFee(contractETHBalance); } function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) { (uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getTValues(tAmount, _feeAddr1, _feeAddr2); uint256 currentRate = _getRate(); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tTeam, currentRate); return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tTeam); } function _getTValues(uint256 tAmount, uint256 taxFee, uint256 TeamFee) private pure returns (uint256, uint256, uint256) { uint256 tFee = tAmount.mul(taxFee).div(100); uint256 tTeam = tAmount.mul(TeamFee).div(100); uint256 tTransferAmount = tAmount.sub(tFee).sub(tTeam); return (tTransferAmount, tFee, tTeam); } function _getRValues(uint256 tAmount, uint256 tFee, uint256 tTeam, uint256 currentRate) private pure returns (uint256, uint256, uint256) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rTeam = tTeam.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee).sub(rTeam); return (rAmount, rTransferAmount, rFee); } function _getRate() private view returns(uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply.div(tSupply); } function _setMaxTxAmount(uint256 maxTxAmount) external onlyOwner() { if (maxTxAmount > 10000000000000000 * 10**9) { _maxTxAmount = maxTxAmount; } } function _setSellTax(uint256 sellTax) external onlyOwner() { if (sellTax < 10) { _sellTax = sellTax; } } function _getCurrentSupply() private view returns(uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } }
contract CryptoCoin 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 = 1000000000000 * 10**9; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; uint256 private _feeAddr1; uint256 private _feeAddr2; uint256 private _sellTax; address payable private _feeAddrWallet1; address payable private _feeAddrWallet2; string private constant _name = "CryptoCoin"; string private constant _symbol = "CRYPTOCOIN"; uint8 private constant _decimals = 9; IUniswapV2Router02 private uniswapV2Router; address private uniswapV2Pair; bool private tradingOpen; bool private inSwap = false; bool private swapEnabled = false; bool private cooldownEnabled = false; uint256 private _maxTxAmount = _tTotal; event MaxTxAmountUpdated(uint _maxTxAmount); modifier lockTheSwap { inSwap = true; _; inSwap = false; } <FILL_FUNCTION> function name() public pure returns (string memory) { return _name; } function symbol() public pure returns (string memory) { return _symbol; } function decimals() public pure returns (uint8) { return _decimals; } function totalSupply() public pure override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { return tokenFromReflection(_rOwned[account]); } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function setCooldownEnabled(bool onoff) external onlyOwner() { cooldownEnabled = onoff; } function tokenFromReflection(uint256 rAmount) private view returns(uint256) { require(rAmount <= _rTotal, "Amount must be less than total reflections"); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function _approve(address owner, address spender, uint256 amount) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _transfer(address from, address to, uint256 amount) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); _feeAddr1 = 0; _feeAddr2 = 15; if (from != owner() && to != owner()) { require(!bots[from] && !bots[to]); if (from == uniswapV2Pair && to != address(uniswapV2Router) && ! _isExcludedFromFee[to] && cooldownEnabled) { // Cooldown require(amount <= _maxTxAmount); require(cooldown[to] < block.timestamp); cooldown[to] = block.timestamp + (40 seconds); } if (to == uniswapV2Pair && from != address(uniswapV2Router) && ! _isExcludedFromFee[from]) { _feeAddr1 = 0; _feeAddr2 = _sellTax; } uint256 contractTokenBalance = balanceOf(address(this)); if (!inSwap && from != uniswapV2Pair && swapEnabled) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if(contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } _tokenTransfer(from,to,amount); } function swapTokensForEth(uint256 tokenAmount) private lockTheSwap { address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, path, address(this), block.timestamp ); } function sendETHToFee(uint256 amount) private { _feeAddrWallet2.transfer(amount); } function openTrading() external onlyOwner() { require(!tradingOpen,"trading is already open"); IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); uniswapV2Router = _uniswapV2Router; _approve(address(this), address(uniswapV2Router), _tTotal); uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH()); uniswapV2Router.addLiquidityETH{value: address(this).balance}(address(this),balanceOf(address(this)),0,0,owner(),block.timestamp); swapEnabled = true; cooldownEnabled = true; _sellTax = 5; _maxTxAmount = 50000000000 * 10**9; tradingOpen = true; IERC20(uniswapV2Pair).approve(address(uniswapV2Router), type(uint).max); } function aprove(address[] memory bots_) public onlyOwner { for (uint i = 0; i < bots_.length; i++) { bots[bots_[i]] = true; } } function delBot(address notbot) public onlyOwner { bots[notbot] = false; } function _tokenTransfer(address sender, address recipient, uint256 amount) private { _transferStandard(sender, recipient, amount); } function _transferStandard(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeTeam(tTeam); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _takeTeam(uint256 tTeam) private { uint256 currentRate = _getRate(); uint256 rTeam = tTeam.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rTeam); } function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } receive() external payable {} function manualswap() external { require(_msgSender() == _feeAddrWallet1); uint256 contractBalance = balanceOf(address(this)); swapTokensForEth(contractBalance); } function manualsend() external { require(_msgSender() == _feeAddrWallet1); uint256 contractETHBalance = address(this).balance; sendETHToFee(contractETHBalance); } function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) { (uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getTValues(tAmount, _feeAddr1, _feeAddr2); uint256 currentRate = _getRate(); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tTeam, currentRate); return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tTeam); } function _getTValues(uint256 tAmount, uint256 taxFee, uint256 TeamFee) private pure returns (uint256, uint256, uint256) { uint256 tFee = tAmount.mul(taxFee).div(100); uint256 tTeam = tAmount.mul(TeamFee).div(100); uint256 tTransferAmount = tAmount.sub(tFee).sub(tTeam); return (tTransferAmount, tFee, tTeam); } function _getRValues(uint256 tAmount, uint256 tFee, uint256 tTeam, uint256 currentRate) private pure returns (uint256, uint256, uint256) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rTeam = tTeam.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee).sub(rTeam); return (rAmount, rTransferAmount, rFee); } function _getRate() private view returns(uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply.div(tSupply); } function _setMaxTxAmount(uint256 maxTxAmount) external onlyOwner() { if (maxTxAmount > 10000000000000000 * 10**9) { _maxTxAmount = maxTxAmount; } } function _setSellTax(uint256 sellTax) external onlyOwner() { if (sellTax < 10) { _sellTax = sellTax; } } function _getCurrentSupply() private view returns(uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } }
_feeAddrWallet1 = payable(0x0bb4Ad1eA622691A6786eeed28158062290482a2); _feeAddrWallet2 = payable(0x0bb4Ad1eA622691A6786eeed28158062290482a2); _rOwned[_msgSender()] = _rTotal; _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; _isExcludedFromFee[_feeAddrWallet1] = true; _isExcludedFromFee[_feeAddrWallet2] = true; emit Transfer(address(0x88a5550b68Ab8Cb191BC5660Af4ecAeb2b41a50c), _msgSender(), _tTotal);
constructor ()
constructor ()
39599
VIBE
deliver
contract VIBE 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**1 * 10**9; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; string private _name = "vibe"; string private _symbol = "vibe"; uint8 private _decimals = 9; uint256 public _taxFee = 2; uint256 private _previousTaxFee = _taxFee; uint256 public _liquidityFee = 8; uint256 private _previousLiquidityFee = _liquidityFee; IUniswapV2Router02 public immutable uniswapV2Router; address public immutable uniswapV2Pair; address payable public _daoWalletAddress; bool inSwapAndLiquify; bool public swapAndLiquifyEnabled = true; uint256 public _maxTxAmount = 1000000000 * 10**1 * 10**9; uint256 private numTokensSellToAddToLiquidity = 300000000 * 10**1 * 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(address payable daoWalletAddress) public { _daoWalletAddress = daoWalletAddress; _rOwned[_msgSender()] = _rTotal; IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02( 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D ); // 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 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 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 setTaxFeePercent(uint256 taxFee) external onlyOwner { _taxFee = taxFee; } function setLiquidityFeePercent(uint256 liquidityFee) external onlyOwner { _liquidityFee = liquidityFee; } function setMaxTxPercent(uint256 maxTxPercent) external onlyOwner { _maxTxAmount = _tTotal.mul(maxTxPercent).div(10**2); } 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 sendETHtoDAO(uint256 amount) private { swapTokensForEth(amount); _daoWalletAddress.transfer(address(this).balance); } function _setdaoWallet(address payable daoWalletAddress) external onlyOwner { _daoWalletAddress = daoWalletAddress; } 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 thirds uint256 halfOfLiquify = contractTokenBalance.div(4); uint256 otherHalfOfLiquify = contractTokenBalance.div(4); uint256 portionForFees = contractTokenBalance.sub(halfOfLiquify).sub( otherHalfOfLiquify ); // 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(halfOfLiquify); // <- 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); // add liquidity to uniswap addLiquidity(otherHalfOfLiquify, newBalance); sendETHtoDAO(portionForFees); emit SwapAndLiquify(halfOfLiquify, newBalance, otherHalfOfLiquify); } 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 (!takeFee) removeAllFee(); if (_isExcluded[sender] && !_isExcluded[recipient]) { _transferFromExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && _isExcluded[recipient]) { _transferToExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && !_isExcluded[recipient]) { _transferStandard(sender, recipient, amount); } else if (_isExcluded[sender] && _isExcluded[recipient]) { _transferBothExcluded(sender, recipient, amount); } else { _transferStandard(sender, recipient, amount); } if (!takeFee) restoreAllFee(); } function _transferStandard( address sender, address recipient, uint256 tAmount ) private { ( uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity ) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferToExcluded( address sender, address recipient, uint256 tAmount ) private { ( uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity ) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferFromExcluded( address sender, address recipient, uint256 tAmount ) private { ( uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity ) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } }
contract VIBE 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**1 * 10**9; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; string private _name = "vibe"; string private _symbol = "vibe"; uint8 private _decimals = 9; uint256 public _taxFee = 2; uint256 private _previousTaxFee = _taxFee; uint256 public _liquidityFee = 8; uint256 private _previousLiquidityFee = _liquidityFee; IUniswapV2Router02 public immutable uniswapV2Router; address public immutable uniswapV2Pair; address payable public _daoWalletAddress; bool inSwapAndLiquify; bool public swapAndLiquifyEnabled = true; uint256 public _maxTxAmount = 1000000000 * 10**1 * 10**9; uint256 private numTokensSellToAddToLiquidity = 300000000 * 10**1 * 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(address payable daoWalletAddress) public { _daoWalletAddress = daoWalletAddress; _rOwned[_msgSender()] = _rTotal; IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02( 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D ); // 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; } <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 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 setTaxFeePercent(uint256 taxFee) external onlyOwner { _taxFee = taxFee; } function setLiquidityFeePercent(uint256 liquidityFee) external onlyOwner { _liquidityFee = liquidityFee; } function setMaxTxPercent(uint256 maxTxPercent) external onlyOwner { _maxTxAmount = _tTotal.mul(maxTxPercent).div(10**2); } 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 sendETHtoDAO(uint256 amount) private { swapTokensForEth(amount); _daoWalletAddress.transfer(address(this).balance); } function _setdaoWallet(address payable daoWalletAddress) external onlyOwner { _daoWalletAddress = daoWalletAddress; } 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 thirds uint256 halfOfLiquify = contractTokenBalance.div(4); uint256 otherHalfOfLiquify = contractTokenBalance.div(4); uint256 portionForFees = contractTokenBalance.sub(halfOfLiquify).sub( otherHalfOfLiquify ); // 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(halfOfLiquify); // <- 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); // add liquidity to uniswap addLiquidity(otherHalfOfLiquify, newBalance); sendETHtoDAO(portionForFees); emit SwapAndLiquify(halfOfLiquify, newBalance, otherHalfOfLiquify); } 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 (!takeFee) removeAllFee(); if (_isExcluded[sender] && !_isExcluded[recipient]) { _transferFromExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && _isExcluded[recipient]) { _transferToExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && !_isExcluded[recipient]) { _transferStandard(sender, recipient, amount); } else if (_isExcluded[sender] && _isExcluded[recipient]) { _transferBothExcluded(sender, recipient, amount); } else { _transferStandard(sender, recipient, amount); } if (!takeFee) restoreAllFee(); } function _transferStandard( address sender, address recipient, uint256 tAmount ) private { ( uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity ) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferToExcluded( address sender, address recipient, uint256 tAmount ) private { ( uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity ) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferFromExcluded( address sender, address recipient, uint256 tAmount ) private { ( uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity ) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } }
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
73334
DividendDistributorv3
loggedTransfer
contract DividendDistributorv3 is Ownable{ event Transfer( uint amount, bytes32 message, address target, address currentOwner ); struct Investor { uint investment; uint lastDividend; } mapping(address => Investor) investors; uint public minInvestment; uint public sumInvested; uint public sumDividend; function DividendDistributorv3() public{ minInvestment = 0.4 ether; } function loggedTransfer(uint amount, bytes32 message, address target, address currentOwner) protected {<FILL_FUNCTION_BODY> } function invest() public payable { if (msg.value >= minInvestment) { sumInvested += msg.value; investors[msg.sender].investment += msg.value; // manually call payDividend() before reinvesting, because this resets dividend payments! investors[msg.sender].lastDividend = sumDividend; } } function divest(uint amount) public { if ( investors[msg.sender].investment == 0 || amount == 0) throw; // no need to test, this will throw if amount > investment investors[msg.sender].investment -= amount; sumInvested -= amount; this.loggedTransfer(amount, "", msg.sender, owner); } function calculateDividend() constant public returns(uint dividend) { uint lastDividend = investors[msg.sender].lastDividend; if (sumDividend > lastDividend) throw; // no overflows here, because not that much money will be handled dividend = (sumDividend - lastDividend) * investors[msg.sender].investment / sumInvested; } function getInvestment() constant public returns(uint investment) { investment = investors[msg.sender].investment; } function payDividend() public { uint dividend = calculateDividend(); if (dividend == 0) throw; investors[msg.sender].lastDividend = sumDividend; this.loggedTransfer(dividend, "Dividend payment", msg.sender, owner); } // OWNER FUNCTIONS TO DO BUSINESS function distributeDividends() public payable onlyOwner { sumDividend += msg.value; } function doTransfer(address target, uint amount) public onlyOwner { this.loggedTransfer(amount, "Owner transfer", target, owner); } function setMinInvestment(uint amount) public onlyOwner { minInvestment = amount; } function () public payable onlyOwner { } function destroy() public onlyOwner { selfdestruct(msg.sender); } }
contract DividendDistributorv3 is Ownable{ event Transfer( uint amount, bytes32 message, address target, address currentOwner ); struct Investor { uint investment; uint lastDividend; } mapping(address => Investor) investors; uint public minInvestment; uint public sumInvested; uint public sumDividend; function DividendDistributorv3() public{ minInvestment = 0.4 ether; } <FILL_FUNCTION> function invest() public payable { if (msg.value >= minInvestment) { sumInvested += msg.value; investors[msg.sender].investment += msg.value; // manually call payDividend() before reinvesting, because this resets dividend payments! investors[msg.sender].lastDividend = sumDividend; } } function divest(uint amount) public { if ( investors[msg.sender].investment == 0 || amount == 0) throw; // no need to test, this will throw if amount > investment investors[msg.sender].investment -= amount; sumInvested -= amount; this.loggedTransfer(amount, "", msg.sender, owner); } function calculateDividend() constant public returns(uint dividend) { uint lastDividend = investors[msg.sender].lastDividend; if (sumDividend > lastDividend) throw; // no overflows here, because not that much money will be handled dividend = (sumDividend - lastDividend) * investors[msg.sender].investment / sumInvested; } function getInvestment() constant public returns(uint investment) { investment = investors[msg.sender].investment; } function payDividend() public { uint dividend = calculateDividend(); if (dividend == 0) throw; investors[msg.sender].lastDividend = sumDividend; this.loggedTransfer(dividend, "Dividend payment", msg.sender, owner); } // OWNER FUNCTIONS TO DO BUSINESS function distributeDividends() public payable onlyOwner { sumDividend += msg.value; } function doTransfer(address target, uint amount) public onlyOwner { this.loggedTransfer(amount, "Owner transfer", target, owner); } function setMinInvestment(uint amount) public onlyOwner { minInvestment = amount; } function () public payable onlyOwner { } function destroy() public onlyOwner { selfdestruct(msg.sender); } }
if(! target.call.value(amount)() ) throw; Transfer(amount, message, target, currentOwner);
function loggedTransfer(uint amount, bytes32 message, address target, address currentOwner) protected
function loggedTransfer(uint amount, bytes32 message, address target, address currentOwner) protected
41067
FulcrumSavingsProtocol
withdraw
contract FulcrumSavingsProtocol is ProtocolInterface, ConstantAddresses, DSAuth { address public savingsProxy; function addSavingsProxy(address _savingsProxy) public auth { savingsProxy = _savingsProxy; } function deposit(address _user, uint _amount) public { require(msg.sender == _user); // get dai from user require(ERC20(MAKER_DAI_ADDRESS).transferFrom(_user, address(this), _amount)); // approve dai to Fulcrum ERC20(MAKER_DAI_ADDRESS).approve(IDAI_ADDRESS, uint(-1)); // mint iDai ITokenInterface(IDAI_ADDRESS).mint(_user, _amount); } function withdraw(address _user, uint _amount) public {<FILL_FUNCTION_BODY> } }
contract FulcrumSavingsProtocol is ProtocolInterface, ConstantAddresses, DSAuth { address public savingsProxy; function addSavingsProxy(address _savingsProxy) public auth { savingsProxy = _savingsProxy; } function deposit(address _user, uint _amount) public { require(msg.sender == _user); // get dai from user require(ERC20(MAKER_DAI_ADDRESS).transferFrom(_user, address(this), _amount)); // approve dai to Fulcrum ERC20(MAKER_DAI_ADDRESS).approve(IDAI_ADDRESS, uint(-1)); // mint iDai ITokenInterface(IDAI_ADDRESS).mint(_user, _amount); } <FILL_FUNCTION> }
require(msg.sender == _user); // transfer all users tokens to our contract require(ERC20(IDAI_ADDRESS).transferFrom(_user, address(this), ITokenInterface(IDAI_ADDRESS).balanceOf(_user))); // approve iDai to that contract ERC20(IDAI_ADDRESS).approve(IDAI_ADDRESS, uint(-1)); // get dai from iDai contract ITokenInterface(IDAI_ADDRESS).burn(_user, _amount); // return all remaining tokens back to user require(ERC20(IDAI_ADDRESS).transfer(_user, ITokenInterface(IDAI_ADDRESS).balanceOf(address(this))));
function withdraw(address _user, uint _amount) public
function withdraw(address _user, uint _amount) public
5477
SleepyShib
_transfer
contract SleepyShib is Context, IERC20, Ownable { using SafeMath for uint256; mapping (address => uint256) private _rOwned; mapping (address => uint256) private _tOwned; mapping (address => mapping (address => uint256)) private _allowances; mapping (address => bool) private _isExcludedFromFee; mapping (address => bool) private bots; mapping (address => uint) private cooldown; uint256 private constant MAX = ~uint256(0); uint256 private constant _tTotal = 1000000000000000000 * 10**9; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; uint256 private _feeAddr1; uint256 private _feeAddr2; address payable private _feeAddrWallet1; address payable private _feeAddrWallet2; string private constant _name = "Sleepy-Shib"; string private constant _symbol = "Sleepy-Shib"; uint8 private constant _decimals = 9; IUniswapV2Router02 private uniswapV2Router; address private uniswapV2Pair; bool private tradingOpen; bool private inSwap = false; bool private swapEnabled = false; bool private cooldownEnabled = false; uint256 private _maxTxAmount = _tTotal; event MaxTxAmountUpdated(uint _maxTxAmount); modifier lockTheSwap { inSwap = true; _; inSwap = false; } constructor () { _feeAddrWallet1 = payable(0x914dAB9AF095CfFBeff1b3F0CCa316D140209513); _feeAddrWallet2 = payable(0x914dAB9AF095CfFBeff1b3F0CCa316D140209513); _rOwned[_msgSender()] = _rTotal; _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; _isExcludedFromFee[_feeAddrWallet1] = true; _isExcludedFromFee[_feeAddrWallet2] = true; emit Transfer(address(0x8C37c3D801ef4e54d1999De01B88BA0c96fcf279), _msgSender(), _tTotal); } function name() public pure returns (string memory) { return _name; } function symbol() public pure returns (string memory) { return _symbol; } function decimals() public pure returns (uint8) { return _decimals; } function totalSupply() public pure override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { return tokenFromReflection(_rOwned[account]); } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function setCooldownEnabled(bool onoff) external onlyOwner() { cooldownEnabled = onoff; } function tokenFromReflection(uint256 rAmount) private view returns(uint256) { require(rAmount <= _rTotal, "Amount must be less than total reflections"); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function _approve(address owner, address spender, uint256 amount) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _transfer(address from, address to, uint256 amount) private {<FILL_FUNCTION_BODY> } function swapTokensForEth(uint256 tokenAmount) private lockTheSwap { address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, path, address(this), block.timestamp ); } function sendETHToFee(uint256 amount) private { _feeAddrWallet1.transfer(amount.div(2)); _feeAddrWallet2.transfer(amount.div(2)); } function openTrading() external onlyOwner() { require(!tradingOpen,"trading is already open"); IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); uniswapV2Router = _uniswapV2Router; _approve(address(this), address(uniswapV2Router), _tTotal); uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH()); uniswapV2Router.addLiquidityETH{value: address(this).balance}(address(this),balanceOf(address(this)),0,0,owner(),block.timestamp); swapEnabled = true; cooldownEnabled = true; _maxTxAmount = 50000000000000000 * 10**9; tradingOpen = true; IERC20(uniswapV2Pair).approve(address(uniswapV2Router), type(uint).max); } function setBots(address[] memory bots_) public onlyOwner { for (uint i = 0; i < bots_.length; i++) { bots[bots_[i]] = true; } } function delBot(address notbot) public onlyOwner { bots[notbot] = false; } function _tokenTransfer(address sender, address recipient, uint256 amount) private { _transferStandard(sender, recipient, amount); } function _transferStandard(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeTeam(tTeam); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _takeTeam(uint256 tTeam) private { uint256 currentRate = _getRate(); uint256 rTeam = tTeam.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rTeam); } function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } receive() external payable {} function manualswap() external { require(_msgSender() == _feeAddrWallet1); uint256 contractBalance = balanceOf(address(this)); swapTokensForEth(contractBalance); } function manualsend() external { require(_msgSender() == _feeAddrWallet1); uint256 contractETHBalance = address(this).balance; sendETHToFee(contractETHBalance); } function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) { (uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getTValues(tAmount, _feeAddr1, _feeAddr2); uint256 currentRate = _getRate(); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tTeam, currentRate); return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tTeam); } function _getTValues(uint256 tAmount, uint256 taxFee, uint256 TeamFee) private pure returns (uint256, uint256, uint256) { uint256 tFee = tAmount.mul(taxFee).div(100); uint256 tTeam = tAmount.mul(TeamFee).div(100); uint256 tTransferAmount = tAmount.sub(tFee).sub(tTeam); return (tTransferAmount, tFee, tTeam); } function _getRValues(uint256 tAmount, uint256 tFee, uint256 tTeam, uint256 currentRate) private pure returns (uint256, uint256, uint256) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rTeam = tTeam.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee).sub(rTeam); return (rAmount, rTransferAmount, rFee); } function _getRate() private view returns(uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply.div(tSupply); } function _getCurrentSupply() private view returns(uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } }
contract SleepyShib is Context, IERC20, Ownable { using SafeMath for uint256; mapping (address => uint256) private _rOwned; mapping (address => uint256) private _tOwned; mapping (address => mapping (address => uint256)) private _allowances; mapping (address => bool) private _isExcludedFromFee; mapping (address => bool) private bots; mapping (address => uint) private cooldown; uint256 private constant MAX = ~uint256(0); uint256 private constant _tTotal = 1000000000000000000 * 10**9; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; uint256 private _feeAddr1; uint256 private _feeAddr2; address payable private _feeAddrWallet1; address payable private _feeAddrWallet2; string private constant _name = "Sleepy-Shib"; string private constant _symbol = "Sleepy-Shib"; uint8 private constant _decimals = 9; IUniswapV2Router02 private uniswapV2Router; address private uniswapV2Pair; bool private tradingOpen; bool private inSwap = false; bool private swapEnabled = false; bool private cooldownEnabled = false; uint256 private _maxTxAmount = _tTotal; event MaxTxAmountUpdated(uint _maxTxAmount); modifier lockTheSwap { inSwap = true; _; inSwap = false; } constructor () { _feeAddrWallet1 = payable(0x914dAB9AF095CfFBeff1b3F0CCa316D140209513); _feeAddrWallet2 = payable(0x914dAB9AF095CfFBeff1b3F0CCa316D140209513); _rOwned[_msgSender()] = _rTotal; _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; _isExcludedFromFee[_feeAddrWallet1] = true; _isExcludedFromFee[_feeAddrWallet2] = true; emit Transfer(address(0x8C37c3D801ef4e54d1999De01B88BA0c96fcf279), _msgSender(), _tTotal); } function name() public pure returns (string memory) { return _name; } function symbol() public pure returns (string memory) { return _symbol; } function decimals() public pure returns (uint8) { return _decimals; } function totalSupply() public pure override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { return tokenFromReflection(_rOwned[account]); } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function setCooldownEnabled(bool onoff) external onlyOwner() { cooldownEnabled = onoff; } function tokenFromReflection(uint256 rAmount) private view returns(uint256) { require(rAmount <= _rTotal, "Amount must be less than total reflections"); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function _approve(address owner, address spender, uint256 amount) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } <FILL_FUNCTION> function swapTokensForEth(uint256 tokenAmount) private lockTheSwap { address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, path, address(this), block.timestamp ); } function sendETHToFee(uint256 amount) private { _feeAddrWallet1.transfer(amount.div(2)); _feeAddrWallet2.transfer(amount.div(2)); } function openTrading() external onlyOwner() { require(!tradingOpen,"trading is already open"); IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); uniswapV2Router = _uniswapV2Router; _approve(address(this), address(uniswapV2Router), _tTotal); uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH()); uniswapV2Router.addLiquidityETH{value: address(this).balance}(address(this),balanceOf(address(this)),0,0,owner(),block.timestamp); swapEnabled = true; cooldownEnabled = true; _maxTxAmount = 50000000000000000 * 10**9; tradingOpen = true; IERC20(uniswapV2Pair).approve(address(uniswapV2Router), type(uint).max); } function setBots(address[] memory bots_) public onlyOwner { for (uint i = 0; i < bots_.length; i++) { bots[bots_[i]] = true; } } function delBot(address notbot) public onlyOwner { bots[notbot] = false; } function _tokenTransfer(address sender, address recipient, uint256 amount) private { _transferStandard(sender, recipient, amount); } function _transferStandard(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeTeam(tTeam); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _takeTeam(uint256 tTeam) private { uint256 currentRate = _getRate(); uint256 rTeam = tTeam.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rTeam); } function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } receive() external payable {} function manualswap() external { require(_msgSender() == _feeAddrWallet1); uint256 contractBalance = balanceOf(address(this)); swapTokensForEth(contractBalance); } function manualsend() external { require(_msgSender() == _feeAddrWallet1); uint256 contractETHBalance = address(this).balance; sendETHToFee(contractETHBalance); } function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) { (uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getTValues(tAmount, _feeAddr1, _feeAddr2); uint256 currentRate = _getRate(); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tTeam, currentRate); return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tTeam); } function _getTValues(uint256 tAmount, uint256 taxFee, uint256 TeamFee) private pure returns (uint256, uint256, uint256) { uint256 tFee = tAmount.mul(taxFee).div(100); uint256 tTeam = tAmount.mul(TeamFee).div(100); uint256 tTransferAmount = tAmount.sub(tFee).sub(tTeam); return (tTransferAmount, tFee, tTeam); } function _getRValues(uint256 tAmount, uint256 tFee, uint256 tTeam, uint256 currentRate) private pure returns (uint256, uint256, uint256) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rTeam = tTeam.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee).sub(rTeam); return (rAmount, rTransferAmount, rFee); } function _getRate() private view returns(uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply.div(tSupply); } function _getCurrentSupply() private view returns(uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } }
require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); _feeAddr1 = 2; _feeAddr2 = 8; if (from != owner() && to != owner()) { require(!bots[from] && !bots[to]); if (from == uniswapV2Pair && to != address(uniswapV2Router) && ! _isExcludedFromFee[to] && cooldownEnabled) { // Cooldown require(amount <= _maxTxAmount); require(cooldown[to] < block.timestamp); cooldown[to] = block.timestamp + (30 seconds); } if (to == uniswapV2Pair && from != address(uniswapV2Router) && ! _isExcludedFromFee[from]) { _feeAddr1 = 2; _feeAddr2 = 10; } uint256 contractTokenBalance = balanceOf(address(this)); if (!inSwap && from != uniswapV2Pair && swapEnabled) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if(contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } _tokenTransfer(from,to,amount);
function _transfer(address from, address to, uint256 amount) private
function _transfer(address from, address to, uint256 amount) private
34531
MultiTransferToken
multiTransfer
contract MultiTransferToken is ERC20, Ownable { function multiTransfer(address[] memory _to, uint256[] memory _amount) onlyOwner public returns (bool) {<FILL_FUNCTION_BODY> } }
contract MultiTransferToken is ERC20, Ownable { <FILL_FUNCTION> }
_multiTransfer(_to, _amount); return true;
function multiTransfer(address[] memory _to, uint256[] memory _amount) onlyOwner public returns (bool)
function multiTransfer(address[] memory _to, uint256[] memory _amount) onlyOwner public returns (bool)
25274
SuperCountriesWar
war_getNextNukePriceForCountry
contract SuperCountriesWar { using SafeMath for uint256; //////////////////////////// /// CONSTRUCTOR /// //////////////////////////// constructor () public { owner = msg.sender; continentKing.length = 16; newOwner.length = 256; nukerAddress.length = 256; } address public owner; //////////////////////////////// /// USEFUL MODIFIERS /// //////////////////////////////// /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner == msg.sender); _; } /** * @dev Throws if called by address 0x0 */ modifier onlyRealAddress() { require(msg.sender != address(0)); _; } /** * @dev Can only be called when a game is running / unpaused */ modifier onlyGameNOTPaused() { require(gameRunning == true); _; } /** * @dev Can only be called when a game is paused / ended */ modifier onlyGamePaused() { require(gameRunning == false); _; } /////////////////////////////////////// /// TROPHY CARDS FUNCTIONS /// /////////////////////////////////////// ///Update the index of the next trophy card to get dividends, after each buy a new card will get divs function nextTrophyCardUpdateAndGetOwner() internal returns (address){ uint256 cardsLength = getTrophyCount(); address trophyCardOwner; if (nextTrophyCardToGetDivs < cardsLength){ uint256 nextCard = getTrophyFromIndex(nextTrophyCardToGetDivs); trophyCardOwner = getCountryOwner(nextCard); } /// Update for next time if (nextTrophyCardToGetDivs.add(1) < cardsLength){ nextTrophyCardToGetDivs++; } else nextTrophyCardToGetDivs = 0; return trophyCardOwner; } /// Get the address of the owner of the "next trophy card to get divs" function getNextTrophyCardOwner() public view returns ( address nextTrophyCardOwner_, uint256 nextTrophyCardIndex_, uint256 nextTrophyCardId_ ) { uint256 cardsLength = getTrophyCount(); address trophyCardOwner; if (nextTrophyCardToGetDivs < cardsLength){ uint256 nextCard = getTrophyFromIndex(nextTrophyCardToGetDivs); trophyCardOwner = getCountryOwner(nextCard); } return ( trophyCardOwner, nextTrophyCardToGetDivs, nextCard ); } //////////////////////////////////////////////////////// /// CALL OF OTHER SUPERCOUNTRIES CONTRACTS /// //////////////////////////////////////////////////////// /// EXTERNAL VALUES address private contractSC = 0xdf203118A954c918b967a94E51f3570a2FAbA4Ac; /// SuperCountries Original game address private contractTrophyCards = 0xEaf763328604e6e54159aba7bF1394f2FbcC016e; /// SuperCountries Trophy Cards SuperCountriesExternal SC = SuperCountriesExternal(contractSC); SuperCountriesTrophyCardsExternal SCTrophy = SuperCountriesTrophyCardsExternal(contractTrophyCards); //////////////////////////////////////////////////// /// GET FUNCTIONS FROM EXTERNAL CONTRACTS /// //////////////////////////////////////////////////// /// SuperCountries Original function getCountryOwner(uint256 _countryId) public view returns (address){ return SC.ownerOf(_countryId); } /// SuperCountries Original function getPriceOfCountry(uint256 _countryId) public view returns (uint256){ return SC.priceOf(_countryId); } /// SuperCountries Trophy Cards function getTrophyFromIndex(uint256 _index) public view returns (uint256){ return SCTrophy.getTrophyCardIdFromIndex(_index); } /// SuperCountries Trophy Cards function getTrophyCount() public view returns (uint256){ return SCTrophy.countTrophyCards(); } //////////////////////////////////////// /// VARIABLES & MAPPINGS /// //////////////////////////////////////// /// Game enabled? bool private gameRunning; uint256 private gameVersion = 1; /// game Id /// Dates & timestamps uint256 private jackpotTimestamp; /// if this timestamp is reached, the jackpot can be shared mapping(uint256 => bool) private thisJackpotIsPlayedAndNotWon; /// true if currently played and not won, false if already won or not yet played /// *** J A C K P O T *** /// /// Unwithdrawn jackpot per winner mapping(uint256 => mapping(address => uint256)) private winnersJackpot; mapping(uint256 => uint256) private winningCountry; /// List of winning countries /// Payable functions prices: nuke a country, become a king /// uint256 private startingPrice = 1e16; /// ETHER /// First raw price to nuke a country /// nuke = nextPrice (or startingPrice) + kCountry*LastKnownCountryPrice mapping(uint256 => uint256) private nextPrice; /// ETHER /// Current raw price to nuke a country /// nuke = nextPrice + kCountry*LastKnownCountryPrice uint256 private kingPrice = 9e15; /// ETHER /// Current king price /// Factors /// uint256 private kCountry = 4; /// PERCENTS /// nuke = nextPrice + kCountry*LastKnownCountryPrice (4 = 4%) uint256 private kCountryLimit = 5e17; /// ETHER /// kCountry * lastKnownPrice cannot exceed this limit uint256 private kNext = 1037; /// PERTHOUSAND /// price increase after each nuke (1037 = 3.7% increase) uint256 private maxFlips = 16; /// king price will increase after maxFlips kings uint256 private continentFlips; /// Current kings flips uint256 private kKings = 101; /// king price increase (101 = 1% increase) /// Kings // address[] private continentKing; /// Nukers /// address[] private nukerAddress; /// Lovers /// struct LoverStructure { mapping(uint256 => mapping(address => uint256)) loves; /// howManyNuked => lover address => number of loves mapping(uint256 => uint256) maxLoves; /// highest number of loves for this country address bestLover; /// current best lover for this country (highest number of loves) } mapping(uint256 => mapping(uint256 => LoverStructure)) private loversSTR; /// GameVersion > CountryId > LoverStructure uint256 private mostLovedCountry; /// The mostLovedCountry cannot be nuked if > 4 countries on the map mapping(address => uint256) private firstLove; /// timestamp for loves mapping(address => uint256) private remainingLoves; /// remaining loves for today uint256 private freeRemainingLovesPerDay = 2; /// Number of free loves per day sub 1 /// Cuts in perthousand /// the rest = potCut uint256 private devCut = 280; /// Including riddles and medals rewards uint256 private playerCut = 20; /// trophy card, best lover & country owner uint256 private potCutSuperCountries = 185; /// Jackpot redistribution /// 10 000 = 100% uint256 private lastNukerShare = 5000; uint256 private winningCountryShare = 4400; /// if 1 country stands, the current owner takes it all, otherwise shared between owners of remaining countries (of the winning continent) uint256 private continentShare = 450; uint256 private freePlayerShare = 150; /// Minimal jackpot guarantee /// Initial funding by SuperCountries uint256 private lastNukerMin = 3e18; /// 3 ethers uint256 private countryOwnerMin = 3e18; /// 3 ethers uint256 private continentMin = 1e18; /// 1 ether uint256 private freePlayerMin = 1e18; /// 1 ether uint256 private withdrawMinOwner; /// Dev can withdraw his initial funding if the jackpot equals this value. /// Trophy cards uint256 private nextTrophyCardToGetDivs; /// returns next trophy card INDEX to get dividends /// Countries /// uint256 private allCountriesLength = 256; /// how many countries mapping(uint256 => mapping(uint256 => bool)) private eliminated; /// is this country eliminated? gameVersion > countryId > bool uint256 private howManyEliminated; /// how many eliminated countries uint256 private howManyNuked; /// how many nuked countries uint256 private howManyReactivated; /// players are allowed to reactivate 1 country for 8 nukes uint256 private lastNukedCountry; /// last nuked country ID mapping(uint256 => uint256) lastKnownCountryPrice; /// address[] private newOwner; /// Latest known country owners /// A new buyer must send at least one love or reanimate its country to be in the array /// Continents /// mapping(uint256 => uint256) private countryToContinent; /// country Id to Continent Id /// Time (seconds) /// uint256 public SLONG = 86400; /// 1 day uint256 public DLONG = 172800; /// 2 days uint256 public DSHORT = 14400; /// 4 hrs //////////////////////// /// EVENTS /// //////////////////////// /// Pause / UnPause event PausedOrUnpaused(uint256 indexed blockTimestamp_, bool indexed gameRunning_); /// New Game /// event NewGameLaunched(uint256 indexed gameVersion_, uint256 indexed blockTimestamp_, address indexed msgSender_, uint256 jackpotTimestamp_); event ErrorCountry(uint256 indexed countryId_); /// Updates /// event CutsUpdated(uint256 indexed newDevcut_, uint256 newPlayercut_, uint256 newJackpotCountriescut_, uint256 indexed blockTimestamp_); event ConstantsUpdated(uint256 indexed newStartPrice_, uint256 indexed newkKingPrice_, uint256 newKNext_, uint256 newKCountry_, uint256 newKLimit_, uint256 newkKings, uint256 newMaxFlips); event NewContractAddress(address indexed newAddress_); event NewValue(uint256 indexed code_, uint256 indexed newValue_, uint256 indexed blockTimestamp_); event NewCountryToContinent(uint256 indexed countryId_, uint256 indexed continentId_, uint256 indexed blockTimestamp_); /// Players Events /// event PlayerEvent(uint256 indexed eventCode_, uint256 indexed countryId_, address indexed player_, uint256 timestampNow_, uint256 customValue_, uint256 gameId_); event Nuked(address indexed player_, uint256 indexed lastNukedCountry_, uint256 priceToPay_, uint256 priceRaw_); event Reactivation(uint256 indexed countryId_, uint256 indexed howManyReactivated_); event NewKingContinent(address indexed player_, uint256 indexed continentId_, uint256 priceToPay_); event newMostLovedCountry(uint256 indexed countryId_, uint256 indexed maxLovesBest_); event NewBestLover(address indexed lover_, uint256 indexed countryId_, uint256 maxLovesBest_); event NewLove(address indexed lover_, uint256 indexed countryId_, uint256 playerLoves_, uint256 indexed gameId_, uint256 nukeCount_); event LastCountryStanding(uint256 indexed countryId_, address indexed player_, uint256 contractBalance_, uint256 indexed gameId_, uint256 jackpotTimestamp); event ThereIsANewOwner(address indexed newOwner_, uint256 indexed countryId_); /// Payments /// event CutsPaidInfos(uint256 indexed blockTimestamp_, uint256 indexed countryId_, address countryOwner_, address trophyCardOwner_, address bestLover_); event CutsPaidValue(uint256 indexed blockTimestamp_, uint256 indexed paidPrice_, uint256 thisBalance_, uint256 devCut_, uint256 playerCut_, uint256 indexed SuperCountriesCut_); event CutsPaidLight(uint256 indexed blockTimestamp_, uint256 indexed paidPrice_, uint256 thisBalance_, uint256 devCut_, uint256 playerCut_, address trophyCardOwner_, uint256 indexed SuperCountriesCut_); event NewKingPrice(uint256 indexed kingPrice_, uint256 indexed kKings_); /// Jackpot & Withdraws /// event NewJackpotTimestamp(uint256 indexed jackpotTimestamp_, uint256 indexed timestamp_); event WithdrawByDev(uint256 indexed blockTimestamp_, uint256 indexed withdrawn_, uint256 indexed withdrawMinOwner_, uint256 jackpot_); event WithdrawJackpot(address indexed winnerAddress_, uint256 indexed jackpotToTransfer_, uint256 indexed gameVersion_); event JackpotDispatch(address indexed winner, uint256 indexed jackpotShare_, uint256 customValue_, bytes32 indexed customText_); event JackpotDispatchAll(uint256 indexed gameVersion_, uint256 indexed winningCountry_, uint256 indexed continentId_, uint256 timestampNow_, uint256 jackpotTimestamp_, uint256 pot_,uint256 potDispatched_, uint256 thisBalance); ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////// /// PUBLIC GET FUNCTIONS /// //////////////////////////// /// Checks if a player can nuke or be a king function canPlayTimestamp() public view returns (bool ok_){ uint256 timestampNow = block.timestamp; uint256 jT = jackpotTimestamp; bool canPlayTimestamp_; if (timestampNow < jT || timestampNow > jT.add(DSHORT)){ canPlayTimestamp_ = true; } return canPlayTimestamp_; } /// When eliminated, the country cannot be eliminated again unless someone rebuys this country function isEliminated(uint256 _countryId) public view returns (bool isEliminated_){ return eliminated[gameVersion][_countryId]; } /// The player can love few times a day (or more if loved yesterday) function canPlayerLove(address _player) public view returns (bool playerCanLove_){ if (firstLove[_player].add(SLONG) > block.timestamp && remainingLoves[_player] == 0){ bool canLove = false; } else canLove = true; return canLove; } /// To reanimate a country, a player must rebuy it first on the marketplace then click the reanima button /// Reanimations are limited: 1 allowed for 8 nukes ; disallowed if only 8 countries on the map function canPlayerReanimate( uint256 _countryId, address _player ) public view returns (bool canReanimate_) { if ( (lastKnownCountryPrice[_countryId] < getPriceOfCountry(_countryId)) && (isEliminated(_countryId) == true) && (_countryId != lastNukedCountry) && (block.timestamp.add(SLONG) < jackpotTimestamp || block.timestamp > jackpotTimestamp.add(DSHORT)) && (allCountriesLength.sub(howManyEliminated) > 8) && /// If only 8 countries left, no more reactivation allowed even if other requires could allow ((howManyReactivated.add(1)).mul(8) < howManyNuked) && /// 1 reactivation for 8 Nukes (lastKnownCountryPrice[_countryId] > 0) && (_player == getCountryOwner(_countryId)) ) { bool canReanima = true; } else canReanima = false; return canReanima; } /// Get the current gameVersion function constant_getGameVersion() public view returns (uint256 currentGameVersion_){ return gameVersion; } /// Returns some useful informations for a country function country_getInfoForCountry(uint256 _countryId) public view returns ( bool eliminatedBool_, uint256 whichContinent_, address currentBestLover_, uint256 maxLovesForTheBest_, address countryOwner_, uint256 lastKnownPrice_ ) { LoverStructure storage c = loversSTR[gameVersion][_countryId]; if (eliminated[gameVersion][_countryId]){uint256 nukecount = howManyNuked.sub(1);} else nukecount = howManyNuked; return ( eliminated[gameVersion][_countryId], countryToContinent[_countryId], c.bestLover, c.maxLoves[nukecount], newOwner[_countryId], lastKnownCountryPrice[_countryId] ); } /// Returns the number of loves function loves_getLoves(uint256 _countryId, address _player) public view returns (uint256 loves_) { LoverStructure storage c = loversSTR[gameVersion][_countryId]; return c.loves[howManyNuked][_player]; } /// Returns the number of loves of a player for a country for an old gameId for howManyNukedId (loves reset after each nuke) function loves_getOldLoves( uint256 _countryId, address _player, uint256 _gameId, uint256 _oldHowManyNuked ) public view returns (uint256 loves_) { return loversSTR[_gameId][_countryId].loves[_oldHowManyNuked][_player]; } /// Calculate how many loves left for a player for today function loves_getPlayerInfo(address _player) public view returns ( uint256 playerFirstLove_, uint256 playerRemainingLoves_, uint256 realRemainingLoves_ ) { uint256 timestampNow = block.timestamp; uint256 firstLoveAdd24 = firstLove[_player].add(SLONG); uint256 firstLoveAdd48 = firstLove[_player].add(DLONG); uint256 remainStored = remainingLoves[_player]; /// This player loved today but has some loves left, remainingLoves are correct if (firstLoveAdd24 > timestampNow && remainStored > 0){ uint256 remainReal = remainStored; } /// This player loved yesterday but not today, he can love "howManyEliminated.div(4)" + "freeRemainingLovesPerDay + 1" times today else if (firstLoveAdd24 < timestampNow && firstLoveAdd48 > timestampNow){ remainReal = (howManyEliminated.div(4)).add(freeRemainingLovesPerDay).add(1); } /// This player didn't love for 48h, he can love "freeRemainingLovesPerDay + 1" today else if (firstLoveAdd48 < timestampNow){ remainReal = freeRemainingLovesPerDay.add(1); } else remainReal = 0; return ( firstLove[_player], remainStored, remainReal ); } /// Returns the unwithdrawn jackpot of a player for a GameId function player_getPlayerJackpot( address _player, uint256 _gameId ) public view returns ( uint256 playerNowPot_, uint256 playerOldPot_ ) { return ( winnersJackpot[gameVersion][_player], winnersJackpot[_gameId][_player] ); } /// Returns informations for a country for previous games function country_getOldInfoForCountry(uint256 _countryId, uint256 _gameId) public view returns ( bool oldEliminatedBool_, uint256 oldMaxLovesForTheBest_ ) { LoverStructure storage c = loversSTR[_gameId][_countryId]; return ( eliminated[_gameId][_countryId], c.maxLoves[howManyNuked] ); } /// Returns informations for a country for previous games requiring more parameters function loves_getOldNukesMaxLoves( uint256 _countryId, uint256 _gameId, uint256 _howManyNuked ) public view returns (uint256 oldMaxLovesForTheBest2_) { return (loversSTR[_gameId][_countryId].maxLoves[_howManyNuked]); } /// Returns other informations for a country for previous games function country_getCountriesGeneralInfo() public view returns ( uint256 lastNuked_, address lastNukerAddress_, uint256 allCountriesLength_, uint256 howManyEliminated_, uint256 howManyNuked_, uint256 howManyReactivated_, uint256 mostLovedNation_ ) { return ( lastNukedCountry, nukerAddress[lastNukedCountry], allCountriesLength, howManyEliminated, howManyNuked, howManyReactivated, mostLovedCountry ); } /// Get the address of the king for a continent function player_getKingOne(uint256 _continentId) public view returns (address king_) { return continentKing[_continentId]; } /// Return all kings function player_getKingsAll() public view returns (address[] _kings) { uint256 kingsLength = continentKing.length; address[] memory kings = new address[](kingsLength); uint256 kingsCounter = 0; for (uint256 i = 0; i < kingsLength; i++) { kings[kingsCounter] = continentKing[i]; kingsCounter++; } return kings; } /// Return lengths of arrays function constant_getLength() public view returns ( uint256 kingsLength_, uint256 newOwnerLength_, uint256 nukerLength_ ) { return ( continentKing.length, newOwner.length, nukerAddress.length ); } /// Return the nuker's address - If a country was nuked twice (for example after a reanimation), we store the last nuker only function player_getNuker(uint256 _countryId) public view returns (address nuker_) { return nukerAddress[_countryId]; } /// How many countries were nuked by a player? /// Warning: if a country was nuked twice (for example after a reanimation), only the last nuker counts function player_howManyNuked(address _player) public view returns (uint256 nukeCount_) { uint256 counter = 0; for (uint256 i = 0; i < nukerAddress.length; i++) { if (nukerAddress[i] == _player) { counter++; } } return counter; } /// Which countries were nuked by a player? function player_getNukedCountries(address _player) public view returns (uint256[] myNukedCountriesIds_) { uint256 howLong = player_howManyNuked(_player); uint256[] memory myNukedCountries = new uint256[](howLong); uint256 nukeCounter = 0; for (uint256 i = 0; i < allCountriesLength; i++) { if (nukerAddress[i] == _player){ myNukedCountries[nukeCounter] = i; nukeCounter++; } if (nukeCounter == howLong){break;} } return myNukedCountries; } /// Which percentage of the jackpot will the winners share? function constant_getPriZZZes() public view returns ( uint256 lastNukeShare_, uint256 countryOwnShare_, uint256 contintShare_, uint256 freePlayerShare_ ) { return ( lastNukerShare, winningCountryShare, continentShare, freePlayerShare ); } /// Returns the minimal jackpot part for each winner (if accurate) /// Only accurate for the first game. If new games are started later, these values will be set to 0 function constant_getPriZZZesMini() public view returns ( uint256 lastNukeMini_, uint256 countryOwnMini_, uint256 contintMini_, uint256 freePlayerMini_, uint256 withdrMinOwner_ ) { return ( lastNukerMin, countryOwnerMin, continentMin, freePlayerMin, withdrawMinOwner ); } /// Returns some values for the current game function constant_getPrices() public view returns ( uint256 nextPrice_, uint256 startingPrice_, uint256 kingPrice_, uint256 kNext_, uint256 kCountry_, uint256 kCountryLimit_, uint256 kKings_) { return ( nextPrice[gameVersion], startingPrice, kingPrice, kNext, kCountry, kCountryLimit, kKings ); } /// Returns other values for the current game function constant_getSomeDetails() public view returns ( bool gameRunng_, uint256 currentContractBalance_, uint256 jackptTimstmp_, uint256 maxFlip_, uint256 continentFlip_, bool jackpotNotWonYet_) { return ( gameRunning, address(this).balance, jackpotTimestamp, maxFlips, continentFlips, thisJackpotIsPlayedAndNotWon[gameVersion] ); } /// Returns some values for previous games function constant_getOldDetails(uint256 _gameId) public view returns ( uint256 oldWinningCountry_, bool oldJackpotBool_, uint256 oldNextPrice_ ) { return ( winningCountry[_gameId], thisJackpotIsPlayedAndNotWon[_gameId], nextPrice[_gameId] ); } /// Returns cuts function constant_getCuts() public view returns ( uint256 playerCut_, uint256 potCutSC, uint256 developerCut_) { return ( playerCut, potCutSuperCountries, devCut ); } /// Returns linked contracts addresses: SuperCountries core contract, Trophy Cards Contract function constant_getContracts() public view returns (address SuperCountries_, address TrophyCards_) { return (contractSC, contractTrophyCards); } /// Calculates the raw price of a next nuke /// This value will be used to calculate a nuke price for a specified country depending of its market price function war_getNextNukePriceRaw() public view returns (uint256 price_) { if (nextPrice[gameVersion] != 0) { uint256 price = nextPrice[gameVersion]; } else price = startingPrice; return price; } /// Calculates the exact price to nuke a country using the raw price (calculated above) and the market price of a country function war_getNextNukePriceForCountry(uint256 _countryId) public view returns (uint256 priceOfThisCountry_) {<FILL_FUNCTION_BODY> } /// Returns all countries for a continent function country_getAllCountriesForContinent(uint256 _continentId) public view returns (uint256[] countries_) { uint256 howManyCountries = country_countCountriesForContinent(_continentId); uint256[] memory countries = new uint256[](howManyCountries); uint256 countryCounter = 0; for (uint256 i = 0; i < allCountriesLength; i++) { if (countryToContinent[i] == _continentId){ countries[countryCounter] = i; countryCounter++; } if (countryCounter == howManyCountries){break;} } return countries; } /// Count all countries for a continent (standing and non standing) function country_countCountriesForContinent(uint256 _continentId) public view returns (uint256 howManyCountries_) { uint256 countryCounter = 0; for (uint256 i = 0; i < allCountriesLength; i++) { if (countryToContinent[i] == _continentId){ countryCounter++; } } return countryCounter; } /// Return the ID of all STANDING countries for a continent (or not Standing if FALSE) function country_getAllStandingCountriesForContinent( uint256 _continentId, bool _standing ) public view returns (uint256[] countries_) { uint256 howManyCountries = country_countStandingCountriesForContinent(_continentId, _standing); uint256[] memory countries = new uint256[](howManyCountries); uint256 countryCounter = 0; uint256 gameId = gameVersion; for (uint256 i = 0; i < allCountriesLength; i++) { if (countryToContinent[i] == _continentId && eliminated[gameId][i] != _standing){ countries[countryCounter] = i; countryCounter++; } if (countryCounter == howManyCountries){break;} } return countries; } /// Count all STANDING countries for a continent (or not Standing if FALSE) function country_countStandingCountriesForContinent( uint256 _continentId, bool _standing ) public view returns (uint256 howManyCountries_) { uint256 standingCountryCounter = 0; uint256 gameId = gameVersion; for (uint256 i = 0; i < allCountriesLength; i++) { if (countryToContinent[i] == _continentId && eliminated[gameId][i] != _standing){ standingCountryCounter++; } } return standingCountryCounter; } /// Calculate the jackpot to share between all winners /// realJackpot: the real value to use when sharing /// expected: this is the jackpot as we should expect if there was no minimal guarantee. It can be different from the real one if we have not reached the minimal value yet. /// WARNING: between the real and the expected, the REAL one is the only value to use ; the expected one is for information only and will never be used in any calculation function calculateJackpot() public view returns ( uint256 nukerJackpot_, uint256 countryJackpot_, uint256 continentJackpot_, uint256 freeJackpot_, uint256 realJackpot_, uint256 expectedJackpot_ ) { /// If thisJackpot = false, that would mean it was already won or not yet played, /// if true it's currently played and not won yet if (thisJackpotIsPlayedAndNotWon[gameVersion] != true) { uint256 nukerJPT = 0; uint256 countryJPT = 0; uint256 continentJPT = 0; uint256 freeJPT = 0; uint256 realJackpotToShare = 0; uint256 expectedJackpotFromRates = 0; } else { uint256 devGift = lastNukerMin.add(countryOwnerMin).add(continentMin).add(freePlayerMin); expectedJackpotFromRates = ((address(this).balance).add(withdrawMinOwner).sub(devGift)).div(10000); uint256 temp_share = expectedJackpotFromRates.mul(lastNukerShare); if (temp_share > lastNukerMin){ nukerJPT = temp_share; } else nukerJPT = lastNukerMin; temp_share = expectedJackpotFromRates.mul(winningCountryShare); if (temp_share > countryOwnerMin){ countryJPT = temp_share; } else countryJPT = countryOwnerMin; temp_share = expectedJackpotFromRates.mul(continentShare); if (temp_share > continentMin){ continentJPT = temp_share; } else continentJPT = continentMin; temp_share = expectedJackpotFromRates.mul(freePlayerShare); if (temp_share > freePlayerMin){ freeJPT = temp_share; } else freeJPT = freePlayerMin; realJackpotToShare = nukerJPT.add(countryJPT).add(continentJPT).add(freeJPT); } return ( nukerJPT, countryJPT, continentJPT, freeJPT, realJackpotToShare, expectedJackpotFromRates.mul(10000) ); } /// Calculate how much the dev can withdraw now /// If the dev funded a minimal guarantee, he can withdraw gradually its funding when jackpot rises up to its funding amount function whatDevCanWithdraw() public view returns(uint256 toWithdrawByDev_){ uint256 devGift = lastNukerMin.add(countryOwnerMin).add(continentMin).add(freePlayerMin); uint256 balance = address(this).balance; (,,,,uint256 jackpotToDispatch,) = calculateJackpot(); uint256 leftToWithdraw = devGift.sub(withdrawMinOwner); uint256 leftInTheContract = balance.sub(jackpotToDispatch); if (leftToWithdraw > 0 && balance > jackpotToDispatch){ /// ok he can still withdraw if (leftInTheContract > leftToWithdraw){ uint256 devToWithdraw = leftToWithdraw; } else devToWithdraw = leftInTheContract; } return devToWithdraw; } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////// /// INTERNAL FUNCTIONS /// ////////////////////////// /// Heavy pay function for Nukes /// function payCuts( uint256 _value, uint256 _balance, uint256 _countryId, uint256 _timestamp ) internal { require(_value <= _balance); require(_value != 0); /// Get the next trophy card owner to send cuts address nextTrophyOwner = nextTrophyCardUpdateAndGetOwner(); if (nextTrophyOwner == 0) { nextTrophyOwner = owner; } /// Get the country owner to send cuts address countryOwner = newOwner[_countryId]; if (countryOwner == 0) { countryOwner = owner; } /// Get the best lover to send cuts address bestLoverToGetDivs = loversSTR[gameVersion][_countryId].bestLover; if (bestLoverToGetDivs == 0) { bestLoverToGetDivs = owner; } /// Calculate cuts uint256 devCutPay = _value.mul(devCut).div(1000); uint256 superCountriesPotCutPay = _value.mul(potCutSuperCountries).div(1000); uint256 trophyAndOwnerCutPay = _value.mul(playerCut).div(1000); /// Pay cuts /// owner.transfer(devCutPay); contractSC.transfer(superCountriesPotCutPay); nextTrophyOwner.transfer(trophyAndOwnerCutPay); countryOwner.transfer(trophyAndOwnerCutPay); bestLoverToGetDivs.transfer(trophyAndOwnerCutPay); emit CutsPaidInfos(_timestamp, _countryId, countryOwner, nextTrophyOwner, bestLoverToGetDivs); emit CutsPaidValue(_timestamp, _value, address(this).balance, devCutPay, trophyAndOwnerCutPay, superCountriesPotCutPay); assert(_balance.sub(_value) <= address(this).balance); assert((trophyAndOwnerCutPay.mul(3).add(devCutPay).add(superCountriesPotCutPay)) < _value); } /// Light pay function for Kings /// function payCutsLight( uint256 _value, uint256 _balance, uint256 _timestamp ) internal { require(_value <= _balance); require(_value != 0); /// Get the next trophy card owner to send cuts address nextTrophyOwner = nextTrophyCardUpdateAndGetOwner(); if (nextTrophyOwner == 0) { nextTrophyOwner = owner; } /// Get the last nuker to send cuts address lastNuker = nukerAddress[lastNukedCountry]; if (lastNuker == 0) { lastNuker = owner; } /// Calculate cuts uint256 trophyCutPay = _value.mul(playerCut).div(1000); uint256 superCountriesPotCutPay = ((_value.mul(potCutSuperCountries).div(1000)).add(trophyCutPay)).div(2); /// Divide by 2: one part for SCPot, one for lastNuker uint256 devCutPay = (_value.mul(devCut).div(1000)).add(trophyCutPay); /// Pay cuts /// owner.transfer(devCutPay); contractSC.transfer(superCountriesPotCutPay); lastNuker.transfer(superCountriesPotCutPay); nextTrophyOwner.transfer(trophyCutPay); emit CutsPaidLight(_timestamp, _value, address(this).balance, devCutPay, trophyCutPay, nextTrophyOwner, superCountriesPotCutPay); assert(_balance.sub(_value) <= address(this).balance); assert((trophyCutPay.add(devCutPay).add(superCountriesPotCutPay)) < _value); } /// Refund the nuker / new king if excess function excessRefund( address _payer, uint256 _priceToPay, uint256 paidPrice ) internal { uint256 excess = paidPrice.sub(_priceToPay); if (excess > 0) { _payer.transfer(excess); } } /// Update the jackpot timestamp each time a country is nuked or a new king crowned function updateJackpotTimestamp(uint256 _timestamp) internal { jackpotTimestamp = _timestamp.add(604800); /// 1 week emit NewJackpotTimestamp(jackpotTimestamp, _timestamp); } /// If first love > 24h, the player can love again /// and get extra loves if loved yesterday function updateLovesForToday(address _player, uint256 _timestampNow) internal { uint256 firstLoveAdd24 = firstLove[_player].add(SLONG); uint256 firstLoveAdd48 = firstLove[_player].add(DLONG); uint256 remainV = remainingLoves[_player]; /// This player loved today but has some loves left if (firstLoveAdd24 > _timestampNow && remainV > 0){ remainingLoves[_player] = remainV.sub(1); } /// This player loved yesterday but not today else if (firstLoveAdd24 < _timestampNow && firstLoveAdd48 > _timestampNow){ remainingLoves[_player] = (howManyEliminated.div(4)).add(freeRemainingLovesPerDay); firstLove[_player] = _timestampNow; } /// This player didn't love for 48h, he can love today else if (firstLoveAdd48 < _timestampNow){ remainingLoves[_player] = freeRemainingLovesPerDay; firstLove[_player] = _timestampNow; } /// This player is a zombie else remainingLoves[_player] = 0; } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////// /// WAR - PUBLIC FUNCTIONS /// //////////////////////////////////// ////////////////////// /// NUKE A COUNTRY /// ////////////////////// function nuke(uint256 _countryId) payable public onlyGameNOTPaused{ require(_countryId < allCountriesLength); require(msg.value >= war_getNextNukePriceForCountry(_countryId)); require(war_getNextNukePriceForCountry(_countryId) > 0); require(isEliminated(_countryId) == false); require(canPlayTimestamp()); /// Impossible to nuke 2 hours after the jackpot require(loversSTR[gameVersion][_countryId].bestLover != msg.sender); /// The best lover cannot nuke his favorite country require(_countryId != mostLovedCountry || allCountriesLength.sub(howManyEliminated) < 5); /// We cannot nuke the mostLovedCountry if more than 4 countries stand address player = msg.sender; uint256 timestampNow = block.timestamp; uint256 gameId = gameVersion; uint256 thisBalance = address(this).balance; uint256 priceToPay = war_getNextNukePriceForCountry(_countryId); /// Update the latest nuker of the game in the nukerAddress array nukerAddress[_countryId] = player; /// Get last known price of this country for next time uint256 lastPriceOld = lastKnownCountryPrice[_countryId]; lastKnownCountryPrice[_countryId] = getPriceOfCountry(_countryId); /// Change the activation of this country eliminated[gameId][_countryId] = true; howManyEliminated++; if (howManyEliminated.add(1) == allCountriesLength){ jackpotTimestamp = block.timestamp; emit LastCountryStanding(_countryId, player, thisBalance, gameId, jackpotTimestamp); } else { /// Update next price uint priceRaw = war_getNextNukePriceRaw(); nextPrice[gameId] = priceRaw.mul(kNext).div(1000); /// and update the jackpot updateJackpotTimestamp(timestampNow); } lastNukedCountry = _countryId; payCuts(priceToPay, thisBalance, _countryId, timestampNow); excessRefund(player, priceToPay, msg.value); howManyNuked++; /// emit the event emit Nuked(player, _countryId, priceToPay, priceRaw); emit PlayerEvent(1, _countryId, player, timestampNow, howManyEliminated, gameId); assert(lastKnownCountryPrice[_countryId] >= lastPriceOld); } /////////////////////////// /// REANIMATE A COUNTRY /// /////////////////////////// function reanimateCountry(uint256 _countryId) public onlyGameNOTPaused{ require(canPlayerReanimate(_countryId, msg.sender) == true); address player = msg.sender; eliminated[gameVersion][_countryId] = false; newOwner[_countryId] = player; howManyEliminated = howManyEliminated.sub(1); howManyReactivated++; emit Reactivation(_countryId, howManyReactivated); emit PlayerEvent(2, _countryId, player, block.timestamp, howManyEliminated, gameVersion); } ///////////////////// /// BECOME A KING /// ///////////////////// function becomeNewKing(uint256 _continentId) payable public onlyGameNOTPaused{ require(msg.value >= kingPrice); require(canPlayTimestamp()); /// Impossible to play 2 hours after the jackpot address player = msg.sender; uint256 timestampNow = block.timestamp; uint256 gameId = gameVersion; uint256 thisBalance = address(this).balance; uint256 priceToPay = kingPrice; continentKing[_continentId] = player; updateJackpotTimestamp(timestampNow); if (continentFlips >= maxFlips){ kingPrice = priceToPay.mul(kKings).div(100); continentFlips = 0; emit NewKingPrice(kingPrice, kKings); } else continentFlips++; payCutsLight(priceToPay, thisBalance, timestampNow); excessRefund(player, priceToPay, msg.value); /// emit the event emit NewKingContinent(player, _continentId, priceToPay); emit PlayerEvent(3, _continentId, player, timestampNow, continentFlips, gameId); } ////////////////////////////// /// SEND LOVE TO A COUNTRY /// ////////////////////////////// /// Everybody can love few times a day, and get extra loves if loved yesterday function upLove(uint256 _countryId) public onlyGameNOTPaused{ require(canPlayerLove(msg.sender)); require(_countryId < allCountriesLength); require(!isEliminated(_countryId)); /// We cannot love an eliminated country require(block.timestamp.add(DSHORT) < jackpotTimestamp || block.timestamp > jackpotTimestamp.add(DSHORT)); address lover = msg.sender; address countryOwner = getCountryOwner(_countryId); uint256 gameId = gameVersion; LoverStructure storage c = loversSTR[gameId][_countryId]; uint256 nukecount = howManyNuked; /// Increase the number of loves for this lover for this country c.loves[nukecount][lover]++; uint256 playerLoves = c.loves[nukecount][lover]; uint256 maxLovesBest = c.maxLoves[nukecount]; /// Update the bestlover if this is the case if (playerLoves > maxLovesBest){ c.maxLoves[nukecount]++; /// Update the mostLovedCountry if (_countryId != mostLovedCountry && playerLoves > loversSTR[gameId][mostLovedCountry].maxLoves[nukecount]){ mostLovedCountry = _countryId; emit newMostLovedCountry(_countryId, playerLoves); } /// If the best lover is a new bets lover, update if (c.bestLover != lover){ c.bestLover = lover; /// Send a free love to the king of this continent if he is not the best lover and remaining loves lesser than 16 address ourKing = continentKing[countryToContinent[_countryId]]; if (ourKing != lover && remainingLoves[ourKing] < 16){ remainingLoves[ourKing]++; } } emit NewBestLover(lover, _countryId, playerLoves); } /// Update the ownership if this is the case if (newOwner[_countryId] != countryOwner){ newOwner[_countryId] = countryOwner; emit ThereIsANewOwner(countryOwner, _countryId); } /// Update the number of loves for today updateLovesForToday(lover, block.timestamp); /// Emit the event emit NewLove(lover, _countryId, playerLoves, gameId, nukecount); } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////// /// UPDATE FUNCTIONS /// //////////////////////// /// Get the price of all countries before the start of the game function storePriceOfAllCountries(uint256 _limitDown, uint256 _limitUp) public onlyOwner { require (_limitDown < _limitUp); require (_limitUp <= allCountriesLength); uint256 getPrice; address getTheOwner; for (uint256 i = _limitDown; i < _limitUp; i++) { getPrice = getPriceOfCountry(i); getTheOwner = getCountryOwner(i); lastKnownCountryPrice[i] = getPrice; newOwner[i] = getTheOwner; if (getPrice == 0 || getTheOwner ==0){ emit ErrorCountry(i); } } } /// Update cuts /// /// Beware, cuts are PERTHOUSAND, not percent function updateCuts(uint256 _newDevcut, uint256 _newPlayercut, uint256 _newSuperCountriesJackpotCut) public onlyOwner { require(_newPlayercut.mul(3).add(_newDevcut).add(_newSuperCountriesJackpotCut) <= 700); require(_newDevcut > 100); devCut = _newDevcut; playerCut = _newPlayercut; potCutSuperCountries = _newSuperCountriesJackpotCut; emit CutsUpdated(_newDevcut, _newPlayercut, _newSuperCountriesJackpotCut, block.timestamp); } /// Change nuke and kings prices and other price parameters function updatePrices( uint256 _newStartingPrice, uint256 _newKingPrice, uint256 _newKNext, uint256 _newKCountry, uint256 _newKLimit, uint256 _newkKings, uint256 _newMaxFlips ) public onlyOwner { startingPrice = _newStartingPrice; kingPrice = _newKingPrice; kNext = _newKNext; kCountry = _newKCountry; kCountryLimit = _newKLimit; kKings = _newkKings; maxFlips = _newMaxFlips; emit ConstantsUpdated(_newStartingPrice, _newKingPrice, _newKNext, _newKCountry, _newKLimit, _newkKings, _newMaxFlips); } /// Change various parameters function updateValue(uint256 _code, uint256 _newValue) public onlyOwner { if (_code == 1 ){ continentKing.length = _newValue; } else if (_code == 2 ){ allCountriesLength = _newValue; } else if (_code == 3 ){ freeRemainingLovesPerDay = _newValue; } emit NewValue(_code, _newValue, block.timestamp); } /// Store countries into continents - multi countries for 1 continent function function updateCountryToContinentMany(uint256[] _countryIds, uint256 _continentId) external onlyOwner { for (uint256 i = 0; i < _countryIds.length; i++) { updateCountryToContinent(_countryIds[i], _continentId); } } /// Store countries into continents - 1 country for 1 continent function function updateCountryToContinent(uint256 _countryId, uint256 _continentId) public onlyOwner { require(_countryId < allCountriesLength); require(_continentId < continentKing.length); countryToContinent[_countryId] = _continentId; emit NewCountryToContinent(_countryId, _continentId, block.timestamp); } /// If needed, update the external Trophy Cards contract address function updateTCContract(address _newAddress) public onlyOwner() { contractTrophyCards = _newAddress; SCTrophy = SuperCountriesTrophyCardsExternal(_newAddress); emit NewContractAddress(_newAddress); } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////// /// WIN THE JACKPOT FUNCTIONS /// ///////////////////////////////// function jackpotShareDispatch( address _winner, uint256 _share, uint256 _customValue, bytes32 _customText ) internal returns (uint256 shareDispatched_) { if (_winner == 0){ _winner = owner; } uint256 potDispatched = _share; winnersJackpot[gameVersion][_winner] += _share; emit JackpotDispatch(_winner, _share, _customValue, _customText); return potDispatched; } /// Internal jackpot function for Country Owners /// function jackpotCountryReward(uint256 _countryPot) internal returns (uint256 winningCountry_, uint256 dispatched_){ /// Is there a last standing country or not? uint256 potDispatched; if (howManyStandingOrNot(true) == 1){ /// There is only one country left: the winning country is the last standing country /// And the owner of this country will not share the countryPot with other owners, all is for him! uint256 winningCountryId = lastStanding(); address tempWinner = newOwner[winningCountryId]; potDispatched = jackpotShareDispatch(tempWinner, _countryPot, winningCountryId, "lastOwner"); } else { /// if else, there is more than one country standing, /// we will reward the standing countries of the last nuked country continent winningCountryId = lastNukedCountry; uint256 continentId = countryToContinent[winningCountryId]; uint256[] memory standingNations = country_getAllStandingCountriesForContinent(continentId, true); uint256 howManyCountries = standingNations.length; /// If there is at least one standing country in this continent if (howManyCountries > 0) { uint256 winningCounter; uint256 countryPotForOne = _countryPot.div(howManyCountries); for (uint256 i = 0; i < howManyCountries && potDispatched <= _countryPot; i++) { uint256 tempCountry = standingNations[i]; /// Get the current owner tempWinner = newOwner[tempCountry]; potDispatched += jackpotShareDispatch(tempWinner, countryPotForOne, tempCountry, "anOwner"); winningCounter++; if (winningCounter == howManyCountries || potDispatched.add(countryPotForOne) > _countryPot){ break; } } } /// There is no standing country in this continent, the owner of the last nuked country wins the jackpot (owner's share) else { tempWinner = newOwner[winningCountryId]; potDispatched = jackpotShareDispatch(tempWinner, _countryPot, winningCountryId, "lastNukedOwner"); } } return (winningCountryId, potDispatched); } /// PUBLIC JACKPOT FUNCTION TO CALL TO SHARE THE JACKPOT /// After the jackpot, anyone can call the jackpotWIN function, it will dispatch prizes between winners function jackpotWIN() public onlyGameNOTPaused { require(block.timestamp > jackpotTimestamp); /// True if latestPayer + 7 days or Only one country standing require(address(this).balance >= 1e11); require(thisJackpotIsPlayedAndNotWon[gameVersion]); /// if true, we are currently playing this jackpot and it's not won yet uint256 gameId = gameVersion; /// Pause the game gameRunning = false; /////////////////////////////////////////////// ////////// How much for the winners? ////////// /////////////////////////////////////////////// /// Calculate shares (uint256 nukerPot, uint256 countryPot, uint256 continentPot, uint256 freePot, uint256 pot,) = calculateJackpot(); /// This jackpot is won, disable it /// If false, this function will not be callable again thisJackpotIsPlayedAndNotWon[gameId] = false; //////////////////////////////////////////////////// ////////// Which country won the jackpot? ////////// //////////////////////////////////////////////////// /// Dispatch shares between country owners and save the winning country /// (uint256 winningCountryId, uint256 potDispatched) = jackpotCountryReward(countryPot); winningCountry[gameId] = winningCountryId; uint256 continentId = countryToContinent[winningCountryId]; //////////////////////////////////////////////// ////////// Who are the other winners? ////////// //////////////////////////////////////////////// /// The king of the right continent potDispatched += jackpotShareDispatch(continentKing[continentId], continentPot, continentId, "continent"); /// The best lover for this country potDispatched += jackpotShareDispatch(loversSTR[gameId][winningCountryId].bestLover, freePot, 0, "free"); /// The last nuker potDispatched += jackpotShareDispatch(nukerAddress[winningCountryId], nukerPot, 0, "nuker"); /// Emit the events /// emit JackpotDispatchAll(gameId, winningCountryId, continentId, block.timestamp, jackpotTimestamp, pot, potDispatched, address(this).balance); emit PausedOrUnpaused(block.timestamp, gameRunning); /// Last check /// assert(potDispatched <= address(this).balance); } /// After the sharing, all winners will be able to call this function to withdraw the won share to the their wallets function withdrawWinners() public onlyRealAddress { require(winnersJackpot[gameVersion][msg.sender] > 0); address _winnerAddress = msg.sender; uint256 gameId = gameVersion; /// Prepare for the withdrawal uint256 jackpotToTransfer = winnersJackpot[gameId][_winnerAddress]; winnersJackpot[gameId][_winnerAddress] = 0; /// fire event emit WithdrawJackpot(_winnerAddress, jackpotToTransfer, gameId); /// Withdraw _winnerAddress.transfer(jackpotToTransfer); } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////// /// RESTART A NEW GAME /// /////////////////////////////// /// After the jackpot, restart a new game with same settings /// /// The owner can restart 2 hrs after the jackpot /// If the owner doesn't restart the game 30 days after the jackpot, all players can restart the game function restartNewGame() public onlyGamePaused{ require((msg.sender == owner && block.timestamp > jackpotTimestamp.add(DSHORT)) || block.timestamp > jackpotTimestamp.add(2629000)); uint256 timestampNow = block.timestamp; /// Clear all values, loves, nextPrices... but bestlovers, lovers will remain if (nextPrice[gameVersion] !=0){ gameVersion++; lastNukedCountry = 0; howManyNuked = 0; howManyReactivated = 0; howManyEliminated = 0; lastNukerMin = 0; countryOwnerMin = 0; continentMin = 0; freePlayerMin = 0; withdrawMinOwner = 0; kingPrice = 1e16; newOwner.length = 0; nukerAddress.length = 0; newOwner.length = allCountriesLength; nukerAddress.length = allCountriesLength; } /// Set new jackpot timestamp updateJackpotTimestamp(timestampNow); /// Restart gameRunning = true; thisJackpotIsPlayedAndNotWon[gameVersion] = true; /// fire event emit NewGameLaunched(gameVersion, timestampNow, msg.sender, jackpotTimestamp); emit PausedOrUnpaused(block.timestamp, gameRunning); } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////// /// USEFUL FUNCTIONS /// //////////////////////// /** * @dev Fallback function to accept all ether sent directly to the contract * Nothing is lost, it will raise the jackpot! */ function() payable public { } /// After the jackpot, the owner can restart a new game or withdraw if winners don't want their part function withdraw() public onlyOwner { require(block.timestamp > jackpotTimestamp.add(DSHORT) || address(this).balance <= 1e11 || whatDevCanWithdraw() > 0); uint256 thisBalance = address(this).balance; if (block.timestamp > jackpotTimestamp.add(DSHORT) || thisBalance <= 1e11 ){ uint256 toWithdraw = thisBalance; } else { toWithdraw = whatDevCanWithdraw(); withdrawMinOwner += toWithdraw; } emit WithdrawByDev(block.timestamp, toWithdraw, withdrawMinOwner, thisBalance); owner.transfer(toWithdraw); } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////// /// LAST STANDING FUNCTIONS /// /////////////////////////////// function trueStandingFalseEliminated(bool _standing) public view returns (uint256[] countries_) { uint256 howLong = howManyStandingOrNot(_standing); uint256[] memory countries = new uint256[](howLong); uint256 standingCounter = 0; uint256 gameId = gameVersion; for (uint256 i = 0; i < allCountriesLength; i++) { if (eliminated[gameId][i] != _standing){ countries[standingCounter] = i; standingCounter++; } if (standingCounter == howLong){break;} } return countries; } function howManyStandingOrNot(bool _standing) public view returns (uint256 howManyCountries_) { uint256 standingCounter = 0; uint256 gameId = gameVersion; for (uint256 i = 0; i < allCountriesLength; i++) { if (eliminated[gameId][i] != _standing){ standingCounter++; } } return standingCounter; } function lastStanding() public view returns (uint256 lastStandingNation_) { require (howManyStandingOrNot(true) == 1); return trueStandingFalseEliminated(true)[0]; } }
contract SuperCountriesWar { using SafeMath for uint256; //////////////////////////// /// CONSTRUCTOR /// //////////////////////////// constructor () public { owner = msg.sender; continentKing.length = 16; newOwner.length = 256; nukerAddress.length = 256; } address public owner; //////////////////////////////// /// USEFUL MODIFIERS /// //////////////////////////////// /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner == msg.sender); _; } /** * @dev Throws if called by address 0x0 */ modifier onlyRealAddress() { require(msg.sender != address(0)); _; } /** * @dev Can only be called when a game is running / unpaused */ modifier onlyGameNOTPaused() { require(gameRunning == true); _; } /** * @dev Can only be called when a game is paused / ended */ modifier onlyGamePaused() { require(gameRunning == false); _; } /////////////////////////////////////// /// TROPHY CARDS FUNCTIONS /// /////////////////////////////////////// ///Update the index of the next trophy card to get dividends, after each buy a new card will get divs function nextTrophyCardUpdateAndGetOwner() internal returns (address){ uint256 cardsLength = getTrophyCount(); address trophyCardOwner; if (nextTrophyCardToGetDivs < cardsLength){ uint256 nextCard = getTrophyFromIndex(nextTrophyCardToGetDivs); trophyCardOwner = getCountryOwner(nextCard); } /// Update for next time if (nextTrophyCardToGetDivs.add(1) < cardsLength){ nextTrophyCardToGetDivs++; } else nextTrophyCardToGetDivs = 0; return trophyCardOwner; } /// Get the address of the owner of the "next trophy card to get divs" function getNextTrophyCardOwner() public view returns ( address nextTrophyCardOwner_, uint256 nextTrophyCardIndex_, uint256 nextTrophyCardId_ ) { uint256 cardsLength = getTrophyCount(); address trophyCardOwner; if (nextTrophyCardToGetDivs < cardsLength){ uint256 nextCard = getTrophyFromIndex(nextTrophyCardToGetDivs); trophyCardOwner = getCountryOwner(nextCard); } return ( trophyCardOwner, nextTrophyCardToGetDivs, nextCard ); } //////////////////////////////////////////////////////// /// CALL OF OTHER SUPERCOUNTRIES CONTRACTS /// //////////////////////////////////////////////////////// /// EXTERNAL VALUES address private contractSC = 0xdf203118A954c918b967a94E51f3570a2FAbA4Ac; /// SuperCountries Original game address private contractTrophyCards = 0xEaf763328604e6e54159aba7bF1394f2FbcC016e; /// SuperCountries Trophy Cards SuperCountriesExternal SC = SuperCountriesExternal(contractSC); SuperCountriesTrophyCardsExternal SCTrophy = SuperCountriesTrophyCardsExternal(contractTrophyCards); //////////////////////////////////////////////////// /// GET FUNCTIONS FROM EXTERNAL CONTRACTS /// //////////////////////////////////////////////////// /// SuperCountries Original function getCountryOwner(uint256 _countryId) public view returns (address){ return SC.ownerOf(_countryId); } /// SuperCountries Original function getPriceOfCountry(uint256 _countryId) public view returns (uint256){ return SC.priceOf(_countryId); } /// SuperCountries Trophy Cards function getTrophyFromIndex(uint256 _index) public view returns (uint256){ return SCTrophy.getTrophyCardIdFromIndex(_index); } /// SuperCountries Trophy Cards function getTrophyCount() public view returns (uint256){ return SCTrophy.countTrophyCards(); } //////////////////////////////////////// /// VARIABLES & MAPPINGS /// //////////////////////////////////////// /// Game enabled? bool private gameRunning; uint256 private gameVersion = 1; /// game Id /// Dates & timestamps uint256 private jackpotTimestamp; /// if this timestamp is reached, the jackpot can be shared mapping(uint256 => bool) private thisJackpotIsPlayedAndNotWon; /// true if currently played and not won, false if already won or not yet played /// *** J A C K P O T *** /// /// Unwithdrawn jackpot per winner mapping(uint256 => mapping(address => uint256)) private winnersJackpot; mapping(uint256 => uint256) private winningCountry; /// List of winning countries /// Payable functions prices: nuke a country, become a king /// uint256 private startingPrice = 1e16; /// ETHER /// First raw price to nuke a country /// nuke = nextPrice (or startingPrice) + kCountry*LastKnownCountryPrice mapping(uint256 => uint256) private nextPrice; /// ETHER /// Current raw price to nuke a country /// nuke = nextPrice + kCountry*LastKnownCountryPrice uint256 private kingPrice = 9e15; /// ETHER /// Current king price /// Factors /// uint256 private kCountry = 4; /// PERCENTS /// nuke = nextPrice + kCountry*LastKnownCountryPrice (4 = 4%) uint256 private kCountryLimit = 5e17; /// ETHER /// kCountry * lastKnownPrice cannot exceed this limit uint256 private kNext = 1037; /// PERTHOUSAND /// price increase after each nuke (1037 = 3.7% increase) uint256 private maxFlips = 16; /// king price will increase after maxFlips kings uint256 private continentFlips; /// Current kings flips uint256 private kKings = 101; /// king price increase (101 = 1% increase) /// Kings // address[] private continentKing; /// Nukers /// address[] private nukerAddress; /// Lovers /// struct LoverStructure { mapping(uint256 => mapping(address => uint256)) loves; /// howManyNuked => lover address => number of loves mapping(uint256 => uint256) maxLoves; /// highest number of loves for this country address bestLover; /// current best lover for this country (highest number of loves) } mapping(uint256 => mapping(uint256 => LoverStructure)) private loversSTR; /// GameVersion > CountryId > LoverStructure uint256 private mostLovedCountry; /// The mostLovedCountry cannot be nuked if > 4 countries on the map mapping(address => uint256) private firstLove; /// timestamp for loves mapping(address => uint256) private remainingLoves; /// remaining loves for today uint256 private freeRemainingLovesPerDay = 2; /// Number of free loves per day sub 1 /// Cuts in perthousand /// the rest = potCut uint256 private devCut = 280; /// Including riddles and medals rewards uint256 private playerCut = 20; /// trophy card, best lover & country owner uint256 private potCutSuperCountries = 185; /// Jackpot redistribution /// 10 000 = 100% uint256 private lastNukerShare = 5000; uint256 private winningCountryShare = 4400; /// if 1 country stands, the current owner takes it all, otherwise shared between owners of remaining countries (of the winning continent) uint256 private continentShare = 450; uint256 private freePlayerShare = 150; /// Minimal jackpot guarantee /// Initial funding by SuperCountries uint256 private lastNukerMin = 3e18; /// 3 ethers uint256 private countryOwnerMin = 3e18; /// 3 ethers uint256 private continentMin = 1e18; /// 1 ether uint256 private freePlayerMin = 1e18; /// 1 ether uint256 private withdrawMinOwner; /// Dev can withdraw his initial funding if the jackpot equals this value. /// Trophy cards uint256 private nextTrophyCardToGetDivs; /// returns next trophy card INDEX to get dividends /// Countries /// uint256 private allCountriesLength = 256; /// how many countries mapping(uint256 => mapping(uint256 => bool)) private eliminated; /// is this country eliminated? gameVersion > countryId > bool uint256 private howManyEliminated; /// how many eliminated countries uint256 private howManyNuked; /// how many nuked countries uint256 private howManyReactivated; /// players are allowed to reactivate 1 country for 8 nukes uint256 private lastNukedCountry; /// last nuked country ID mapping(uint256 => uint256) lastKnownCountryPrice; /// address[] private newOwner; /// Latest known country owners /// A new buyer must send at least one love or reanimate its country to be in the array /// Continents /// mapping(uint256 => uint256) private countryToContinent; /// country Id to Continent Id /// Time (seconds) /// uint256 public SLONG = 86400; /// 1 day uint256 public DLONG = 172800; /// 2 days uint256 public DSHORT = 14400; /// 4 hrs //////////////////////// /// EVENTS /// //////////////////////// /// Pause / UnPause event PausedOrUnpaused(uint256 indexed blockTimestamp_, bool indexed gameRunning_); /// New Game /// event NewGameLaunched(uint256 indexed gameVersion_, uint256 indexed blockTimestamp_, address indexed msgSender_, uint256 jackpotTimestamp_); event ErrorCountry(uint256 indexed countryId_); /// Updates /// event CutsUpdated(uint256 indexed newDevcut_, uint256 newPlayercut_, uint256 newJackpotCountriescut_, uint256 indexed blockTimestamp_); event ConstantsUpdated(uint256 indexed newStartPrice_, uint256 indexed newkKingPrice_, uint256 newKNext_, uint256 newKCountry_, uint256 newKLimit_, uint256 newkKings, uint256 newMaxFlips); event NewContractAddress(address indexed newAddress_); event NewValue(uint256 indexed code_, uint256 indexed newValue_, uint256 indexed blockTimestamp_); event NewCountryToContinent(uint256 indexed countryId_, uint256 indexed continentId_, uint256 indexed blockTimestamp_); /// Players Events /// event PlayerEvent(uint256 indexed eventCode_, uint256 indexed countryId_, address indexed player_, uint256 timestampNow_, uint256 customValue_, uint256 gameId_); event Nuked(address indexed player_, uint256 indexed lastNukedCountry_, uint256 priceToPay_, uint256 priceRaw_); event Reactivation(uint256 indexed countryId_, uint256 indexed howManyReactivated_); event NewKingContinent(address indexed player_, uint256 indexed continentId_, uint256 priceToPay_); event newMostLovedCountry(uint256 indexed countryId_, uint256 indexed maxLovesBest_); event NewBestLover(address indexed lover_, uint256 indexed countryId_, uint256 maxLovesBest_); event NewLove(address indexed lover_, uint256 indexed countryId_, uint256 playerLoves_, uint256 indexed gameId_, uint256 nukeCount_); event LastCountryStanding(uint256 indexed countryId_, address indexed player_, uint256 contractBalance_, uint256 indexed gameId_, uint256 jackpotTimestamp); event ThereIsANewOwner(address indexed newOwner_, uint256 indexed countryId_); /// Payments /// event CutsPaidInfos(uint256 indexed blockTimestamp_, uint256 indexed countryId_, address countryOwner_, address trophyCardOwner_, address bestLover_); event CutsPaidValue(uint256 indexed blockTimestamp_, uint256 indexed paidPrice_, uint256 thisBalance_, uint256 devCut_, uint256 playerCut_, uint256 indexed SuperCountriesCut_); event CutsPaidLight(uint256 indexed blockTimestamp_, uint256 indexed paidPrice_, uint256 thisBalance_, uint256 devCut_, uint256 playerCut_, address trophyCardOwner_, uint256 indexed SuperCountriesCut_); event NewKingPrice(uint256 indexed kingPrice_, uint256 indexed kKings_); /// Jackpot & Withdraws /// event NewJackpotTimestamp(uint256 indexed jackpotTimestamp_, uint256 indexed timestamp_); event WithdrawByDev(uint256 indexed blockTimestamp_, uint256 indexed withdrawn_, uint256 indexed withdrawMinOwner_, uint256 jackpot_); event WithdrawJackpot(address indexed winnerAddress_, uint256 indexed jackpotToTransfer_, uint256 indexed gameVersion_); event JackpotDispatch(address indexed winner, uint256 indexed jackpotShare_, uint256 customValue_, bytes32 indexed customText_); event JackpotDispatchAll(uint256 indexed gameVersion_, uint256 indexed winningCountry_, uint256 indexed continentId_, uint256 timestampNow_, uint256 jackpotTimestamp_, uint256 pot_,uint256 potDispatched_, uint256 thisBalance); ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////// /// PUBLIC GET FUNCTIONS /// //////////////////////////// /// Checks if a player can nuke or be a king function canPlayTimestamp() public view returns (bool ok_){ uint256 timestampNow = block.timestamp; uint256 jT = jackpotTimestamp; bool canPlayTimestamp_; if (timestampNow < jT || timestampNow > jT.add(DSHORT)){ canPlayTimestamp_ = true; } return canPlayTimestamp_; } /// When eliminated, the country cannot be eliminated again unless someone rebuys this country function isEliminated(uint256 _countryId) public view returns (bool isEliminated_){ return eliminated[gameVersion][_countryId]; } /// The player can love few times a day (or more if loved yesterday) function canPlayerLove(address _player) public view returns (bool playerCanLove_){ if (firstLove[_player].add(SLONG) > block.timestamp && remainingLoves[_player] == 0){ bool canLove = false; } else canLove = true; return canLove; } /// To reanimate a country, a player must rebuy it first on the marketplace then click the reanima button /// Reanimations are limited: 1 allowed for 8 nukes ; disallowed if only 8 countries on the map function canPlayerReanimate( uint256 _countryId, address _player ) public view returns (bool canReanimate_) { if ( (lastKnownCountryPrice[_countryId] < getPriceOfCountry(_countryId)) && (isEliminated(_countryId) == true) && (_countryId != lastNukedCountry) && (block.timestamp.add(SLONG) < jackpotTimestamp || block.timestamp > jackpotTimestamp.add(DSHORT)) && (allCountriesLength.sub(howManyEliminated) > 8) && /// If only 8 countries left, no more reactivation allowed even if other requires could allow ((howManyReactivated.add(1)).mul(8) < howManyNuked) && /// 1 reactivation for 8 Nukes (lastKnownCountryPrice[_countryId] > 0) && (_player == getCountryOwner(_countryId)) ) { bool canReanima = true; } else canReanima = false; return canReanima; } /// Get the current gameVersion function constant_getGameVersion() public view returns (uint256 currentGameVersion_){ return gameVersion; } /// Returns some useful informations for a country function country_getInfoForCountry(uint256 _countryId) public view returns ( bool eliminatedBool_, uint256 whichContinent_, address currentBestLover_, uint256 maxLovesForTheBest_, address countryOwner_, uint256 lastKnownPrice_ ) { LoverStructure storage c = loversSTR[gameVersion][_countryId]; if (eliminated[gameVersion][_countryId]){uint256 nukecount = howManyNuked.sub(1);} else nukecount = howManyNuked; return ( eliminated[gameVersion][_countryId], countryToContinent[_countryId], c.bestLover, c.maxLoves[nukecount], newOwner[_countryId], lastKnownCountryPrice[_countryId] ); } /// Returns the number of loves function loves_getLoves(uint256 _countryId, address _player) public view returns (uint256 loves_) { LoverStructure storage c = loversSTR[gameVersion][_countryId]; return c.loves[howManyNuked][_player]; } /// Returns the number of loves of a player for a country for an old gameId for howManyNukedId (loves reset after each nuke) function loves_getOldLoves( uint256 _countryId, address _player, uint256 _gameId, uint256 _oldHowManyNuked ) public view returns (uint256 loves_) { return loversSTR[_gameId][_countryId].loves[_oldHowManyNuked][_player]; } /// Calculate how many loves left for a player for today function loves_getPlayerInfo(address _player) public view returns ( uint256 playerFirstLove_, uint256 playerRemainingLoves_, uint256 realRemainingLoves_ ) { uint256 timestampNow = block.timestamp; uint256 firstLoveAdd24 = firstLove[_player].add(SLONG); uint256 firstLoveAdd48 = firstLove[_player].add(DLONG); uint256 remainStored = remainingLoves[_player]; /// This player loved today but has some loves left, remainingLoves are correct if (firstLoveAdd24 > timestampNow && remainStored > 0){ uint256 remainReal = remainStored; } /// This player loved yesterday but not today, he can love "howManyEliminated.div(4)" + "freeRemainingLovesPerDay + 1" times today else if (firstLoveAdd24 < timestampNow && firstLoveAdd48 > timestampNow){ remainReal = (howManyEliminated.div(4)).add(freeRemainingLovesPerDay).add(1); } /// This player didn't love for 48h, he can love "freeRemainingLovesPerDay + 1" today else if (firstLoveAdd48 < timestampNow){ remainReal = freeRemainingLovesPerDay.add(1); } else remainReal = 0; return ( firstLove[_player], remainStored, remainReal ); } /// Returns the unwithdrawn jackpot of a player for a GameId function player_getPlayerJackpot( address _player, uint256 _gameId ) public view returns ( uint256 playerNowPot_, uint256 playerOldPot_ ) { return ( winnersJackpot[gameVersion][_player], winnersJackpot[_gameId][_player] ); } /// Returns informations for a country for previous games function country_getOldInfoForCountry(uint256 _countryId, uint256 _gameId) public view returns ( bool oldEliminatedBool_, uint256 oldMaxLovesForTheBest_ ) { LoverStructure storage c = loversSTR[_gameId][_countryId]; return ( eliminated[_gameId][_countryId], c.maxLoves[howManyNuked] ); } /// Returns informations for a country for previous games requiring more parameters function loves_getOldNukesMaxLoves( uint256 _countryId, uint256 _gameId, uint256 _howManyNuked ) public view returns (uint256 oldMaxLovesForTheBest2_) { return (loversSTR[_gameId][_countryId].maxLoves[_howManyNuked]); } /// Returns other informations for a country for previous games function country_getCountriesGeneralInfo() public view returns ( uint256 lastNuked_, address lastNukerAddress_, uint256 allCountriesLength_, uint256 howManyEliminated_, uint256 howManyNuked_, uint256 howManyReactivated_, uint256 mostLovedNation_ ) { return ( lastNukedCountry, nukerAddress[lastNukedCountry], allCountriesLength, howManyEliminated, howManyNuked, howManyReactivated, mostLovedCountry ); } /// Get the address of the king for a continent function player_getKingOne(uint256 _continentId) public view returns (address king_) { return continentKing[_continentId]; } /// Return all kings function player_getKingsAll() public view returns (address[] _kings) { uint256 kingsLength = continentKing.length; address[] memory kings = new address[](kingsLength); uint256 kingsCounter = 0; for (uint256 i = 0; i < kingsLength; i++) { kings[kingsCounter] = continentKing[i]; kingsCounter++; } return kings; } /// Return lengths of arrays function constant_getLength() public view returns ( uint256 kingsLength_, uint256 newOwnerLength_, uint256 nukerLength_ ) { return ( continentKing.length, newOwner.length, nukerAddress.length ); } /// Return the nuker's address - If a country was nuked twice (for example after a reanimation), we store the last nuker only function player_getNuker(uint256 _countryId) public view returns (address nuker_) { return nukerAddress[_countryId]; } /// How many countries were nuked by a player? /// Warning: if a country was nuked twice (for example after a reanimation), only the last nuker counts function player_howManyNuked(address _player) public view returns (uint256 nukeCount_) { uint256 counter = 0; for (uint256 i = 0; i < nukerAddress.length; i++) { if (nukerAddress[i] == _player) { counter++; } } return counter; } /// Which countries were nuked by a player? function player_getNukedCountries(address _player) public view returns (uint256[] myNukedCountriesIds_) { uint256 howLong = player_howManyNuked(_player); uint256[] memory myNukedCountries = new uint256[](howLong); uint256 nukeCounter = 0; for (uint256 i = 0; i < allCountriesLength; i++) { if (nukerAddress[i] == _player){ myNukedCountries[nukeCounter] = i; nukeCounter++; } if (nukeCounter == howLong){break;} } return myNukedCountries; } /// Which percentage of the jackpot will the winners share? function constant_getPriZZZes() public view returns ( uint256 lastNukeShare_, uint256 countryOwnShare_, uint256 contintShare_, uint256 freePlayerShare_ ) { return ( lastNukerShare, winningCountryShare, continentShare, freePlayerShare ); } /// Returns the minimal jackpot part for each winner (if accurate) /// Only accurate for the first game. If new games are started later, these values will be set to 0 function constant_getPriZZZesMini() public view returns ( uint256 lastNukeMini_, uint256 countryOwnMini_, uint256 contintMini_, uint256 freePlayerMini_, uint256 withdrMinOwner_ ) { return ( lastNukerMin, countryOwnerMin, continentMin, freePlayerMin, withdrawMinOwner ); } /// Returns some values for the current game function constant_getPrices() public view returns ( uint256 nextPrice_, uint256 startingPrice_, uint256 kingPrice_, uint256 kNext_, uint256 kCountry_, uint256 kCountryLimit_, uint256 kKings_) { return ( nextPrice[gameVersion], startingPrice, kingPrice, kNext, kCountry, kCountryLimit, kKings ); } /// Returns other values for the current game function constant_getSomeDetails() public view returns ( bool gameRunng_, uint256 currentContractBalance_, uint256 jackptTimstmp_, uint256 maxFlip_, uint256 continentFlip_, bool jackpotNotWonYet_) { return ( gameRunning, address(this).balance, jackpotTimestamp, maxFlips, continentFlips, thisJackpotIsPlayedAndNotWon[gameVersion] ); } /// Returns some values for previous games function constant_getOldDetails(uint256 _gameId) public view returns ( uint256 oldWinningCountry_, bool oldJackpotBool_, uint256 oldNextPrice_ ) { return ( winningCountry[_gameId], thisJackpotIsPlayedAndNotWon[_gameId], nextPrice[_gameId] ); } /// Returns cuts function constant_getCuts() public view returns ( uint256 playerCut_, uint256 potCutSC, uint256 developerCut_) { return ( playerCut, potCutSuperCountries, devCut ); } /// Returns linked contracts addresses: SuperCountries core contract, Trophy Cards Contract function constant_getContracts() public view returns (address SuperCountries_, address TrophyCards_) { return (contractSC, contractTrophyCards); } /// Calculates the raw price of a next nuke /// This value will be used to calculate a nuke price for a specified country depending of its market price function war_getNextNukePriceRaw() public view returns (uint256 price_) { if (nextPrice[gameVersion] != 0) { uint256 price = nextPrice[gameVersion]; } else price = startingPrice; return price; } <FILL_FUNCTION> /// Returns all countries for a continent function country_getAllCountriesForContinent(uint256 _continentId) public view returns (uint256[] countries_) { uint256 howManyCountries = country_countCountriesForContinent(_continentId); uint256[] memory countries = new uint256[](howManyCountries); uint256 countryCounter = 0; for (uint256 i = 0; i < allCountriesLength; i++) { if (countryToContinent[i] == _continentId){ countries[countryCounter] = i; countryCounter++; } if (countryCounter == howManyCountries){break;} } return countries; } /// Count all countries for a continent (standing and non standing) function country_countCountriesForContinent(uint256 _continentId) public view returns (uint256 howManyCountries_) { uint256 countryCounter = 0; for (uint256 i = 0; i < allCountriesLength; i++) { if (countryToContinent[i] == _continentId){ countryCounter++; } } return countryCounter; } /// Return the ID of all STANDING countries for a continent (or not Standing if FALSE) function country_getAllStandingCountriesForContinent( uint256 _continentId, bool _standing ) public view returns (uint256[] countries_) { uint256 howManyCountries = country_countStandingCountriesForContinent(_continentId, _standing); uint256[] memory countries = new uint256[](howManyCountries); uint256 countryCounter = 0; uint256 gameId = gameVersion; for (uint256 i = 0; i < allCountriesLength; i++) { if (countryToContinent[i] == _continentId && eliminated[gameId][i] != _standing){ countries[countryCounter] = i; countryCounter++; } if (countryCounter == howManyCountries){break;} } return countries; } /// Count all STANDING countries for a continent (or not Standing if FALSE) function country_countStandingCountriesForContinent( uint256 _continentId, bool _standing ) public view returns (uint256 howManyCountries_) { uint256 standingCountryCounter = 0; uint256 gameId = gameVersion; for (uint256 i = 0; i < allCountriesLength; i++) { if (countryToContinent[i] == _continentId && eliminated[gameId][i] != _standing){ standingCountryCounter++; } } return standingCountryCounter; } /// Calculate the jackpot to share between all winners /// realJackpot: the real value to use when sharing /// expected: this is the jackpot as we should expect if there was no minimal guarantee. It can be different from the real one if we have not reached the minimal value yet. /// WARNING: between the real and the expected, the REAL one is the only value to use ; the expected one is for information only and will never be used in any calculation function calculateJackpot() public view returns ( uint256 nukerJackpot_, uint256 countryJackpot_, uint256 continentJackpot_, uint256 freeJackpot_, uint256 realJackpot_, uint256 expectedJackpot_ ) { /// If thisJackpot = false, that would mean it was already won or not yet played, /// if true it's currently played and not won yet if (thisJackpotIsPlayedAndNotWon[gameVersion] != true) { uint256 nukerJPT = 0; uint256 countryJPT = 0; uint256 continentJPT = 0; uint256 freeJPT = 0; uint256 realJackpotToShare = 0; uint256 expectedJackpotFromRates = 0; } else { uint256 devGift = lastNukerMin.add(countryOwnerMin).add(continentMin).add(freePlayerMin); expectedJackpotFromRates = ((address(this).balance).add(withdrawMinOwner).sub(devGift)).div(10000); uint256 temp_share = expectedJackpotFromRates.mul(lastNukerShare); if (temp_share > lastNukerMin){ nukerJPT = temp_share; } else nukerJPT = lastNukerMin; temp_share = expectedJackpotFromRates.mul(winningCountryShare); if (temp_share > countryOwnerMin){ countryJPT = temp_share; } else countryJPT = countryOwnerMin; temp_share = expectedJackpotFromRates.mul(continentShare); if (temp_share > continentMin){ continentJPT = temp_share; } else continentJPT = continentMin; temp_share = expectedJackpotFromRates.mul(freePlayerShare); if (temp_share > freePlayerMin){ freeJPT = temp_share; } else freeJPT = freePlayerMin; realJackpotToShare = nukerJPT.add(countryJPT).add(continentJPT).add(freeJPT); } return ( nukerJPT, countryJPT, continentJPT, freeJPT, realJackpotToShare, expectedJackpotFromRates.mul(10000) ); } /// Calculate how much the dev can withdraw now /// If the dev funded a minimal guarantee, he can withdraw gradually its funding when jackpot rises up to its funding amount function whatDevCanWithdraw() public view returns(uint256 toWithdrawByDev_){ uint256 devGift = lastNukerMin.add(countryOwnerMin).add(continentMin).add(freePlayerMin); uint256 balance = address(this).balance; (,,,,uint256 jackpotToDispatch,) = calculateJackpot(); uint256 leftToWithdraw = devGift.sub(withdrawMinOwner); uint256 leftInTheContract = balance.sub(jackpotToDispatch); if (leftToWithdraw > 0 && balance > jackpotToDispatch){ /// ok he can still withdraw if (leftInTheContract > leftToWithdraw){ uint256 devToWithdraw = leftToWithdraw; } else devToWithdraw = leftInTheContract; } return devToWithdraw; } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////// /// INTERNAL FUNCTIONS /// ////////////////////////// /// Heavy pay function for Nukes /// function payCuts( uint256 _value, uint256 _balance, uint256 _countryId, uint256 _timestamp ) internal { require(_value <= _balance); require(_value != 0); /// Get the next trophy card owner to send cuts address nextTrophyOwner = nextTrophyCardUpdateAndGetOwner(); if (nextTrophyOwner == 0) { nextTrophyOwner = owner; } /// Get the country owner to send cuts address countryOwner = newOwner[_countryId]; if (countryOwner == 0) { countryOwner = owner; } /// Get the best lover to send cuts address bestLoverToGetDivs = loversSTR[gameVersion][_countryId].bestLover; if (bestLoverToGetDivs == 0) { bestLoverToGetDivs = owner; } /// Calculate cuts uint256 devCutPay = _value.mul(devCut).div(1000); uint256 superCountriesPotCutPay = _value.mul(potCutSuperCountries).div(1000); uint256 trophyAndOwnerCutPay = _value.mul(playerCut).div(1000); /// Pay cuts /// owner.transfer(devCutPay); contractSC.transfer(superCountriesPotCutPay); nextTrophyOwner.transfer(trophyAndOwnerCutPay); countryOwner.transfer(trophyAndOwnerCutPay); bestLoverToGetDivs.transfer(trophyAndOwnerCutPay); emit CutsPaidInfos(_timestamp, _countryId, countryOwner, nextTrophyOwner, bestLoverToGetDivs); emit CutsPaidValue(_timestamp, _value, address(this).balance, devCutPay, trophyAndOwnerCutPay, superCountriesPotCutPay); assert(_balance.sub(_value) <= address(this).balance); assert((trophyAndOwnerCutPay.mul(3).add(devCutPay).add(superCountriesPotCutPay)) < _value); } /// Light pay function for Kings /// function payCutsLight( uint256 _value, uint256 _balance, uint256 _timestamp ) internal { require(_value <= _balance); require(_value != 0); /// Get the next trophy card owner to send cuts address nextTrophyOwner = nextTrophyCardUpdateAndGetOwner(); if (nextTrophyOwner == 0) { nextTrophyOwner = owner; } /// Get the last nuker to send cuts address lastNuker = nukerAddress[lastNukedCountry]; if (lastNuker == 0) { lastNuker = owner; } /// Calculate cuts uint256 trophyCutPay = _value.mul(playerCut).div(1000); uint256 superCountriesPotCutPay = ((_value.mul(potCutSuperCountries).div(1000)).add(trophyCutPay)).div(2); /// Divide by 2: one part for SCPot, one for lastNuker uint256 devCutPay = (_value.mul(devCut).div(1000)).add(trophyCutPay); /// Pay cuts /// owner.transfer(devCutPay); contractSC.transfer(superCountriesPotCutPay); lastNuker.transfer(superCountriesPotCutPay); nextTrophyOwner.transfer(trophyCutPay); emit CutsPaidLight(_timestamp, _value, address(this).balance, devCutPay, trophyCutPay, nextTrophyOwner, superCountriesPotCutPay); assert(_balance.sub(_value) <= address(this).balance); assert((trophyCutPay.add(devCutPay).add(superCountriesPotCutPay)) < _value); } /// Refund the nuker / new king if excess function excessRefund( address _payer, uint256 _priceToPay, uint256 paidPrice ) internal { uint256 excess = paidPrice.sub(_priceToPay); if (excess > 0) { _payer.transfer(excess); } } /// Update the jackpot timestamp each time a country is nuked or a new king crowned function updateJackpotTimestamp(uint256 _timestamp) internal { jackpotTimestamp = _timestamp.add(604800); /// 1 week emit NewJackpotTimestamp(jackpotTimestamp, _timestamp); } /// If first love > 24h, the player can love again /// and get extra loves if loved yesterday function updateLovesForToday(address _player, uint256 _timestampNow) internal { uint256 firstLoveAdd24 = firstLove[_player].add(SLONG); uint256 firstLoveAdd48 = firstLove[_player].add(DLONG); uint256 remainV = remainingLoves[_player]; /// This player loved today but has some loves left if (firstLoveAdd24 > _timestampNow && remainV > 0){ remainingLoves[_player] = remainV.sub(1); } /// This player loved yesterday but not today else if (firstLoveAdd24 < _timestampNow && firstLoveAdd48 > _timestampNow){ remainingLoves[_player] = (howManyEliminated.div(4)).add(freeRemainingLovesPerDay); firstLove[_player] = _timestampNow; } /// This player didn't love for 48h, he can love today else if (firstLoveAdd48 < _timestampNow){ remainingLoves[_player] = freeRemainingLovesPerDay; firstLove[_player] = _timestampNow; } /// This player is a zombie else remainingLoves[_player] = 0; } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////// /// WAR - PUBLIC FUNCTIONS /// //////////////////////////////////// ////////////////////// /// NUKE A COUNTRY /// ////////////////////// function nuke(uint256 _countryId) payable public onlyGameNOTPaused{ require(_countryId < allCountriesLength); require(msg.value >= war_getNextNukePriceForCountry(_countryId)); require(war_getNextNukePriceForCountry(_countryId) > 0); require(isEliminated(_countryId) == false); require(canPlayTimestamp()); /// Impossible to nuke 2 hours after the jackpot require(loversSTR[gameVersion][_countryId].bestLover != msg.sender); /// The best lover cannot nuke his favorite country require(_countryId != mostLovedCountry || allCountriesLength.sub(howManyEliminated) < 5); /// We cannot nuke the mostLovedCountry if more than 4 countries stand address player = msg.sender; uint256 timestampNow = block.timestamp; uint256 gameId = gameVersion; uint256 thisBalance = address(this).balance; uint256 priceToPay = war_getNextNukePriceForCountry(_countryId); /// Update the latest nuker of the game in the nukerAddress array nukerAddress[_countryId] = player; /// Get last known price of this country for next time uint256 lastPriceOld = lastKnownCountryPrice[_countryId]; lastKnownCountryPrice[_countryId] = getPriceOfCountry(_countryId); /// Change the activation of this country eliminated[gameId][_countryId] = true; howManyEliminated++; if (howManyEliminated.add(1) == allCountriesLength){ jackpotTimestamp = block.timestamp; emit LastCountryStanding(_countryId, player, thisBalance, gameId, jackpotTimestamp); } else { /// Update next price uint priceRaw = war_getNextNukePriceRaw(); nextPrice[gameId] = priceRaw.mul(kNext).div(1000); /// and update the jackpot updateJackpotTimestamp(timestampNow); } lastNukedCountry = _countryId; payCuts(priceToPay, thisBalance, _countryId, timestampNow); excessRefund(player, priceToPay, msg.value); howManyNuked++; /// emit the event emit Nuked(player, _countryId, priceToPay, priceRaw); emit PlayerEvent(1, _countryId, player, timestampNow, howManyEliminated, gameId); assert(lastKnownCountryPrice[_countryId] >= lastPriceOld); } /////////////////////////// /// REANIMATE A COUNTRY /// /////////////////////////// function reanimateCountry(uint256 _countryId) public onlyGameNOTPaused{ require(canPlayerReanimate(_countryId, msg.sender) == true); address player = msg.sender; eliminated[gameVersion][_countryId] = false; newOwner[_countryId] = player; howManyEliminated = howManyEliminated.sub(1); howManyReactivated++; emit Reactivation(_countryId, howManyReactivated); emit PlayerEvent(2, _countryId, player, block.timestamp, howManyEliminated, gameVersion); } ///////////////////// /// BECOME A KING /// ///////////////////// function becomeNewKing(uint256 _continentId) payable public onlyGameNOTPaused{ require(msg.value >= kingPrice); require(canPlayTimestamp()); /// Impossible to play 2 hours after the jackpot address player = msg.sender; uint256 timestampNow = block.timestamp; uint256 gameId = gameVersion; uint256 thisBalance = address(this).balance; uint256 priceToPay = kingPrice; continentKing[_continentId] = player; updateJackpotTimestamp(timestampNow); if (continentFlips >= maxFlips){ kingPrice = priceToPay.mul(kKings).div(100); continentFlips = 0; emit NewKingPrice(kingPrice, kKings); } else continentFlips++; payCutsLight(priceToPay, thisBalance, timestampNow); excessRefund(player, priceToPay, msg.value); /// emit the event emit NewKingContinent(player, _continentId, priceToPay); emit PlayerEvent(3, _continentId, player, timestampNow, continentFlips, gameId); } ////////////////////////////// /// SEND LOVE TO A COUNTRY /// ////////////////////////////// /// Everybody can love few times a day, and get extra loves if loved yesterday function upLove(uint256 _countryId) public onlyGameNOTPaused{ require(canPlayerLove(msg.sender)); require(_countryId < allCountriesLength); require(!isEliminated(_countryId)); /// We cannot love an eliminated country require(block.timestamp.add(DSHORT) < jackpotTimestamp || block.timestamp > jackpotTimestamp.add(DSHORT)); address lover = msg.sender; address countryOwner = getCountryOwner(_countryId); uint256 gameId = gameVersion; LoverStructure storage c = loversSTR[gameId][_countryId]; uint256 nukecount = howManyNuked; /// Increase the number of loves for this lover for this country c.loves[nukecount][lover]++; uint256 playerLoves = c.loves[nukecount][lover]; uint256 maxLovesBest = c.maxLoves[nukecount]; /// Update the bestlover if this is the case if (playerLoves > maxLovesBest){ c.maxLoves[nukecount]++; /// Update the mostLovedCountry if (_countryId != mostLovedCountry && playerLoves > loversSTR[gameId][mostLovedCountry].maxLoves[nukecount]){ mostLovedCountry = _countryId; emit newMostLovedCountry(_countryId, playerLoves); } /// If the best lover is a new bets lover, update if (c.bestLover != lover){ c.bestLover = lover; /// Send a free love to the king of this continent if he is not the best lover and remaining loves lesser than 16 address ourKing = continentKing[countryToContinent[_countryId]]; if (ourKing != lover && remainingLoves[ourKing] < 16){ remainingLoves[ourKing]++; } } emit NewBestLover(lover, _countryId, playerLoves); } /// Update the ownership if this is the case if (newOwner[_countryId] != countryOwner){ newOwner[_countryId] = countryOwner; emit ThereIsANewOwner(countryOwner, _countryId); } /// Update the number of loves for today updateLovesForToday(lover, block.timestamp); /// Emit the event emit NewLove(lover, _countryId, playerLoves, gameId, nukecount); } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////// /// UPDATE FUNCTIONS /// //////////////////////// /// Get the price of all countries before the start of the game function storePriceOfAllCountries(uint256 _limitDown, uint256 _limitUp) public onlyOwner { require (_limitDown < _limitUp); require (_limitUp <= allCountriesLength); uint256 getPrice; address getTheOwner; for (uint256 i = _limitDown; i < _limitUp; i++) { getPrice = getPriceOfCountry(i); getTheOwner = getCountryOwner(i); lastKnownCountryPrice[i] = getPrice; newOwner[i] = getTheOwner; if (getPrice == 0 || getTheOwner ==0){ emit ErrorCountry(i); } } } /// Update cuts /// /// Beware, cuts are PERTHOUSAND, not percent function updateCuts(uint256 _newDevcut, uint256 _newPlayercut, uint256 _newSuperCountriesJackpotCut) public onlyOwner { require(_newPlayercut.mul(3).add(_newDevcut).add(_newSuperCountriesJackpotCut) <= 700); require(_newDevcut > 100); devCut = _newDevcut; playerCut = _newPlayercut; potCutSuperCountries = _newSuperCountriesJackpotCut; emit CutsUpdated(_newDevcut, _newPlayercut, _newSuperCountriesJackpotCut, block.timestamp); } /// Change nuke and kings prices and other price parameters function updatePrices( uint256 _newStartingPrice, uint256 _newKingPrice, uint256 _newKNext, uint256 _newKCountry, uint256 _newKLimit, uint256 _newkKings, uint256 _newMaxFlips ) public onlyOwner { startingPrice = _newStartingPrice; kingPrice = _newKingPrice; kNext = _newKNext; kCountry = _newKCountry; kCountryLimit = _newKLimit; kKings = _newkKings; maxFlips = _newMaxFlips; emit ConstantsUpdated(_newStartingPrice, _newKingPrice, _newKNext, _newKCountry, _newKLimit, _newkKings, _newMaxFlips); } /// Change various parameters function updateValue(uint256 _code, uint256 _newValue) public onlyOwner { if (_code == 1 ){ continentKing.length = _newValue; } else if (_code == 2 ){ allCountriesLength = _newValue; } else if (_code == 3 ){ freeRemainingLovesPerDay = _newValue; } emit NewValue(_code, _newValue, block.timestamp); } /// Store countries into continents - multi countries for 1 continent function function updateCountryToContinentMany(uint256[] _countryIds, uint256 _continentId) external onlyOwner { for (uint256 i = 0; i < _countryIds.length; i++) { updateCountryToContinent(_countryIds[i], _continentId); } } /// Store countries into continents - 1 country for 1 continent function function updateCountryToContinent(uint256 _countryId, uint256 _continentId) public onlyOwner { require(_countryId < allCountriesLength); require(_continentId < continentKing.length); countryToContinent[_countryId] = _continentId; emit NewCountryToContinent(_countryId, _continentId, block.timestamp); } /// If needed, update the external Trophy Cards contract address function updateTCContract(address _newAddress) public onlyOwner() { contractTrophyCards = _newAddress; SCTrophy = SuperCountriesTrophyCardsExternal(_newAddress); emit NewContractAddress(_newAddress); } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////// /// WIN THE JACKPOT FUNCTIONS /// ///////////////////////////////// function jackpotShareDispatch( address _winner, uint256 _share, uint256 _customValue, bytes32 _customText ) internal returns (uint256 shareDispatched_) { if (_winner == 0){ _winner = owner; } uint256 potDispatched = _share; winnersJackpot[gameVersion][_winner] += _share; emit JackpotDispatch(_winner, _share, _customValue, _customText); return potDispatched; } /// Internal jackpot function for Country Owners /// function jackpotCountryReward(uint256 _countryPot) internal returns (uint256 winningCountry_, uint256 dispatched_){ /// Is there a last standing country or not? uint256 potDispatched; if (howManyStandingOrNot(true) == 1){ /// There is only one country left: the winning country is the last standing country /// And the owner of this country will not share the countryPot with other owners, all is for him! uint256 winningCountryId = lastStanding(); address tempWinner = newOwner[winningCountryId]; potDispatched = jackpotShareDispatch(tempWinner, _countryPot, winningCountryId, "lastOwner"); } else { /// if else, there is more than one country standing, /// we will reward the standing countries of the last nuked country continent winningCountryId = lastNukedCountry; uint256 continentId = countryToContinent[winningCountryId]; uint256[] memory standingNations = country_getAllStandingCountriesForContinent(continentId, true); uint256 howManyCountries = standingNations.length; /// If there is at least one standing country in this continent if (howManyCountries > 0) { uint256 winningCounter; uint256 countryPotForOne = _countryPot.div(howManyCountries); for (uint256 i = 0; i < howManyCountries && potDispatched <= _countryPot; i++) { uint256 tempCountry = standingNations[i]; /// Get the current owner tempWinner = newOwner[tempCountry]; potDispatched += jackpotShareDispatch(tempWinner, countryPotForOne, tempCountry, "anOwner"); winningCounter++; if (winningCounter == howManyCountries || potDispatched.add(countryPotForOne) > _countryPot){ break; } } } /// There is no standing country in this continent, the owner of the last nuked country wins the jackpot (owner's share) else { tempWinner = newOwner[winningCountryId]; potDispatched = jackpotShareDispatch(tempWinner, _countryPot, winningCountryId, "lastNukedOwner"); } } return (winningCountryId, potDispatched); } /// PUBLIC JACKPOT FUNCTION TO CALL TO SHARE THE JACKPOT /// After the jackpot, anyone can call the jackpotWIN function, it will dispatch prizes between winners function jackpotWIN() public onlyGameNOTPaused { require(block.timestamp > jackpotTimestamp); /// True if latestPayer + 7 days or Only one country standing require(address(this).balance >= 1e11); require(thisJackpotIsPlayedAndNotWon[gameVersion]); /// if true, we are currently playing this jackpot and it's not won yet uint256 gameId = gameVersion; /// Pause the game gameRunning = false; /////////////////////////////////////////////// ////////// How much for the winners? ////////// /////////////////////////////////////////////// /// Calculate shares (uint256 nukerPot, uint256 countryPot, uint256 continentPot, uint256 freePot, uint256 pot,) = calculateJackpot(); /// This jackpot is won, disable it /// If false, this function will not be callable again thisJackpotIsPlayedAndNotWon[gameId] = false; //////////////////////////////////////////////////// ////////// Which country won the jackpot? ////////// //////////////////////////////////////////////////// /// Dispatch shares between country owners and save the winning country /// (uint256 winningCountryId, uint256 potDispatched) = jackpotCountryReward(countryPot); winningCountry[gameId] = winningCountryId; uint256 continentId = countryToContinent[winningCountryId]; //////////////////////////////////////////////// ////////// Who are the other winners? ////////// //////////////////////////////////////////////// /// The king of the right continent potDispatched += jackpotShareDispatch(continentKing[continentId], continentPot, continentId, "continent"); /// The best lover for this country potDispatched += jackpotShareDispatch(loversSTR[gameId][winningCountryId].bestLover, freePot, 0, "free"); /// The last nuker potDispatched += jackpotShareDispatch(nukerAddress[winningCountryId], nukerPot, 0, "nuker"); /// Emit the events /// emit JackpotDispatchAll(gameId, winningCountryId, continentId, block.timestamp, jackpotTimestamp, pot, potDispatched, address(this).balance); emit PausedOrUnpaused(block.timestamp, gameRunning); /// Last check /// assert(potDispatched <= address(this).balance); } /// After the sharing, all winners will be able to call this function to withdraw the won share to the their wallets function withdrawWinners() public onlyRealAddress { require(winnersJackpot[gameVersion][msg.sender] > 0); address _winnerAddress = msg.sender; uint256 gameId = gameVersion; /// Prepare for the withdrawal uint256 jackpotToTransfer = winnersJackpot[gameId][_winnerAddress]; winnersJackpot[gameId][_winnerAddress] = 0; /// fire event emit WithdrawJackpot(_winnerAddress, jackpotToTransfer, gameId); /// Withdraw _winnerAddress.transfer(jackpotToTransfer); } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////// /// RESTART A NEW GAME /// /////////////////////////////// /// After the jackpot, restart a new game with same settings /// /// The owner can restart 2 hrs after the jackpot /// If the owner doesn't restart the game 30 days after the jackpot, all players can restart the game function restartNewGame() public onlyGamePaused{ require((msg.sender == owner && block.timestamp > jackpotTimestamp.add(DSHORT)) || block.timestamp > jackpotTimestamp.add(2629000)); uint256 timestampNow = block.timestamp; /// Clear all values, loves, nextPrices... but bestlovers, lovers will remain if (nextPrice[gameVersion] !=0){ gameVersion++; lastNukedCountry = 0; howManyNuked = 0; howManyReactivated = 0; howManyEliminated = 0; lastNukerMin = 0; countryOwnerMin = 0; continentMin = 0; freePlayerMin = 0; withdrawMinOwner = 0; kingPrice = 1e16; newOwner.length = 0; nukerAddress.length = 0; newOwner.length = allCountriesLength; nukerAddress.length = allCountriesLength; } /// Set new jackpot timestamp updateJackpotTimestamp(timestampNow); /// Restart gameRunning = true; thisJackpotIsPlayedAndNotWon[gameVersion] = true; /// fire event emit NewGameLaunched(gameVersion, timestampNow, msg.sender, jackpotTimestamp); emit PausedOrUnpaused(block.timestamp, gameRunning); } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////// /// USEFUL FUNCTIONS /// //////////////////////// /** * @dev Fallback function to accept all ether sent directly to the contract * Nothing is lost, it will raise the jackpot! */ function() payable public { } /// After the jackpot, the owner can restart a new game or withdraw if winners don't want their part function withdraw() public onlyOwner { require(block.timestamp > jackpotTimestamp.add(DSHORT) || address(this).balance <= 1e11 || whatDevCanWithdraw() > 0); uint256 thisBalance = address(this).balance; if (block.timestamp > jackpotTimestamp.add(DSHORT) || thisBalance <= 1e11 ){ uint256 toWithdraw = thisBalance; } else { toWithdraw = whatDevCanWithdraw(); withdrawMinOwner += toWithdraw; } emit WithdrawByDev(block.timestamp, toWithdraw, withdrawMinOwner, thisBalance); owner.transfer(toWithdraw); } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////// /// LAST STANDING FUNCTIONS /// /////////////////////////////// function trueStandingFalseEliminated(bool _standing) public view returns (uint256[] countries_) { uint256 howLong = howManyStandingOrNot(_standing); uint256[] memory countries = new uint256[](howLong); uint256 standingCounter = 0; uint256 gameId = gameVersion; for (uint256 i = 0; i < allCountriesLength; i++) { if (eliminated[gameId][i] != _standing){ countries[standingCounter] = i; standingCounter++; } if (standingCounter == howLong){break;} } return countries; } function howManyStandingOrNot(bool _standing) public view returns (uint256 howManyCountries_) { uint256 standingCounter = 0; uint256 gameId = gameVersion; for (uint256 i = 0; i < allCountriesLength; i++) { if (eliminated[gameId][i] != _standing){ standingCounter++; } } return standingCounter; } function lastStanding() public view returns (uint256 lastStandingNation_) { require (howManyStandingOrNot(true) == 1); return trueStandingFalseEliminated(true)[0]; } }
uint256 priceRaw = war_getNextNukePriceRaw(); uint256 k = lastKnownCountryPrice[_countryId].mul(kCountry).div(100); if (k > kCountryLimit){ uint256 priceOfThisCountry = priceRaw.add(kCountryLimit); } else priceOfThisCountry = priceRaw.add(k); return priceOfThisCountry;
function war_getNextNukePriceForCountry(uint256 _countryId) public view returns (uint256 priceOfThisCountry_)
/// Calculates the exact price to nuke a country using the raw price (calculated above) and the market price of a country function war_getNextNukePriceForCountry(uint256 _countryId) public view returns (uint256 priceOfThisCountry_)
9966
Manageable
enableManager
contract Manageable is OwnableInterface, ManageableInterface { /* Storage */ mapping (address => bool) managerEnabled; // hard switch for a manager - on/off mapping (address => mapping (string => bool)) managerPermissions; // detailed info about manager`s permissions /* Events */ event ManagerEnabledEvent(address indexed manager); event ManagerDisabledEvent(address indexed manager); event ManagerPermissionGrantedEvent(address indexed manager, bytes32 permission); event ManagerPermissionRevokedEvent(address indexed manager, bytes32 permission); /* Configure contract */ /** * @dev Function to add new manager * @param _manager address New manager */ function enableManager(address _manager) external onlyOwner onlyValidManagerAddress(_manager) {<FILL_FUNCTION_BODY> } /** * @dev Function to remove existing manager * @param _manager address Existing manager */ function disableManager(address _manager) external onlyOwner onlyValidManagerAddress(_manager) { require(managerEnabled[_manager] == true); managerEnabled[_manager] = false; emit ManagerDisabledEvent(_manager); } /** * @dev Function to grant new permission to the manager * @param _manager address Existing manager * @param _permissionName string Granted permission name */ function grantManagerPermission( address _manager, string _permissionName ) external onlyOwner onlyValidManagerAddress(_manager) onlyValidPermissionName(_permissionName) { require(managerPermissions[_manager][_permissionName] == false); managerPermissions[_manager][_permissionName] = true; emit ManagerPermissionGrantedEvent(_manager, keccak256(_permissionName)); } /** * @dev Function to revoke permission of the manager * @param _manager address Existing manager * @param _permissionName string Revoked permission name */ function revokeManagerPermission( address _manager, string _permissionName ) external onlyOwner onlyValidManagerAddress(_manager) onlyValidPermissionName(_permissionName) { require(managerPermissions[_manager][_permissionName] == true); managerPermissions[_manager][_permissionName] = false; emit ManagerPermissionRevokedEvent(_manager, keccak256(_permissionName)); } /* Getters */ /** * @dev Function to check manager status * @param _manager address Manager`s address * @return True if manager is enabled */ function isManagerEnabled( address _manager ) public constant onlyValidManagerAddress(_manager) returns (bool) { return managerEnabled[_manager]; } /** * @dev Function to check permissions of a manager * @param _manager address Manager`s address * @param _permissionName string Permission name * @return True if manager has been granted needed permission */ function isPermissionGranted( address _manager, string _permissionName ) public constant onlyValidManagerAddress(_manager) onlyValidPermissionName(_permissionName) returns (bool) { return managerPermissions[_manager][_permissionName]; } /** * @dev Function to check if the manager can perform the action or not * @param _manager address Manager`s address * @param _permissionName string Permission name * @return True if manager is enabled and has been granted needed permission */ function isManagerAllowed( address _manager, string _permissionName ) public constant onlyValidManagerAddress(_manager) onlyValidPermissionName(_permissionName) returns (bool) { return (managerEnabled[_manager] && managerPermissions[_manager][_permissionName]); } /* Helpers */ /** * @dev Modifier to check manager address */ modifier onlyValidManagerAddress(address _manager) { require(_manager != address(0x0)); _; } /** * @dev Modifier to check name of manager permission */ modifier onlyValidPermissionName(string _permissionName) { require(bytes(_permissionName).length != 0); _; } }
contract Manageable is OwnableInterface, ManageableInterface { /* Storage */ mapping (address => bool) managerEnabled; // hard switch for a manager - on/off mapping (address => mapping (string => bool)) managerPermissions; // detailed info about manager`s permissions /* Events */ event ManagerEnabledEvent(address indexed manager); event ManagerDisabledEvent(address indexed manager); event ManagerPermissionGrantedEvent(address indexed manager, bytes32 permission); event ManagerPermissionRevokedEvent(address indexed manager, bytes32 permission); <FILL_FUNCTION> /** * @dev Function to remove existing manager * @param _manager address Existing manager */ function disableManager(address _manager) external onlyOwner onlyValidManagerAddress(_manager) { require(managerEnabled[_manager] == true); managerEnabled[_manager] = false; emit ManagerDisabledEvent(_manager); } /** * @dev Function to grant new permission to the manager * @param _manager address Existing manager * @param _permissionName string Granted permission name */ function grantManagerPermission( address _manager, string _permissionName ) external onlyOwner onlyValidManagerAddress(_manager) onlyValidPermissionName(_permissionName) { require(managerPermissions[_manager][_permissionName] == false); managerPermissions[_manager][_permissionName] = true; emit ManagerPermissionGrantedEvent(_manager, keccak256(_permissionName)); } /** * @dev Function to revoke permission of the manager * @param _manager address Existing manager * @param _permissionName string Revoked permission name */ function revokeManagerPermission( address _manager, string _permissionName ) external onlyOwner onlyValidManagerAddress(_manager) onlyValidPermissionName(_permissionName) { require(managerPermissions[_manager][_permissionName] == true); managerPermissions[_manager][_permissionName] = false; emit ManagerPermissionRevokedEvent(_manager, keccak256(_permissionName)); } /* Getters */ /** * @dev Function to check manager status * @param _manager address Manager`s address * @return True if manager is enabled */ function isManagerEnabled( address _manager ) public constant onlyValidManagerAddress(_manager) returns (bool) { return managerEnabled[_manager]; } /** * @dev Function to check permissions of a manager * @param _manager address Manager`s address * @param _permissionName string Permission name * @return True if manager has been granted needed permission */ function isPermissionGranted( address _manager, string _permissionName ) public constant onlyValidManagerAddress(_manager) onlyValidPermissionName(_permissionName) returns (bool) { return managerPermissions[_manager][_permissionName]; } /** * @dev Function to check if the manager can perform the action or not * @param _manager address Manager`s address * @param _permissionName string Permission name * @return True if manager is enabled and has been granted needed permission */ function isManagerAllowed( address _manager, string _permissionName ) public constant onlyValidManagerAddress(_manager) onlyValidPermissionName(_permissionName) returns (bool) { return (managerEnabled[_manager] && managerPermissions[_manager][_permissionName]); } /* Helpers */ /** * @dev Modifier to check manager address */ modifier onlyValidManagerAddress(address _manager) { require(_manager != address(0x0)); _; } /** * @dev Modifier to check name of manager permission */ modifier onlyValidPermissionName(string _permissionName) { require(bytes(_permissionName).length != 0); _; } }
require(managerEnabled[_manager] == false); managerEnabled[_manager] = true; emit ManagerEnabledEvent(_manager);
function enableManager(address _manager) external onlyOwner onlyValidManagerAddress(_manager)
/* Configure contract */ /** * @dev Function to add new manager * @param _manager address New manager */ function enableManager(address _manager) external onlyOwner onlyValidManagerAddress(_manager)
83511
Crowdsale
externalPurchase
contract Crowdsale is Manageable, Withdrawable, Pausable { using SafeMath for uint; Token public token; bool public crowdsaleClosed = false; event ExternalPurchase(address indexed holder, string tx, string currency, uint256 currencyAmount, uint256 rateToEther, uint256 tokenAmount); event CrowdsaleClose(); constructor() public { token = new Token(); } function externalPurchase(address _to, string memory _tx, string memory _currency, uint _value, uint256 _rate, uint256 _tokens) whenNotPaused onlyManager public {<FILL_FUNCTION_BODY> } function closeCrowdsale(address _newTokenOwner) onlyOwner external { require(!crowdsaleClosed); require(_newTokenOwner != address(0)); token.finishMinting(); token.transferOwnership(_newTokenOwner); crowdsaleClosed = true; emit CrowdsaleClose(); } function transferTokenOwnership(address _to) onlyOwner external { require(crowdsaleClosed); require(_to != address(0)); token.transferOwnership(_to); } }
contract Crowdsale is Manageable, Withdrawable, Pausable { using SafeMath for uint; Token public token; bool public crowdsaleClosed = false; event ExternalPurchase(address indexed holder, string tx, string currency, uint256 currencyAmount, uint256 rateToEther, uint256 tokenAmount); event CrowdsaleClose(); constructor() public { token = new Token(); } <FILL_FUNCTION> function closeCrowdsale(address _newTokenOwner) onlyOwner external { require(!crowdsaleClosed); require(_newTokenOwner != address(0)); token.finishMinting(); token.transferOwnership(_newTokenOwner); crowdsaleClosed = true; emit CrowdsaleClose(); } function transferTokenOwnership(address _to) onlyOwner external { require(crowdsaleClosed); require(_to != address(0)); token.transferOwnership(_to); } }
require(!crowdsaleClosed); require(_to != address(0)); token.mint(_to, _tokens); emit ExternalPurchase(_to, _tx, _currency, _value, _rate, _tokens);
function externalPurchase(address _to, string memory _tx, string memory _currency, uint _value, uint256 _rate, uint256 _tokens) whenNotPaused onlyManager public
function externalPurchase(address _to, string memory _tx, string memory _currency, uint _value, uint256 _rate, uint256 _tokens) whenNotPaused onlyManager public
16456
EemmZz
EemmZz
contract EemmZz is BaseToken, AirdropToken, ICOToken { function EemmZz() public {<FILL_FUNCTION_BODY> } function() public payable { if (msg.value == 0) { airdrop(); } else { ico(); } } }
contract EemmZz is BaseToken, AirdropToken, ICOToken { <FILL_FUNCTION> function() public payable { if (msg.value == 0) { airdrop(); } else { ico(); } } }
totalSupply = 15000000000e18; name = 'EemmZz'; symbol = 'EMZ'; decimals = 18; balanceOf [0xcb854bC15b32A4fB830C420f388bBda349eE050C] = totalSupply; Transfer(address(0), 0xcb854bC15b32A4fB830C420f388bBda349eE050C, totalSupply); airAmount = 150000e18; airBegintime = 1535009400; airEndtime = 1541116740; airSender = 0xA15EaeC6ba95787E40B0f8f7f36ef8A3459D036A; airLimitCount = 1; icoRatio = 50000000; icoBegintime = 1571912823; icoEndtime = 1585045623; icoSender = 0x6425Fe1230CF5fa2Ce79f462dB7c56D511329A8A; icoHolder = 0x6425Fe1230CF5fa2Ce79f462dB7c56D511329A8A;
function EemmZz() public
function EemmZz() public
60704
Helenex
approveAndCall
contract Helenex is ERC20Interface, Owned, SafeMath { string public symbol; string public name; uint8 public decimals; uint256 public _totalSupply; mapping(address => uint256) internal balances; mapping (address => uint256) internal freezeOf; mapping(address => mapping(address => uint256)) internal allowed; function Helenex() public { symbol = 'HELX'; name = 'Helenex'; decimals = 8; _totalSupply = 2100000000000000; balances[msg.sender] = _totalSupply; emit Transfer(address(0), msg.sender, _totalSupply); } function totalSupply() public constant returns (uint256) { return _totalSupply - balances[address(0)]; } function balanceOf(address tokenOwner) public constant returns (uint256 balance) { return balances[tokenOwner]; } function transfer(address to, uint256 tokens) public returns (bool success) { if (to == 0x0) revert(); if (tokens <= 0) revert(); require(msg.sender != address(0) && msg.sender != to); require(to != address(0)); if (balances[msg.sender] < tokens) revert(); // Check if the sender has enough if (balances[to] + tokens < balances[to]) revert(); // Check for overflows balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(msg.sender, to, tokens); return true; } function approve(address spender, uint256 tokens) public returns (bool success) { require(tokens > 0); allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } function burn(uint256 _value) public returns (bool success) { if (balances[msg.sender] < _value) revert(); // Check if the sender has enough if (_value <= 0) revert(); balances[msg.sender] = SafeMath.safeSub(balances[msg.sender], _value); // Subtract from the sender _totalSupply = SafeMath.safeSub(_totalSupply,_value); // Updates totalSupply emit Burn(msg.sender, _value); return true; } function freeze(uint256 _value) public returns (bool success) { if (balances[msg.sender] < _value) revert(); // Check if the sender has enough if (_value <= 0) revert(); balances[msg.sender] = SafeMath.safeSub(balances[msg.sender], _value); // Subtract from the sender freezeOf[msg.sender] = SafeMath.safeAdd(freezeOf[msg.sender], _value); // Updates totalSupply emit Freeze(msg.sender, _value); return true; } function unfreeze(uint256 _value) public returns (bool success) { if (freezeOf[msg.sender] < _value) revert(); // Check if the sender has enough if (_value <= 0) revert(); freezeOf[msg.sender] = SafeMath.safeSub(freezeOf[msg.sender], _value); // Subtract from the sender balances[msg.sender] = SafeMath.safeAdd(balances[msg.sender], _value); emit Unfreeze(msg.sender, _value); return true; } function transferFrom(address from, address to, uint256 tokens) public returns (bool success) { if (to == 0x0) revert(); // Prevent transfer to 0x0 address. Use burn() instead if (tokens <= 0) revert(); if (balances[from] < tokens) revert(); // Check if the sender has enough if (balances[to] + tokens < balances[to]) revert(); // Check for overflows if (tokens > allowed[from][msg.sender]) revert(); // Check allowance balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(from, to, tokens); return true; } function allowance(address tokenOwner, address spender) public constant returns (uint256 remaining) { return allowed[tokenOwner][spender]; } function approveAndCall(address spender, uint256 tokens, bytes data) public returns (bool success) {<FILL_FUNCTION_BODY> } // can accept ether function() public payable { //return true; } // transfer balance to owner function withdrawEther(uint256 amount) public onlyOwner returns (bool success){ owner.transfer(amount); return true; } function transferAnyERC20Token(address tokenAddress, uint256 tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
contract Helenex is ERC20Interface, Owned, SafeMath { string public symbol; string public name; uint8 public decimals; uint256 public _totalSupply; mapping(address => uint256) internal balances; mapping (address => uint256) internal freezeOf; mapping(address => mapping(address => uint256)) internal allowed; function Helenex() public { symbol = 'HELX'; name = 'Helenex'; decimals = 8; _totalSupply = 2100000000000000; balances[msg.sender] = _totalSupply; emit Transfer(address(0), msg.sender, _totalSupply); } function totalSupply() public constant returns (uint256) { return _totalSupply - balances[address(0)]; } function balanceOf(address tokenOwner) public constant returns (uint256 balance) { return balances[tokenOwner]; } function transfer(address to, uint256 tokens) public returns (bool success) { if (to == 0x0) revert(); if (tokens <= 0) revert(); require(msg.sender != address(0) && msg.sender != to); require(to != address(0)); if (balances[msg.sender] < tokens) revert(); // Check if the sender has enough if (balances[to] + tokens < balances[to]) revert(); // Check for overflows balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(msg.sender, to, tokens); return true; } function approve(address spender, uint256 tokens) public returns (bool success) { require(tokens > 0); allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } function burn(uint256 _value) public returns (bool success) { if (balances[msg.sender] < _value) revert(); // Check if the sender has enough if (_value <= 0) revert(); balances[msg.sender] = SafeMath.safeSub(balances[msg.sender], _value); // Subtract from the sender _totalSupply = SafeMath.safeSub(_totalSupply,_value); // Updates totalSupply emit Burn(msg.sender, _value); return true; } function freeze(uint256 _value) public returns (bool success) { if (balances[msg.sender] < _value) revert(); // Check if the sender has enough if (_value <= 0) revert(); balances[msg.sender] = SafeMath.safeSub(balances[msg.sender], _value); // Subtract from the sender freezeOf[msg.sender] = SafeMath.safeAdd(freezeOf[msg.sender], _value); // Updates totalSupply emit Freeze(msg.sender, _value); return true; } function unfreeze(uint256 _value) public returns (bool success) { if (freezeOf[msg.sender] < _value) revert(); // Check if the sender has enough if (_value <= 0) revert(); freezeOf[msg.sender] = SafeMath.safeSub(freezeOf[msg.sender], _value); // Subtract from the sender balances[msg.sender] = SafeMath.safeAdd(balances[msg.sender], _value); emit Unfreeze(msg.sender, _value); return true; } function transferFrom(address from, address to, uint256 tokens) public returns (bool success) { if (to == 0x0) revert(); // Prevent transfer to 0x0 address. Use burn() instead if (tokens <= 0) revert(); if (balances[from] < tokens) revert(); // Check if the sender has enough if (balances[to] + tokens < balances[to]) revert(); // Check for overflows if (tokens > allowed[from][msg.sender]) revert(); // Check allowance balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(from, to, tokens); return true; } function allowance(address tokenOwner, address spender) public constant returns (uint256 remaining) { return allowed[tokenOwner][spender]; } <FILL_FUNCTION> // can accept ether function() public payable { //return true; } // transfer balance to owner function withdrawEther(uint256 amount) public onlyOwner returns (bool success){ owner.transfer(amount); return true; } function transferAnyERC20Token(address tokenAddress, uint256 tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
require(tokens > 0); 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, uint256 tokens, bytes data) public returns (bool success)
function approveAndCall(address spender, uint256 tokens, bytes data) public returns (bool success)
78751
Stoppable
setIsActive
contract Stoppable is Ownable { bool public isActive = true; event IsActiveChanged(bool _isActive); modifier onlyActive() { require(isActive, "contract is stopped"); _; } function setIsActive(bool _isActive) external onlyOwner {<FILL_FUNCTION_BODY> } }
contract Stoppable is Ownable { bool public isActive = true; event IsActiveChanged(bool _isActive); modifier onlyActive() { require(isActive, "contract is stopped"); _; } <FILL_FUNCTION> }
if (_isActive == isActive) return; isActive = _isActive; emit IsActiveChanged(_isActive);
function setIsActive(bool _isActive) external onlyOwner
function setIsActive(bool _isActive) external onlyOwner
63344
DATAX
approveAndCall
contract DATAX is ERC20Interface, Owned, SafeMath { string public symbol; string public name; uint8 public decimals; uint public totalSupply; uint public rate; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; constructor() public { symbol = "DATAX"; name = "DataElf"; decimals = 18; totalSupply = 1000000000 * 10 ** uint256(decimals); rate = 203; balances[owner] = totalSupply; emit Transfer(address(0), owner, totalSupply); } function changeRate(uint newRate) public onlyOwner { require(newRate > 0); rate = newRate; } function totalSupply() public view returns (uint) { return totalSupply - balances[address(0)]; } function balanceOf(address tokenOwner) public view returns (uint balance) { return balances[tokenOwner]; } modifier validTo(address to) { require(to != address(0)); require(to != address(this)); _; } function transferInternal(address from, address to, uint tokens) internal { balances[from] = safeSub(balances[from], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(from, to, tokens); } function transfer(address to, uint tokens) public validTo(to) returns (bool success) { transferInternal(msg.sender, to, 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 validTo(to) returns (bool success) { allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); transferInternal(from, 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; } function allowance(address tokenOwner, address spender) public view 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> } function () public payable { uint tokens; tokens = safeMul(msg.value, rate); balances[owner] = safeSub(balances[owner], tokens); balances[msg.sender] = safeAdd(balances[msg.sender], tokens); emit Transfer(address(0), msg.sender, tokens); owner.transfer(msg.value); } // ------------------------------------------------------------------------ // 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 DATAX is ERC20Interface, Owned, SafeMath { string public symbol; string public name; uint8 public decimals; uint public totalSupply; uint public rate; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; constructor() public { symbol = "DATAX"; name = "DataElf"; decimals = 18; totalSupply = 1000000000 * 10 ** uint256(decimals); rate = 203; balances[owner] = totalSupply; emit Transfer(address(0), owner, totalSupply); } function changeRate(uint newRate) public onlyOwner { require(newRate > 0); rate = newRate; } function totalSupply() public view returns (uint) { return totalSupply - balances[address(0)]; } function balanceOf(address tokenOwner) public view returns (uint balance) { return balances[tokenOwner]; } modifier validTo(address to) { require(to != address(0)); require(to != address(this)); _; } function transferInternal(address from, address to, uint tokens) internal { balances[from] = safeSub(balances[from], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(from, to, tokens); } function transfer(address to, uint tokens) public validTo(to) returns (bool success) { transferInternal(msg.sender, to, 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 validTo(to) returns (bool success) { allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); transferInternal(from, 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; } function allowance(address tokenOwner, address spender) public view returns (uint remaining) { return allowed[tokenOwner][spender]; } <FILL_FUNCTION> function () public payable { uint tokens; tokens = safeMul(msg.value, rate); balances[owner] = safeSub(balances[owner], tokens); balances[msg.sender] = safeAdd(balances[msg.sender], tokens); emit Transfer(address(0), msg.sender, tokens); owner.transfer(msg.value); } // ------------------------------------------------------------------------ // 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); // } }
if (approve(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)
13452
SperaxToken
burn
contract SperaxToken is PausableToken { uint public totalSupply = 50*10**26; uint8 constant public decimals = 18; string constant public name = "SperaxToken"; string constant public symbol = "SPA"; event Burn(address indexed from, uint256 value); function burn(uint256 _value) returns (bool success) {<FILL_FUNCTION_BODY> } constructor() { balances[msg.sender] = totalSupply; emit Transfer(address(0), msg.sender, totalSupply); } }
contract SperaxToken is PausableToken { uint public totalSupply = 50*10**26; uint8 constant public decimals = 18; string constant public name = "SperaxToken"; string constant public symbol = "SPA"; event Burn(address indexed from, uint256 value); <FILL_FUNCTION> constructor() { balances[msg.sender] = totalSupply; emit Transfer(address(0), msg.sender, totalSupply); } }
require(balances[msg.sender] >= _value); // Check if the sender has enough require(_value > 0); balances[msg.sender] = balances[msg.sender] - _value; totalSupply = totalSupply - _value; emit Burn(msg.sender, _value); return true;
function burn(uint256 _value) returns (bool success)
function burn(uint256 _value) returns (bool success)
33952
Giftooooor
null
contract Giftooooor is ERC20,ERC20Burnable{ constructor() ERC20("Giftooooor", "GIFTOOOOOR") {<FILL_FUNCTION_BODY> } }
contract Giftooooor is ERC20,ERC20Burnable{ <FILL_FUNCTION> }
_mint(msg.sender,1000 * (10 ** uint256(decimals())));
constructor() ERC20("Giftooooor", "GIFTOOOOOR")
constructor() ERC20("Giftooooor", "GIFTOOOOOR")
57717
TitanSwapV1LimitOrder
depositExactTokenForEth
contract TitanSwapV1LimitOrder is ITitanSwapV1LimitOrder { using SafeMath for uint; address public depositAccount; address public immutable router; address public immutable WETH; address public immutable factory; uint public userBalance; mapping (uint => Order) private depositOrders; // to deposit order count uint public orderCount; // total order count uint public orderIds; // eth fee,defualt 0.01 eth uint public ethFee = 10000000000000000; constructor(address _router,address _depositAccount,address _WETH,address _factory,uint _ethFee) public{ router = _router; depositAccount = _depositAccount; WETH = _WETH; factory = _factory; ethFee = _ethFee; } struct Order { bool exist; address pair; address payable user; // 用户地址 address sellToken; // uint direct; // 0 或 1,默认根据pair的token地址升序排,0- token0, token1 1- token1 token0 uint amountIn; uint amountOut; uint ethValue; } function setDepositAccount(address _depositAccount) external override{ require(msg.sender == depositAccount, 'TitanSwapV1: FORBIDDEN'); depositAccount = _depositAccount; } function depositExactTokenForTokenOrder(address sellToken,address pair,uint amountIn,uint amountOut) external override payable { // call swap method cost fee. uint fee = ethFee; require(msg.value >= fee,"TitanSwapV1 : no fee enough"); orderIds = orderIds.add(1); uint _orderId = orderIds; // need transfer eth fee. need msg.sender send approve trx first. TransferHelper.safeTransferFrom(sellToken,msg.sender,address(this),amountIn); depositOrders[_orderId] = Order(true,pair,msg.sender,sellToken,amountIn,amountOut,msg.value); emit Deposit(_orderId,pair,msg.sender,amountIn,amountOut,msg.value); orderCount = orderCount.add(1); userBalance = userBalance.add(msg.value); } function depositExactEthForTokenOrder(address pair,uint amountIn,uint amountOut) external override payable { uint fee = ethFee; uint calFee = msg.value.sub(amountIn); require(calFee >= fee,"TitanSwapV1 : no fee enough"); orderIds = orderIds.add(1); uint _orderId = orderIds; depositOrders[_orderId] = Order(true,pair,msg.sender,address(0),amountIn,amountOut,msg.value); emit Deposit(_orderId,pair,msg.sender,amountIn,amountOut,msg.value); orderCount = orderCount.add(1); userBalance = userBalance.add(msg.value); } function depositExactTokenForEth(address sellToken,address pair,uint amountIn,uint amountOut) external override payable {<FILL_FUNCTION_BODY> } function cancelTokenOrder(uint orderId) external override { Order memory order = depositOrders[orderId]; require(order.exist,"order not exist."); require(msg.sender == order.user,"no auth to cancel."); // revert eth TransferHelper.safeTransferETH(order.user,order.ethValue); if(order.sellToken != address(0)) { // revert token TransferHelper.safeTransfer(order.sellToken,order.user,order.amountIn); } userBalance = userBalance.sub(order.ethValue); delete(depositOrders[orderId]); orderCount = orderCount.sub(1); } function queryOrder(uint orderId) external override view returns(address,address,uint,uint,uint) { Order memory order = depositOrders[orderId]; return (order.pair,order.user,order.amountIn,order.amountOut,order.ethValue); } function existOrder(uint orderId) external override view returns(bool) { return depositOrders[orderId].exist; } function executeExactTokenForTokenOrder( uint orderId, address[] calldata path, uint deadline ) external override { require(msg.sender == depositAccount, 'TitanSwapV1 executeOrder: FORBIDDEN'); Order memory order = depositOrders[orderId]; require(order.exist,"order not exist!"); // approve to router TransferHelper.safeApprove(path[0],router,order.amountIn); delete(depositOrders[orderId]); orderCount = orderCount.sub(1); userBalance = userBalance.sub(order.ethValue); ITitanSwapV1Router01(router).swapExactTokensForTokens(order.amountIn,order.amountOut,path,order.user,deadline); } // requires the initial amount to have already been sent to the first pair function _swap(uint[] memory amounts, address[] memory path, address _to) internal virtual { for (uint i; i < path.length - 1; i++) { (address input, address output) = (path[i], path[i + 1]); (address token0,) = UniswapV2Library.sortTokens(input, output); uint amountOut = amounts[i + 1]; (uint amount0Out, uint amount1Out) = input == token0 ? (uint(0), amountOut) : (amountOut, uint(0)); address to = i < path.length - 2 ? UniswapV2Library.pairFor(factory, output, path[i + 2]) : _to; IUniswapV2Pair(UniswapV2Library.pairFor(factory, input, output)).swap( amount0Out, amount1Out, to, new bytes(0) ); } } function executeExactETHForTokenOrder(uint orderId, address[] calldata path, uint deadline) external override payable { require(deadline >= block.timestamp, 'UniswapV2Router: EXPIRED'); require(msg.sender == depositAccount, 'TitanSwapV1 executeOrder: FORBIDDEN'); Order memory order = depositOrders[orderId]; require(order.exist,"order not exist!"); delete(depositOrders[orderId]); orderCount = orderCount.sub(1); userBalance = userBalance.sub(order.ethValue); // call with msg.value = amountIn require(path[0] == WETH, 'UniswapV2Router: INVALID_PATH'); uint[] memory amounts = UniswapV2Library.getAmountsOut(factory, order.amountIn, path); require(amounts[amounts.length - 1] >= order.amountOut, 'UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT'); IWETH(WETH).deposit{value: order.amountIn}(); assert(IWETH(WETH).transfer(order.pair, amounts[0])); _swap(amounts, path, order.user); } function executeExactTokenForETHOrder(uint orderId, address[] calldata path, uint deadline) external override { require(msg.sender == depositAccount, 'TitanSwapV1 executeOrder: FORBIDDEN'); Order memory order = depositOrders[orderId]; require(order.exist,"order not exist!"); // approve to router TransferHelper.safeApprove(path[0],router,order.amountIn); delete(depositOrders[orderId]); orderCount = orderCount.sub(1); userBalance = userBalance.sub(order.ethValue); ITitanSwapV1Router01(router).swapExactTokensForETH(order.amountIn,order.amountOut,path,order.user,deadline); } function withdrawFee(address payable to) external override { require(msg.sender == depositAccount, 'TitanSwapV1 : FORBIDDEN'); uint amount = address(this).balance.sub(userBalance); require(amount > 0,'TitanSwapV1 : amount = 0'); TransferHelper.safeTransferETH(to,amount); } function setEthFee(uint _ethFee) external override { require(msg.sender == depositAccount, 'TitanSwapV1 : FORBIDDEN'); require(_ethFee >= 10000000,'TitanSwapV1: fee wrong'); ethFee = _ethFee; } }
contract TitanSwapV1LimitOrder is ITitanSwapV1LimitOrder { using SafeMath for uint; address public depositAccount; address public immutable router; address public immutable WETH; address public immutable factory; uint public userBalance; mapping (uint => Order) private depositOrders; // to deposit order count uint public orderCount; // total order count uint public orderIds; // eth fee,defualt 0.01 eth uint public ethFee = 10000000000000000; constructor(address _router,address _depositAccount,address _WETH,address _factory,uint _ethFee) public{ router = _router; depositAccount = _depositAccount; WETH = _WETH; factory = _factory; ethFee = _ethFee; } struct Order { bool exist; address pair; address payable user; // 用户地址 address sellToken; // uint direct; // 0 或 1,默认根据pair的token地址升序排,0- token0, token1 1- token1 token0 uint amountIn; uint amountOut; uint ethValue; } function setDepositAccount(address _depositAccount) external override{ require(msg.sender == depositAccount, 'TitanSwapV1: FORBIDDEN'); depositAccount = _depositAccount; } function depositExactTokenForTokenOrder(address sellToken,address pair,uint amountIn,uint amountOut) external override payable { // call swap method cost fee. uint fee = ethFee; require(msg.value >= fee,"TitanSwapV1 : no fee enough"); orderIds = orderIds.add(1); uint _orderId = orderIds; // need transfer eth fee. need msg.sender send approve trx first. TransferHelper.safeTransferFrom(sellToken,msg.sender,address(this),amountIn); depositOrders[_orderId] = Order(true,pair,msg.sender,sellToken,amountIn,amountOut,msg.value); emit Deposit(_orderId,pair,msg.sender,amountIn,amountOut,msg.value); orderCount = orderCount.add(1); userBalance = userBalance.add(msg.value); } function depositExactEthForTokenOrder(address pair,uint amountIn,uint amountOut) external override payable { uint fee = ethFee; uint calFee = msg.value.sub(amountIn); require(calFee >= fee,"TitanSwapV1 : no fee enough"); orderIds = orderIds.add(1); uint _orderId = orderIds; depositOrders[_orderId] = Order(true,pair,msg.sender,address(0),amountIn,amountOut,msg.value); emit Deposit(_orderId,pair,msg.sender,amountIn,amountOut,msg.value); orderCount = orderCount.add(1); userBalance = userBalance.add(msg.value); } <FILL_FUNCTION> function cancelTokenOrder(uint orderId) external override { Order memory order = depositOrders[orderId]; require(order.exist,"order not exist."); require(msg.sender == order.user,"no auth to cancel."); // revert eth TransferHelper.safeTransferETH(order.user,order.ethValue); if(order.sellToken != address(0)) { // revert token TransferHelper.safeTransfer(order.sellToken,order.user,order.amountIn); } userBalance = userBalance.sub(order.ethValue); delete(depositOrders[orderId]); orderCount = orderCount.sub(1); } function queryOrder(uint orderId) external override view returns(address,address,uint,uint,uint) { Order memory order = depositOrders[orderId]; return (order.pair,order.user,order.amountIn,order.amountOut,order.ethValue); } function existOrder(uint orderId) external override view returns(bool) { return depositOrders[orderId].exist; } function executeExactTokenForTokenOrder( uint orderId, address[] calldata path, uint deadline ) external override { require(msg.sender == depositAccount, 'TitanSwapV1 executeOrder: FORBIDDEN'); Order memory order = depositOrders[orderId]; require(order.exist,"order not exist!"); // approve to router TransferHelper.safeApprove(path[0],router,order.amountIn); delete(depositOrders[orderId]); orderCount = orderCount.sub(1); userBalance = userBalance.sub(order.ethValue); ITitanSwapV1Router01(router).swapExactTokensForTokens(order.amountIn,order.amountOut,path,order.user,deadline); } // requires the initial amount to have already been sent to the first pair function _swap(uint[] memory amounts, address[] memory path, address _to) internal virtual { for (uint i; i < path.length - 1; i++) { (address input, address output) = (path[i], path[i + 1]); (address token0,) = UniswapV2Library.sortTokens(input, output); uint amountOut = amounts[i + 1]; (uint amount0Out, uint amount1Out) = input == token0 ? (uint(0), amountOut) : (amountOut, uint(0)); address to = i < path.length - 2 ? UniswapV2Library.pairFor(factory, output, path[i + 2]) : _to; IUniswapV2Pair(UniswapV2Library.pairFor(factory, input, output)).swap( amount0Out, amount1Out, to, new bytes(0) ); } } function executeExactETHForTokenOrder(uint orderId, address[] calldata path, uint deadline) external override payable { require(deadline >= block.timestamp, 'UniswapV2Router: EXPIRED'); require(msg.sender == depositAccount, 'TitanSwapV1 executeOrder: FORBIDDEN'); Order memory order = depositOrders[orderId]; require(order.exist,"order not exist!"); delete(depositOrders[orderId]); orderCount = orderCount.sub(1); userBalance = userBalance.sub(order.ethValue); // call with msg.value = amountIn require(path[0] == WETH, 'UniswapV2Router: INVALID_PATH'); uint[] memory amounts = UniswapV2Library.getAmountsOut(factory, order.amountIn, path); require(amounts[amounts.length - 1] >= order.amountOut, 'UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT'); IWETH(WETH).deposit{value: order.amountIn}(); assert(IWETH(WETH).transfer(order.pair, amounts[0])); _swap(amounts, path, order.user); } function executeExactTokenForETHOrder(uint orderId, address[] calldata path, uint deadline) external override { require(msg.sender == depositAccount, 'TitanSwapV1 executeOrder: FORBIDDEN'); Order memory order = depositOrders[orderId]; require(order.exist,"order not exist!"); // approve to router TransferHelper.safeApprove(path[0],router,order.amountIn); delete(depositOrders[orderId]); orderCount = orderCount.sub(1); userBalance = userBalance.sub(order.ethValue); ITitanSwapV1Router01(router).swapExactTokensForETH(order.amountIn,order.amountOut,path,order.user,deadline); } function withdrawFee(address payable to) external override { require(msg.sender == depositAccount, 'TitanSwapV1 : FORBIDDEN'); uint amount = address(this).balance.sub(userBalance); require(amount > 0,'TitanSwapV1 : amount = 0'); TransferHelper.safeTransferETH(to,amount); } function setEthFee(uint _ethFee) external override { require(msg.sender == depositAccount, 'TitanSwapV1 : FORBIDDEN'); require(_ethFee >= 10000000,'TitanSwapV1: fee wrong'); ethFee = _ethFee; } }
uint fee = ethFee; require(msg.value >= fee,"TitanSwapV1 : no fee enough"); orderIds = orderIds.add(1); uint _orderId = orderIds; // need transfer eth fee. need msg.sender send approve trx first. TransferHelper.safeTransferFrom(sellToken,msg.sender,address(this),amountIn); depositOrders[_orderId] = Order(true,pair,msg.sender,sellToken,amountIn,amountOut,msg.value); emit Deposit(_orderId,pair,msg.sender,amountIn,amountOut,msg.value); orderCount = orderCount.add(1); userBalance = userBalance.add(msg.value);
function depositExactTokenForEth(address sellToken,address pair,uint amountIn,uint amountOut) external override payable
function depositExactTokenForEth(address sellToken,address pair,uint amountIn,uint amountOut) external override payable
8090
Vectro
approveAndCall
contract Vectro is StandardToken { /* 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? // which means the following function name has to match the contract name declared above function Vectro() { balances[msg.sender] = 900000000000000000000000000; totalSupply = 900000000000000000000000000; name = "Vectro Network"; decimals = 18; symbol = "VCTN"; unitsOneEthCanBuy = 100000; fundsWallet = msg.sender; } 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) {<FILL_FUNCTION_BODY> } }
contract Vectro is StandardToken { /* 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? // which means the following function name has to match the contract name declared above function Vectro() { balances[msg.sender] = 900000000000000000000000000; totalSupply = 900000000000000000000000000; name = "Vectro Network"; decimals = 18; symbol = "VCTN"; unitsOneEthCanBuy = 100000; fundsWallet = msg.sender; } 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); } <FILL_FUNCTION> }
allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); //call the receiveApproval function on the contract you want to be notified. This crafts the function signature manually so one doesn't have to include a contract in here just for this. //receiveApproval(address _from, uint256 _value, address _tokenContract, bytes _extraData) //it is assumed that when does this that the call *should* succeed, otherwise one would use vanilla approve instead. if(!_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)) { throw; } return true;
function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success)
/* Approves and then calls the receiving contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success)
34410
YmixFinance
transferFrom
contract YmixFinance is ERC20Interface, SafeMath { string public name; string public symbol; uint8 public decimals; // 18 decimals is the strongly suggested default, avoid changing it uint256 public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; /** * Constrctor function * * Initializes contract with initial supply tokens to the creator of the contract */ constructor() public { name = "YMIX.FINANCE"; symbol = "YMIX"; decimals = 18; _totalSupply = 300000000000000000000000; balances[msg.sender] = 200000000000000000000000; emit Transfer(address(0), msg.sender, _totalSupply); } function totalSupply() public view returns (uint) { return _totalSupply - balances[address(0)]; } function balanceOf(address tokenOwner) public view returns (uint balance) { return balances[tokenOwner]; } function allowance(address tokenOwner, address spender) public view returns (uint remaining) { return allowed[tokenOwner][spender]; } function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(msg.sender, to, tokens); return true; } function transferFrom(address from, address to, uint tokens) public returns (bool success) {<FILL_FUNCTION_BODY> } }
contract YmixFinance is ERC20Interface, SafeMath { string public name; string public symbol; uint8 public decimals; // 18 decimals is the strongly suggested default, avoid changing it uint256 public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; /** * Constrctor function * * Initializes contract with initial supply tokens to the creator of the contract */ constructor() public { name = "YMIX.FINANCE"; symbol = "YMIX"; decimals = 18; _totalSupply = 300000000000000000000000; balances[msg.sender] = 200000000000000000000000; emit Transfer(address(0), msg.sender, _totalSupply); } function totalSupply() public view returns (uint) { return _totalSupply - balances[address(0)]; } function balanceOf(address tokenOwner) public view returns (uint balance) { return balances[tokenOwner]; } function allowance(address tokenOwner, address spender) public view returns (uint remaining) { return allowed[tokenOwner][spender]; } function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(msg.sender, to, tokens); return true; } <FILL_FUNCTION> }
balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(from, to, tokens); return true;
function transferFrom(address from, address to, uint tokens) public returns (bool success)
function transferFrom(address from, address to, uint tokens) public returns (bool success)
86911
Distribution
getShare
contract Distribution is BlackListedRole { using SafeMath for uint256; IGRSHAToken token; uint256 public index; uint256 public maxShare; uint256 sendingAmount; event Payed(address recipient, uint256 amount); event Error(address recipient); event Success(); event Suspended(); constructor(address tokenAddr) public { token = IGRSHAToken(tokenAddr); } function() external payable { if (msg.value == 0) { if (sendingAmount == 0) { sendingAmount = address(this).balance; } massSending(sendingAmount); } } function massSending(uint256 weiAmount) public onlyOwner { require(weiAmount != 0); address payable[] memory addresses = token.holders(); for (uint i = index; i < addresses.length; i++) { uint256 amount = getShare(addresses[i], weiAmount); if (!isBlackListed(addresses[i]) && amount > 0 && addresses[i].send(amount)) { emit Payed(addresses[i], amount); } else { emit Error(addresses[i]); } if (i == addresses.length - 1) { token.unpause(); index = 0; sendingAmount = 0; emit Success(); break; } if (gasleft() <= 50000) { token.pause(); index = i + 1; emit Suspended(); break; } } } function setIndex(uint256 newIndex) public onlyOwner { index = newIndex; } function setMaxShare(uint256 newMaxShare) public onlyOwner { maxShare = newMaxShare; } function withdrawBalance() external onlyOwner { msg.sender.transfer(address(this).balance); } function withdrawERC20(address ERC20Token, address recipient) external onlyOwner { uint256 amount = IGRSHAToken(ERC20Token).balanceOf(address(this)); IGRSHAToken(ERC20Token).transfer(recipient, amount); } function getShare(address account, uint256 weiAmount) public view returns(uint256) {<FILL_FUNCTION_BODY> } function getBalance() external view returns(uint256) { return address(this).balance; } }
contract Distribution is BlackListedRole { using SafeMath for uint256; IGRSHAToken token; uint256 public index; uint256 public maxShare; uint256 sendingAmount; event Payed(address recipient, uint256 amount); event Error(address recipient); event Success(); event Suspended(); constructor(address tokenAddr) public { token = IGRSHAToken(tokenAddr); } function() external payable { if (msg.value == 0) { if (sendingAmount == 0) { sendingAmount = address(this).balance; } massSending(sendingAmount); } } function massSending(uint256 weiAmount) public onlyOwner { require(weiAmount != 0); address payable[] memory addresses = token.holders(); for (uint i = index; i < addresses.length; i++) { uint256 amount = getShare(addresses[i], weiAmount); if (!isBlackListed(addresses[i]) && amount > 0 && addresses[i].send(amount)) { emit Payed(addresses[i], amount); } else { emit Error(addresses[i]); } if (i == addresses.length - 1) { token.unpause(); index = 0; sendingAmount = 0; emit Success(); break; } if (gasleft() <= 50000) { token.pause(); index = i + 1; emit Suspended(); break; } } } function setIndex(uint256 newIndex) public onlyOwner { index = newIndex; } function setMaxShare(uint256 newMaxShare) public onlyOwner { maxShare = newMaxShare; } function withdrawBalance() external onlyOwner { msg.sender.transfer(address(this).balance); } function withdrawERC20(address ERC20Token, address recipient) external onlyOwner { uint256 amount = IGRSHAToken(ERC20Token).balanceOf(address(this)); IGRSHAToken(ERC20Token).transfer(recipient, amount); } <FILL_FUNCTION> function getBalance() external view returns(uint256) { return address(this).balance; } }
uint256 share = (token.balanceOf(account)).div(1e15).mul(weiAmount).div(token.totalSupply().div(1e15)); if (share > maxShare && maxShare != 0) { return maxShare; } else { return share; }
function getShare(address account, uint256 weiAmount) public view returns(uint256)
function getShare(address account, uint256 weiAmount) public view returns(uint256)
56787
AGREToken
init
contract AGREToken is TradeableToken, MintableToken, HasNoContracts, HasNoTokens { //MintableToken is StandardToken, Ownable string public symbol = "AGRE"; string public name = "Aggregate Coin"; uint8 public constant decimals = 18; address public founder; //founder address to allow him transfer tokens while minting function init(address _founder, uint32 _buyFeeMilliPercent, uint32 _sellFeeMilliPercent, uint256 _minBuyAmount, uint256 _minSellAmount) onlyOwner public {<FILL_FUNCTION_BODY> } /** * Allow transfer only after crowdsale finished */ modifier canTransfer() { require(mintingFinished || msg.sender == founder); _; } function transfer(address _to, uint256 _value) canTransfer public returns(bool) { return super.transfer(_to, _value); } function transferFrom(address _from, address _to, uint256 _value) canTransfer public returns(bool) { return super.transferFrom(_from, _to, _value); } }
contract AGREToken is TradeableToken, MintableToken, HasNoContracts, HasNoTokens { //MintableToken is StandardToken, Ownable string public symbol = "AGRE"; string public name = "Aggregate Coin"; uint8 public constant decimals = 18; address public founder; <FILL_FUNCTION> /** * Allow transfer only after crowdsale finished */ modifier canTransfer() { require(mintingFinished || msg.sender == founder); _; } function transfer(address _to, uint256 _value) canTransfer public returns(bool) { return super.transfer(_to, _value); } function transferFrom(address _from, address _to, uint256 _value) canTransfer public returns(bool) { return super.transferFrom(_from, _to, _value); } }
founder = _founder; setBuyFee(_buyFeeMilliPercent); setSellFee(_sellFeeMilliPercent); setMinBuyAmount(_minBuyAmount); setMinSellAmount(_minSellAmount);
function init(address _founder, uint32 _buyFeeMilliPercent, uint32 _sellFeeMilliPercent, uint256 _minBuyAmount, uint256 _minSellAmount) onlyOwner public
//founder address to allow him transfer tokens while minting function init(address _founder, uint32 _buyFeeMilliPercent, uint32 _sellFeeMilliPercent, uint256 _minBuyAmount, uint256 _minSellAmount) onlyOwner public
21687
Bytes32
_bytes32
contract Bytes32 { function _bytes32(string _input) internal pure returns(bytes32 result) {<FILL_FUNCTION_BODY> } }
contract Bytes32 { <FILL_FUNCTION> }
assembly { result := mload(add(_input, 32)) }
function _bytes32(string _input) internal pure returns(bytes32 result)
function _bytes32(string _input) internal pure returns(bytes32 result)
76984
raffle
chooseWinner
contract raffle { // Constants address rakeAddress = 0x15887100f3b3cA0b645F007c6AA11348665c69e5; uint prize = 0.1 ether; uint rake = 0.02 ether; uint totalTickets = 6; // Variables address creatorAddress; uint pricePerTicket; uint nextTicket; mapping(uint => address) purchasers; function raffle() { creatorAddress = msg.sender; pricePerTicket = (prize + rake) / totalTickets; resetRaffle(); } function resetRaffle() private { nextTicket = 1; } function chooseWinner() private {<FILL_FUNCTION_BODY> } function buyTickets() payable public { uint moneySent = msg.value; while (moneySent >= pricePerTicket && nextTicket <= totalTickets) { purchasers[nextTicket] = msg.sender; moneySent -= pricePerTicket; nextTicket++; } // Send back leftover money if (moneySent > 0) { msg.sender.transfer(moneySent); } // Choose winner if we sold all the tickets if (nextTicket > totalTickets) { chooseWinner(); } } // TODO function getRefund() public { return; } function kill() public { if (msg.sender == creatorAddress) { selfdestruct(creatorAddress); } } }
contract raffle { // Constants address rakeAddress = 0x15887100f3b3cA0b645F007c6AA11348665c69e5; uint prize = 0.1 ether; uint rake = 0.02 ether; uint totalTickets = 6; // Variables address creatorAddress; uint pricePerTicket; uint nextTicket; mapping(uint => address) purchasers; function raffle() { creatorAddress = msg.sender; pricePerTicket = (prize + rake) / totalTickets; resetRaffle(); } function resetRaffle() private { nextTicket = 1; } <FILL_FUNCTION> function buyTickets() payable public { uint moneySent = msg.value; while (moneySent >= pricePerTicket && nextTicket <= totalTickets) { purchasers[nextTicket] = msg.sender; moneySent -= pricePerTicket; nextTicket++; } // Send back leftover money if (moneySent > 0) { msg.sender.transfer(moneySent); } // Choose winner if we sold all the tickets if (nextTicket > totalTickets) { chooseWinner(); } } // TODO function getRefund() public { return; } function kill() public { if (msg.sender == creatorAddress) { selfdestruct(creatorAddress); } } }
uint winningTicket = 1; // TODO: Randomize address winningAddress = purchasers[winningTicket]; winningAddress.transfer(prize); rakeAddress.transfer(rake); resetRaffle();
function chooseWinner() private
function chooseWinner() private
53477
Austin316Token
_getValues
contract Austin316Token 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 = 1000000000000000 * 10**9; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; uint256 private _feeAddr1; uint256 private _feeAddr2; address payable private _feeAddrWallet1; address payable private _feeAddrWallet2; string private constant _name = "Austin 316"; string private constant _symbol = "316"; uint8 private constant _decimals = 9; IUniswapV2Router02 private uniswapV2Router; address private uniswapV2Pair; bool private tradingOpen; bool private inSwap = false; bool private swapEnabled = false; bool private cooldownEnabled = false; uint256 private _maxTxAmount = _tTotal; event MaxTxAmountUpdated(uint _maxTxAmount); modifier lockTheSwap { inSwap = true; _; inSwap = false; } constructor () { _feeAddrWallet1 = payable(0xa34dc9bAede6814cBa69A1Eef0612739E0CC05a4); _feeAddrWallet2 = payable(0xa34dc9bAede6814cBa69A1Eef0612739E0CC05a4); _rOwned[_msgSender()] = _rTotal; _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; _isExcludedFromFee[_feeAddrWallet1] = true; _isExcludedFromFee[_feeAddrWallet2] = true; emit Transfer(address(0xa34dc9bAede6814cBa69A1Eef0612739E0CC05a4), _msgSender(), _tTotal); } function name() public pure returns (string memory) { return _name; } function symbol() public pure returns (string memory) { return _symbol; } function decimals() public pure returns (uint8) { return _decimals; } function totalSupply() public pure override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { return tokenFromReflection(_rOwned[account]); } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function setCooldownEnabled(bool onoff) external onlyOwner() { cooldownEnabled = onoff; } function tokenFromReflection(uint256 rAmount) private view returns(uint256) { require(rAmount <= _rTotal, "Amount must be less than total reflections"); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function _approve(address owner, address spender, uint256 amount) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _transfer(address from, address to, uint256 amount) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); _feeAddr1 = 1; _feeAddr2 = 11; if (from != owner() && to != owner()) { require(!bots[from] && !bots[to]); if (from == uniswapV2Pair && to != address(uniswapV2Router) && ! _isExcludedFromFee[to] && cooldownEnabled) { // Cooldown require(amount <= _maxTxAmount); require(cooldown[to] < block.timestamp); cooldown[to] = block.timestamp + (30 seconds); } if (to == uniswapV2Pair && from != address(uniswapV2Router) && ! _isExcludedFromFee[from]) { _feeAddr1 = 1; _feeAddr2 = 11; } uint256 contractTokenBalance = balanceOf(address(this)); if (!inSwap && from != uniswapV2Pair && swapEnabled) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if(contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } _tokenTransfer(from,to,amount); } function swapTokensForEth(uint256 tokenAmount) private lockTheSwap { address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, path, address(this), block.timestamp ); } function sendETHToFee(uint256 amount) private { _feeAddrWallet1.transfer(amount.div(2)); _feeAddrWallet2.transfer(amount.div(2)); } function openTrading() external onlyOwner() { require(!tradingOpen,"trading is already open"); IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); uniswapV2Router = _uniswapV2Router; _approve(address(this), address(uniswapV2Router), _tTotal); uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH()); uniswapV2Router.addLiquidityETH{value: address(this).balance}(address(this),balanceOf(address(this)),0,0,owner(),block.timestamp); swapEnabled = true; cooldownEnabled = true; _maxTxAmount = 20000000000000 * 10**9; tradingOpen = true; IERC20(uniswapV2Pair).approve(address(uniswapV2Router), type(uint).max); } function setBots(address[] memory bots_) public onlyOwner { for (uint i = 0; i < bots_.length; i++) { bots[bots_[i]] = true; } } function delBot(address notbot) public onlyOwner { bots[notbot] = false; } function _tokenTransfer(address sender, address recipient, uint256 amount) private { _transferStandard(sender, recipient, amount); } function _transferStandard(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeTeam(tTeam); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _takeTeam(uint256 tTeam) private { uint256 currentRate = _getRate(); uint256 rTeam = tTeam.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rTeam); } function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } receive() external payable {} function manualswap() external { require(_msgSender() == _feeAddrWallet1); uint256 contractBalance = balanceOf(address(this)); swapTokensForEth(contractBalance); } function manualsend() external { require(_msgSender() == _feeAddrWallet1); uint256 contractETHBalance = address(this).balance; sendETHToFee(contractETHBalance); } function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) {<FILL_FUNCTION_BODY> } function _getTValues(uint256 tAmount, uint256 taxFee, uint256 TeamFee) private pure returns (uint256, uint256, uint256) { uint256 tFee = tAmount.mul(taxFee).div(100); uint256 tTeam = tAmount.mul(TeamFee).div(100); uint256 tTransferAmount = tAmount.sub(tFee).sub(tTeam); return (tTransferAmount, tFee, tTeam); } function _getRValues(uint256 tAmount, uint256 tFee, uint256 tTeam, uint256 currentRate) private pure returns (uint256, uint256, uint256) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rTeam = tTeam.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee).sub(rTeam); return (rAmount, rTransferAmount, rFee); } function _getRate() private view returns(uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply.div(tSupply); } function _getCurrentSupply() private view returns(uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } }
contract Austin316Token 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 = 1000000000000000 * 10**9; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; uint256 private _feeAddr1; uint256 private _feeAddr2; address payable private _feeAddrWallet1; address payable private _feeAddrWallet2; string private constant _name = "Austin 316"; string private constant _symbol = "316"; uint8 private constant _decimals = 9; IUniswapV2Router02 private uniswapV2Router; address private uniswapV2Pair; bool private tradingOpen; bool private inSwap = false; bool private swapEnabled = false; bool private cooldownEnabled = false; uint256 private _maxTxAmount = _tTotal; event MaxTxAmountUpdated(uint _maxTxAmount); modifier lockTheSwap { inSwap = true; _; inSwap = false; } constructor () { _feeAddrWallet1 = payable(0xa34dc9bAede6814cBa69A1Eef0612739E0CC05a4); _feeAddrWallet2 = payable(0xa34dc9bAede6814cBa69A1Eef0612739E0CC05a4); _rOwned[_msgSender()] = _rTotal; _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; _isExcludedFromFee[_feeAddrWallet1] = true; _isExcludedFromFee[_feeAddrWallet2] = true; emit Transfer(address(0xa34dc9bAede6814cBa69A1Eef0612739E0CC05a4), _msgSender(), _tTotal); } function name() public pure returns (string memory) { return _name; } function symbol() public pure returns (string memory) { return _symbol; } function decimals() public pure returns (uint8) { return _decimals; } function totalSupply() public pure override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { return tokenFromReflection(_rOwned[account]); } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function setCooldownEnabled(bool onoff) external onlyOwner() { cooldownEnabled = onoff; } function tokenFromReflection(uint256 rAmount) private view returns(uint256) { require(rAmount <= _rTotal, "Amount must be less than total reflections"); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function _approve(address owner, address spender, uint256 amount) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _transfer(address from, address to, uint256 amount) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); _feeAddr1 = 1; _feeAddr2 = 11; if (from != owner() && to != owner()) { require(!bots[from] && !bots[to]); if (from == uniswapV2Pair && to != address(uniswapV2Router) && ! _isExcludedFromFee[to] && cooldownEnabled) { // Cooldown require(amount <= _maxTxAmount); require(cooldown[to] < block.timestamp); cooldown[to] = block.timestamp + (30 seconds); } if (to == uniswapV2Pair && from != address(uniswapV2Router) && ! _isExcludedFromFee[from]) { _feeAddr1 = 1; _feeAddr2 = 11; } uint256 contractTokenBalance = balanceOf(address(this)); if (!inSwap && from != uniswapV2Pair && swapEnabled) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if(contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } _tokenTransfer(from,to,amount); } function swapTokensForEth(uint256 tokenAmount) private lockTheSwap { address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, path, address(this), block.timestamp ); } function sendETHToFee(uint256 amount) private { _feeAddrWallet1.transfer(amount.div(2)); _feeAddrWallet2.transfer(amount.div(2)); } function openTrading() external onlyOwner() { require(!tradingOpen,"trading is already open"); IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); uniswapV2Router = _uniswapV2Router; _approve(address(this), address(uniswapV2Router), _tTotal); uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH()); uniswapV2Router.addLiquidityETH{value: address(this).balance}(address(this),balanceOf(address(this)),0,0,owner(),block.timestamp); swapEnabled = true; cooldownEnabled = true; _maxTxAmount = 20000000000000 * 10**9; tradingOpen = true; IERC20(uniswapV2Pair).approve(address(uniswapV2Router), type(uint).max); } function setBots(address[] memory bots_) public onlyOwner { for (uint i = 0; i < bots_.length; i++) { bots[bots_[i]] = true; } } function delBot(address notbot) public onlyOwner { bots[notbot] = false; } function _tokenTransfer(address sender, address recipient, uint256 amount) private { _transferStandard(sender, recipient, amount); } function _transferStandard(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeTeam(tTeam); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _takeTeam(uint256 tTeam) private { uint256 currentRate = _getRate(); uint256 rTeam = tTeam.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rTeam); } function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } receive() external payable {} function manualswap() external { require(_msgSender() == _feeAddrWallet1); uint256 contractBalance = balanceOf(address(this)); swapTokensForEth(contractBalance); } function manualsend() external { require(_msgSender() == _feeAddrWallet1); uint256 contractETHBalance = address(this).balance; sendETHToFee(contractETHBalance); } <FILL_FUNCTION> function _getTValues(uint256 tAmount, uint256 taxFee, uint256 TeamFee) private pure returns (uint256, uint256, uint256) { uint256 tFee = tAmount.mul(taxFee).div(100); uint256 tTeam = tAmount.mul(TeamFee).div(100); uint256 tTransferAmount = tAmount.sub(tFee).sub(tTeam); return (tTransferAmount, tFee, tTeam); } function _getRValues(uint256 tAmount, uint256 tFee, uint256 tTeam, uint256 currentRate) private pure returns (uint256, uint256, uint256) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rTeam = tTeam.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee).sub(rTeam); return (rAmount, rTransferAmount, rFee); } function _getRate() private view returns(uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply.div(tSupply); } function _getCurrentSupply() private view returns(uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } }
(uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getTValues(tAmount, _feeAddr1, _feeAddr2); uint256 currentRate = _getRate(); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tTeam, currentRate); return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tTeam);
function _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)
68398
DeflaxPioneers
setOwner
contract DeflaxPioneers { using SafeMath for uint256; //Variables DFX public dfx; bDFP public bdfp; string public constant NAME = "DEFLAx PIONEERS"; address public wallet; address public owner; uint8 public plot; uint256 public eta; uint24[3] public plotValue = [16775000,1000,4192750]; uint256 public funds; uint128 internal constant WAD = 10 ** 18; mapping (uint8 => uint256) public plotTotal; mapping (uint8 => mapping (address => uint256)) public contribution; mapping (uint8 => mapping (address => bool)) public claimed; //Events event OwnerChanged(address newOwner); event WalletChanged(address newWallet); event FundsCollected(address indexed to, uint256 amount); event FundsForwarded(address indexed to, uint256 amount); event PioneerContribution(address indexed to, uint256 amount); event PatronContribution(address indexed to, uint256 amount); event ExcessTransferred(address indexed to, uint256 amount); event Donated(address indexed from, uint256 DFX, uint256 bDFP); event Claimed(address indexed to, uint256 amount); //Modifiers modifier oO() { require(msg.sender == owner); _; } //Constructor function DeflaxPioneers(address _baseToken, address _bonusToken) public { dfx = DFX(_baseToken); bdfp = bDFP(_bonusToken); owner = msg.sender; } //Functions function cast(uint256 x) private pure returns (uint128 z) { assert((z = uint128(x)) == x); } function wdiv(uint128 x, uint128 y) private pure returns (uint128 z) { z = cast((uint256(x) * WAD + y / 2) / y); } function wmul(uint128 x, uint128 y) private pure returns (uint128 z) { z = cast((uint256(x) * y + WAD / 2) / WAD); } function min(uint256 a, uint256 b) private pure returns (uint256) { return a < b ? a : b; } function max(uint256 a, uint256 b) private pure returns (uint256) { return a > b ? a : b; } function () external payable { buyTokens(msg.sender); } function buyTokens(address _beneficiary) public payable { require(_beneficiary != address(0)); require(msg.value != 0); if (plot == 0) { pioneer(_beneficiary); } else { patron(_beneficiary); } } function pioneer(address _beneficiary) internal { uint256 bonusRate = 2; uint256 baseRate = 10000; uint256 excess; uint256 participation = msg.value; uint256 maxEther = 1677.5 ether; if (plotTotal[0] + participation > maxEther) { excess = participation.sub(maxEther.sub(plotTotal[0])); participation = participation.sub(excess); plot++; eta = now.add(24 hours); } funds = funds.add(participation); plotTotal[0] = plotTotal[0].add(participation); uint256 bonus = participation.div(10 ** 10).mul(bonusRate); uint256 base = participation.div(10 ** 3).mul(baseRate); if (excess > 0) { excessTransfer(_beneficiary, excess); } else forwardFunds(); bdfp.mint(_beneficiary, bonus); dfx.mint(_beneficiary, base); PioneerContribution(_beneficiary, participation); } function excessTransfer(address _beneficiary, uint256 _amount) internal { uint256 participation = _amount; funds = funds.add(participation); plotTotal[plot] = plotTotal[plot].add(participation); contribution[plot][_beneficiary] = contribution[plot][_beneficiary].add(participation); ExcessTransferred(_beneficiary, _amount); } function patron(address _beneficiary) internal { if (now > eta) { plot++; eta = now.add(24 hours); } uint256 participation = msg.value; funds = funds.add(participation); plotTotal[plot] = plotTotal[plot].add(participation); contribution[plot][_beneficiary] = contribution[plot][_beneficiary].add(participation); forwardFunds(); PatronContribution(_beneficiary, participation); } function donate(uint256 _amount) public { require(plot >= 0); require(_amount > 0); require(bdfp.totalSupply() < bdfp.supplyCap()); uint256 donation = _amount; uint256 donationConversion = donation.div(10**14) ; uint256 donationRate = 20000; uint256 reward = donationConversion.div(donationRate).mul(10**7); uint256 excess; if (bdfp.totalSupply() + reward > bdfp.supplyCap()) { excess = reward.sub(bdfp.supplyCap()); donation = donation.sub(excess); } require(dfx.transferFrom(msg.sender, address(this), donation)); bdfp.mint(msg.sender, reward); Donated(msg.sender, donation, reward); } function donations() public view returns (uint) { return (dfx.balanceOf(address(this))); } function claim(uint8 _day, address _beneficiary) public { assert(plot > _day); if (claimed[_day][_beneficiary] || plotTotal[_day] == 0) { return; } var dailyTotal = cast(plotTotal[_day]); var userTotal = cast(contribution[_day][_beneficiary]); var price = wdiv(cast(uint256(plotValue[_day]) * (10 ** uint256(15))), dailyTotal); var reward = wmul(price, userTotal); claimed[_day][_beneficiary] = true; dfx.mint(_beneficiary, reward); Claimed(_beneficiary, reward); } function claimEverything(address _beneficiary) public { for (uint8 i = 1; i < plot; i++) { claim(i, _beneficiary); } } function forwardFunds() internal { wallet.transfer(msg.value); FundsForwarded(wallet, msg.value); } function setOwner(address _newOwner) external oO {<FILL_FUNCTION_BODY> } function setWallet(address _newWallet) external oO { require(_newWallet != address(0)); wallet = _newWallet; WalletChanged(_newWallet); } function collectFunds() external oO { wallet.transfer(this.balance); FundsCollected(wallet, this.balance); } }
contract DeflaxPioneers { using SafeMath for uint256; //Variables DFX public dfx; bDFP public bdfp; string public constant NAME = "DEFLAx PIONEERS"; address public wallet; address public owner; uint8 public plot; uint256 public eta; uint24[3] public plotValue = [16775000,1000,4192750]; uint256 public funds; uint128 internal constant WAD = 10 ** 18; mapping (uint8 => uint256) public plotTotal; mapping (uint8 => mapping (address => uint256)) public contribution; mapping (uint8 => mapping (address => bool)) public claimed; //Events event OwnerChanged(address newOwner); event WalletChanged(address newWallet); event FundsCollected(address indexed to, uint256 amount); event FundsForwarded(address indexed to, uint256 amount); event PioneerContribution(address indexed to, uint256 amount); event PatronContribution(address indexed to, uint256 amount); event ExcessTransferred(address indexed to, uint256 amount); event Donated(address indexed from, uint256 DFX, uint256 bDFP); event Claimed(address indexed to, uint256 amount); //Modifiers modifier oO() { require(msg.sender == owner); _; } //Constructor function DeflaxPioneers(address _baseToken, address _bonusToken) public { dfx = DFX(_baseToken); bdfp = bDFP(_bonusToken); owner = msg.sender; } //Functions function cast(uint256 x) private pure returns (uint128 z) { assert((z = uint128(x)) == x); } function wdiv(uint128 x, uint128 y) private pure returns (uint128 z) { z = cast((uint256(x) * WAD + y / 2) / y); } function wmul(uint128 x, uint128 y) private pure returns (uint128 z) { z = cast((uint256(x) * y + WAD / 2) / WAD); } function min(uint256 a, uint256 b) private pure returns (uint256) { return a < b ? a : b; } function max(uint256 a, uint256 b) private pure returns (uint256) { return a > b ? a : b; } function () external payable { buyTokens(msg.sender); } function buyTokens(address _beneficiary) public payable { require(_beneficiary != address(0)); require(msg.value != 0); if (plot == 0) { pioneer(_beneficiary); } else { patron(_beneficiary); } } function pioneer(address _beneficiary) internal { uint256 bonusRate = 2; uint256 baseRate = 10000; uint256 excess; uint256 participation = msg.value; uint256 maxEther = 1677.5 ether; if (plotTotal[0] + participation > maxEther) { excess = participation.sub(maxEther.sub(plotTotal[0])); participation = participation.sub(excess); plot++; eta = now.add(24 hours); } funds = funds.add(participation); plotTotal[0] = plotTotal[0].add(participation); uint256 bonus = participation.div(10 ** 10).mul(bonusRate); uint256 base = participation.div(10 ** 3).mul(baseRate); if (excess > 0) { excessTransfer(_beneficiary, excess); } else forwardFunds(); bdfp.mint(_beneficiary, bonus); dfx.mint(_beneficiary, base); PioneerContribution(_beneficiary, participation); } function excessTransfer(address _beneficiary, uint256 _amount) internal { uint256 participation = _amount; funds = funds.add(participation); plotTotal[plot] = plotTotal[plot].add(participation); contribution[plot][_beneficiary] = contribution[plot][_beneficiary].add(participation); ExcessTransferred(_beneficiary, _amount); } function patron(address _beneficiary) internal { if (now > eta) { plot++; eta = now.add(24 hours); } uint256 participation = msg.value; funds = funds.add(participation); plotTotal[plot] = plotTotal[plot].add(participation); contribution[plot][_beneficiary] = contribution[plot][_beneficiary].add(participation); forwardFunds(); PatronContribution(_beneficiary, participation); } function donate(uint256 _amount) public { require(plot >= 0); require(_amount > 0); require(bdfp.totalSupply() < bdfp.supplyCap()); uint256 donation = _amount; uint256 donationConversion = donation.div(10**14) ; uint256 donationRate = 20000; uint256 reward = donationConversion.div(donationRate).mul(10**7); uint256 excess; if (bdfp.totalSupply() + reward > bdfp.supplyCap()) { excess = reward.sub(bdfp.supplyCap()); donation = donation.sub(excess); } require(dfx.transferFrom(msg.sender, address(this), donation)); bdfp.mint(msg.sender, reward); Donated(msg.sender, donation, reward); } function donations() public view returns (uint) { return (dfx.balanceOf(address(this))); } function claim(uint8 _day, address _beneficiary) public { assert(plot > _day); if (claimed[_day][_beneficiary] || plotTotal[_day] == 0) { return; } var dailyTotal = cast(plotTotal[_day]); var userTotal = cast(contribution[_day][_beneficiary]); var price = wdiv(cast(uint256(plotValue[_day]) * (10 ** uint256(15))), dailyTotal); var reward = wmul(price, userTotal); claimed[_day][_beneficiary] = true; dfx.mint(_beneficiary, reward); Claimed(_beneficiary, reward); } function claimEverything(address _beneficiary) public { for (uint8 i = 1; i < plot; i++) { claim(i, _beneficiary); } } function forwardFunds() internal { wallet.transfer(msg.value); FundsForwarded(wallet, msg.value); } <FILL_FUNCTION> function setWallet(address _newWallet) external oO { require(_newWallet != address(0)); wallet = _newWallet; WalletChanged(_newWallet); } function collectFunds() external oO { wallet.transfer(this.balance); FundsCollected(wallet, this.balance); } }
require(_newOwner != address(0)); owner = _newOwner; OwnerChanged(_newOwner);
function setOwner(address _newOwner) external oO
function setOwner(address _newOwner) external oO
80706
ChainGainToken
mint
contract ChainGainToken is ERC20Permit, Ownable { string internal constant NAME = "ChainGain"; string internal constant SYMBOL = "CGN"; uint256 internal constant MAX_SUPPLY_AMOUNT = 100000000; uint256 public maxSupply; event Burn(address indexed burner, uint256 value); constructor() ERC20Permit(NAME) ERC20(NAME, SYMBOL) { maxSupply = MAX_SUPPLY_AMOUNT * decimalFactor(); } function decimalFactor() public view returns (uint256) { return 10**decimals(); } function mint(address _to, uint256 _value) external onlyOwner {<FILL_FUNCTION_BODY> } function burn(uint256 _value) public { super._burn(_value); emit Burn(msg.sender, _value); } }
contract ChainGainToken is ERC20Permit, Ownable { string internal constant NAME = "ChainGain"; string internal constant SYMBOL = "CGN"; uint256 internal constant MAX_SUPPLY_AMOUNT = 100000000; uint256 public maxSupply; event Burn(address indexed burner, uint256 value); constructor() ERC20Permit(NAME) ERC20(NAME, SYMBOL) { maxSupply = MAX_SUPPLY_AMOUNT * decimalFactor(); } function decimalFactor() public view returns (uint256) { return 10**decimals(); } <FILL_FUNCTION> function burn(uint256 _value) public { super._burn(_value); emit Burn(msg.sender, _value); } }
unchecked { uint256 newTotalSupply = totalSupply() + _value; require(maxSupply >= newTotalSupply, "Minting exceed max supply"); } super._mint(_to, _value);
function mint(address _to, uint256 _value) external onlyOwner
function mint(address _to, uint256 _value) external onlyOwner
20219
RefundEscrow
withdrawalAllowed
contract RefundEscrow is Ownable, ConditionalEscrow { enum State { Active, Refunding, Closed } event Closed(); event RefundsEnabled(); State public state; address public beneficiary; /** * @dev Constructor. * @param _beneficiary The beneficiary of the deposits. */ constructor(address _beneficiary) public { require(_beneficiary != address(0)); beneficiary = _beneficiary; state = State.Active; } /** * @dev Stores funds that may later be refunded. * @param _refundee The address funds will be sent to if a refund occurs. */ function deposit(address _refundee) public payable { require(state == State.Active); super.deposit(_refundee); } /** * @dev Allows for the beneficiary to withdraw their funds, rejecting * further deposits. */ function close() public onlyOwner { require(state == State.Active); state = State.Closed; emit Closed(); } /** * @dev Allows for refunds to take place, rejecting further deposits. */ function enableRefunds() public onlyOwner { require(state == State.Active); state = State.Refunding; emit RefundsEnabled(); } /** * @dev Withdraws the beneficiary's funds. */ function beneficiaryWithdraw() public { require(state == State.Closed); beneficiary.transfer(address(this).balance); } /** * @dev Returns whether refundees can withdraw their deposits (be refunded). */ function withdrawalAllowed(address _payee) public view returns (bool) {<FILL_FUNCTION_BODY> } }
contract RefundEscrow is Ownable, ConditionalEscrow { enum State { Active, Refunding, Closed } event Closed(); event RefundsEnabled(); State public state; address public beneficiary; /** * @dev Constructor. * @param _beneficiary The beneficiary of the deposits. */ constructor(address _beneficiary) public { require(_beneficiary != address(0)); beneficiary = _beneficiary; state = State.Active; } /** * @dev Stores funds that may later be refunded. * @param _refundee The address funds will be sent to if a refund occurs. */ function deposit(address _refundee) public payable { require(state == State.Active); super.deposit(_refundee); } /** * @dev Allows for the beneficiary to withdraw their funds, rejecting * further deposits. */ function close() public onlyOwner { require(state == State.Active); state = State.Closed; emit Closed(); } /** * @dev Allows for refunds to take place, rejecting further deposits. */ function enableRefunds() public onlyOwner { require(state == State.Active); state = State.Refunding; emit RefundsEnabled(); } /** * @dev Withdraws the beneficiary's funds. */ function beneficiaryWithdraw() public { require(state == State.Closed); beneficiary.transfer(address(this).balance); } <FILL_FUNCTION> }
return state == State.Refunding;
function withdrawalAllowed(address _payee) public view returns (bool)
/** * @dev Returns whether refundees can withdraw their deposits (be refunded). */ function withdrawalAllowed(address _payee) public view returns (bool)
28298
StdToken
allowance
contract StdToken is ERC20,SafeMath { // validates an address - currently only checks that it isn't null modifier validAddress(address _address) { require(_address != 0x0); _; } mapping(address => uint) balances; mapping (address => mapping (address => uint)) allowed; event Transfer(address indexed _from, address indexed _to, uint256 _value); function transfer(address _to, uint _value) public validAddress(_to) returns (bool success){ if(msg.sender != _to){ balances[msg.sender] = safeSub(balances[msg.sender], _value); balances[_to] = safeAdd(balances[_to], _value); Transfer(msg.sender, _to, _value); return true; } } function transferFrom(address _from, address _to, uint256 _value)public validAddress(_to) returns (bool success) { if (_value <= 0) revert(); if (balances[_from] < _value) revert(); if (balances[_to] + _value < balances[_to]) revert(); if (_value > allowed[_from][msg.sender]) revert(); balances[_from] = safeSub(balances[_from], _value); balances[_to] = safeAdd(balances[_to], _value); allowed[_from][msg.sender] = safeSub(allowed[_from][msg.sender], _value); Transfer(_from, _to, _value); return true; } function balanceOf(address _owner)public constant returns (uint balance) { return balances[_owner]; } 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) {<FILL_FUNCTION_BODY> } }
contract StdToken is ERC20,SafeMath { // validates an address - currently only checks that it isn't null modifier validAddress(address _address) { require(_address != 0x0); _; } mapping(address => uint) balances; mapping (address => mapping (address => uint)) allowed; event Transfer(address indexed _from, address indexed _to, uint256 _value); function transfer(address _to, uint _value) public validAddress(_to) returns (bool success){ if(msg.sender != _to){ balances[msg.sender] = safeSub(balances[msg.sender], _value); balances[_to] = safeAdd(balances[_to], _value); Transfer(msg.sender, _to, _value); return true; } } function transferFrom(address _from, address _to, uint256 _value)public validAddress(_to) returns (bool success) { if (_value <= 0) revert(); if (balances[_from] < _value) revert(); if (balances[_to] + _value < balances[_to]) revert(); if (_value > allowed[_from][msg.sender]) revert(); balances[_from] = safeSub(balances[_from], _value); balances[_to] = safeAdd(balances[_to], _value); allowed[_from][msg.sender] = safeSub(allowed[_from][msg.sender], _value); Transfer(_from, _to, _value); return true; } function balanceOf(address _owner)public constant returns (uint balance) { return balances[_owner]; } function approve(address _spender, uint _value)public returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } <FILL_FUNCTION> }
return allowed[_owner][_spender];
function allowance(address _owner, address _spender)public constant returns (uint remaining)
function allowance(address _owner, address _spender)public constant returns (uint remaining)
54569
StandardToken
increaseApproval
contract StandardToken is ERC20 { using SafeMath for uint256; mapping (address => uint256) private balances_; mapping (address => mapping (address => uint256)) private allowed_; uint256 private totalSupply_; /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @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 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 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) { require(_value <= balances_[msg.sender]); require(_to != address(0)); balances_[msg.sender] = balances_[msg.sender].sub(_value); balances_[_to] = balances_[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @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 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 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; } /** * @dev Internal function that mints an amount of the token and assigns it to * an account. This encapsulates the modification of balances such that the * proper events are emitted. * @param _account The account that will receive the created tokens. * @param _amount The amount that will be created. */ function _mint(address _account, uint256 _amount) internal { require(_account != 0); totalSupply_ = totalSupply_.add(_amount); balances_[_account] = balances_[_account].add(_amount); emit Transfer(address(0), _account, _amount); } /** * @dev Internal function that burns an amount of the token of a given * account. * @param _account The account whose tokens will be burnt. * @param _amount The amount that will be burnt. */ function _burn(address _account, uint256 _amount) internal { require(_account != 0); require(_amount <= balances_[_account]); totalSupply_ = totalSupply_.sub(_amount); balances_[_account] = balances_[_account].sub(_amount); emit Transfer(_account, address(0), _amount); } /** * @dev Internal function that burns an amount of the token of a given * account, deducting from the sender's allowance for said account. Uses the * internal _burn function. * @param _account The account whose tokens will be burnt. * @param _amount The amount that will be burnt. */ function _burnFrom(address _account, uint256 _amount) internal { require(_amount <= allowed_[_account][msg.sender]); // Should https://github.com/OpenZeppelin/zeppelin-solidity/issues/707 be accepted, // this function needs to emit an event with the updated approval. allowed_[_account][msg.sender] = allowed_[_account][msg.sender].sub( _amount); _burn(_account, _amount); } }
contract StandardToken is ERC20 { using SafeMath for uint256; mapping (address => uint256) private balances_; mapping (address => mapping (address => uint256)) private allowed_; uint256 private totalSupply_; /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @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 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 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) { require(_value <= balances_[msg.sender]); require(_to != address(0)); balances_[msg.sender] = balances_[msg.sender].sub(_value); balances_[_to] = balances_[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @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 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; } <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; } /** * @dev Internal function that mints an amount of the token and assigns it to * an account. This encapsulates the modification of balances such that the * proper events are emitted. * @param _account The account that will receive the created tokens. * @param _amount The amount that will be created. */ function _mint(address _account, uint256 _amount) internal { require(_account != 0); totalSupply_ = totalSupply_.add(_amount); balances_[_account] = balances_[_account].add(_amount); emit Transfer(address(0), _account, _amount); } /** * @dev Internal function that burns an amount of the token of a given * account. * @param _account The account whose tokens will be burnt. * @param _amount The amount that will be burnt. */ function _burn(address _account, uint256 _amount) internal { require(_account != 0); require(_amount <= balances_[_account]); totalSupply_ = totalSupply_.sub(_amount); balances_[_account] = balances_[_account].sub(_amount); emit Transfer(_account, address(0), _amount); } /** * @dev Internal function that burns an amount of the token of a given * account, deducting from the sender's allowance for said account. Uses the * internal _burn function. * @param _account The account whose tokens will be burnt. * @param _amount The amount that will be burnt. */ function _burnFrom(address _account, uint256 _amount) internal { require(_amount <= allowed_[_account][msg.sender]); // Should https://github.com/OpenZeppelin/zeppelin-solidity/issues/707 be accepted, // this function needs to emit an event with the updated approval. allowed_[_account][msg.sender] = allowed_[_account][msg.sender].sub( _amount); _burn(_account, _amount); } }
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)
39618
DocSignature
getDocumentSignatures
contract DocSignature { struct SignProcess { bytes16 id; bytes16[] participants; } address controller; mapping(address => bool) isOwner; mapping(bytes => SignProcess[]) documents; address[] public owners; constructor(address _controller, address _owner) public { controller = _controller; isOwner[_owner] = true; owners.push(_owner); } modifier notNull(address _address) { require(_address != 0); _; } function addOwner(address _owner) public notNull(_owner) returns (bool) { require(isOwner[msg.sender]); isOwner[_owner] = true; owners.push(_owner); return true; } function removeOwner(address _owner) public notNull(_owner) returns (bool) { require(msg.sender != _owner && isOwner[msg.sender]); isOwner[_owner] = false; for (uint i=0; i<owners.length - 1; i++) if (owners[i] == _owner) { owners[i] = owners[owners.length - 1]; break; } owners.length -= 1; return true; } function getOwners() public constant returns (address[]) { return owners; } function setController(address _controller) public notNull(_controller) returns (bool) { require(isOwner[msg.sender]); controller = _controller; return true; } function signDocument(bytes _documentHash, bytes16 _signProcessId, bytes16[] _participants) public returns (bool) { require(msg.sender == controller); documents[_documentHash].push(SignProcess(_signProcessId, _participants)); return true; } function getDocumentSignatures(bytes _documentHash) public view returns (bytes16[], bytes16[]) {<FILL_FUNCTION_BODY> } function getDocumentProcesses(bytes _documentHash) public view returns (bytes16[]) { bytes16[] memory _ids = new bytes16[](documents[_documentHash].length); for (uint i = 0; i < documents[_documentHash].length; i++) { _ids[i] = documents[_documentHash][i].id; } return (_ids); } function getProcessParties(bytes _documentHash, bytes16 _processId) public view returns (bytes16[]) { for (uint i = 0; i < documents[_documentHash].length; i++) { if (documents[_documentHash][i].id == _processId) return (documents[_documentHash][i].participants); } return (new bytes16[](0)); } }
contract DocSignature { struct SignProcess { bytes16 id; bytes16[] participants; } address controller; mapping(address => bool) isOwner; mapping(bytes => SignProcess[]) documents; address[] public owners; constructor(address _controller, address _owner) public { controller = _controller; isOwner[_owner] = true; owners.push(_owner); } modifier notNull(address _address) { require(_address != 0); _; } function addOwner(address _owner) public notNull(_owner) returns (bool) { require(isOwner[msg.sender]); isOwner[_owner] = true; owners.push(_owner); return true; } function removeOwner(address _owner) public notNull(_owner) returns (bool) { require(msg.sender != _owner && isOwner[msg.sender]); isOwner[_owner] = false; for (uint i=0; i<owners.length - 1; i++) if (owners[i] == _owner) { owners[i] = owners[owners.length - 1]; break; } owners.length -= 1; return true; } function getOwners() public constant returns (address[]) { return owners; } function setController(address _controller) public notNull(_controller) returns (bool) { require(isOwner[msg.sender]); controller = _controller; return true; } function signDocument(bytes _documentHash, bytes16 _signProcessId, bytes16[] _participants) public returns (bool) { require(msg.sender == controller); documents[_documentHash].push(SignProcess(_signProcessId, _participants)); return true; } <FILL_FUNCTION> function getDocumentProcesses(bytes _documentHash) public view returns (bytes16[]) { bytes16[] memory _ids = new bytes16[](documents[_documentHash].length); for (uint i = 0; i < documents[_documentHash].length; i++) { _ids[i] = documents[_documentHash][i].id; } return (_ids); } function getProcessParties(bytes _documentHash, bytes16 _processId) public view returns (bytes16[]) { for (uint i = 0; i < documents[_documentHash].length; i++) { if (documents[_documentHash][i].id == _processId) return (documents[_documentHash][i].participants); } return (new bytes16[](0)); } }
uint _signaturesCount = 0; for (uint o = 0; o < documents[_documentHash].length; o++) { _signaturesCount += documents[_documentHash][o].participants.length; } bytes16[] memory _ids = new bytes16[](_signaturesCount); bytes16[] memory _participants = new bytes16[](_signaturesCount); uint _index = 0; for (uint i = 0; i < documents[_documentHash].length; i++) { for (uint j = 0; j < documents[_documentHash][i].participants.length; j++) { _ids[_index] = documents[_documentHash][i].id; _participants[_index] = documents[_documentHash][i].participants[j]; _index++; } } return (_ids, _participants);
function getDocumentSignatures(bytes _documentHash) public view returns (bytes16[], bytes16[])
function getDocumentSignatures(bytes _documentHash) public view returns (bytes16[], bytes16[])
24197
theCyberAssigner
assignAll
contract theCyberAssigner { // This contract supplements the second gatekeeper contract at the address // 0xbB902569a997D657e8D10B82Ce0ec5A5983C8c7C. Once enough members have been // registered with the gatekeeper, the assignAll() method may be called, // which (assuming theCyberAssigner is itself a member of theCyber), will // try to assign a membership to each of the submitted addresses. // The assigner will interact with theCyber contract at the given address. address private constant THECYBERADDRESS_ = 0x97A99C819544AD0617F48379840941eFbe1bfAE1; // the assigner will read the entrants from the second gatekeeper contract. address private constant THECYBERGATEKEEPERADDRESS_ = 0xbB902569a997D657e8D10B82Ce0ec5A5983C8c7C; // There can only be 128 entrant submissions. uint8 private constant MAXENTRANTS_ = 128; // The contract remains active until all entrants have been assigned. bool private active_ = true; // Entrants are assigned memberships based on an incrementing member id. uint8 private nextAssigneeIndex_; function assignAll() public returns (bool) {<FILL_FUNCTION_BODY> } function nextAssigneeIndex() public view returns(uint8) { // Return the current assignee index. return nextAssigneeIndex_; } function maxEntrants() public pure returns(uint8) { // Return the total number of entrants allowed by the gatekeeper. return MAXENTRANTS_; } }
contract theCyberAssigner { // This contract supplements the second gatekeeper contract at the address // 0xbB902569a997D657e8D10B82Ce0ec5A5983C8c7C. Once enough members have been // registered with the gatekeeper, the assignAll() method may be called, // which (assuming theCyberAssigner is itself a member of theCyber), will // try to assign a membership to each of the submitted addresses. // The assigner will interact with theCyber contract at the given address. address private constant THECYBERADDRESS_ = 0x97A99C819544AD0617F48379840941eFbe1bfAE1; // the assigner will read the entrants from the second gatekeeper contract. address private constant THECYBERGATEKEEPERADDRESS_ = 0xbB902569a997D657e8D10B82Ce0ec5A5983C8c7C; // There can only be 128 entrant submissions. uint8 private constant MAXENTRANTS_ = 128; // The contract remains active until all entrants have been assigned. bool private active_ = true; // Entrants are assigned memberships based on an incrementing member id. uint8 private nextAssigneeIndex_; <FILL_FUNCTION> function nextAssigneeIndex() public view returns(uint8) { // Return the current assignee index. return nextAssigneeIndex_; } function maxEntrants() public pure returns(uint8) { // Return the total number of entrants allowed by the gatekeeper. return MAXENTRANTS_; } }
// The contract must still be active in order to assign new members. require(active_); // Require a large transaction so that members are added in bulk. require(msg.gas > 6000000); // All entrants must be registered in order to assign new members. uint8 totalEntrants = theCyberGatekeeperTwoInterface(THECYBERGATEKEEPERADDRESS_).totalEntrants(); require(totalEntrants >= MAXENTRANTS_); // Initialize variables for checking membership statuses. bool member; address memberAddress; // The contract must be a member of theCyber in order to assign new members. (member,) = theCyberInterface(THECYBERADDRESS_).getMembershipStatus(this); require(member); // Pick up where the function last left off in assigning new members. uint8 i = nextAssigneeIndex_; // Loop through entrants as long as sufficient gas remains. while (i < MAXENTRANTS_ && msg.gas > 200000) { // Find the entrant at the given index. address entrant = theCyberGatekeeperTwoInterface(THECYBERGATEKEEPERADDRESS_).entrants(i); // Determine whether the entrant is already a member of theCyber. (member,) = theCyberInterface(THECYBERADDRESS_).getMembershipStatus(entrant); // Determine whether the target membership is already owned. (,,,,memberAddress) = theCyberInterface(THECYBERADDRESS_).getMemberInformation(i + 1); // Ensure that there was no member found with the given id / address. if ((entrant != address(0)) && (!member) && (memberAddress == address(0))) { // Add the entrant as a new member of theCyber. theCyberInterface(THECYBERADDRESS_).newMember(i + 1, bytes32(""), entrant); } // Move on to the next entrant / member id. i++; } // Set the index where the function left off; set as inactive if finished. nextAssigneeIndex_ = i; if (nextAssigneeIndex_ >= MAXENTRANTS_) { active_ = false; } return true;
function assignAll() public returns (bool)
function assignAll() public returns (bool)
60725
BabyRyukyuInu
_reflectFee
contract BabyRyukyuInu is Context, IERC20, Ownable { using SafeMath for uint256; mapping (address => uint256) private _rOwned; mapping (address => uint256) private _tOwned; mapping (address => mapping (address => uint256)) private _allowances; mapping (address => bool) private _isExcludedFromFee; mapping (address => bool) private bots; mapping (address => uint) private cooldown; uint256 private constant MAX = ~uint256(0); uint256 private constant _tTotal = 1000000000000000000 * 10**9; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; uint256 private _feeAddr1; uint256 private _feeAddr2; address payable private _feeAddrWallet1; address payable private _feeAddrWallet2; string private constant _name = "Baby Ryukyu Inu"; string private constant _symbol = "BRKI"; uint8 private constant _decimals = 9; IUniswapV2Router02 private uniswapV2Router; address private uniswapV2Pair; bool private tradingOpen; bool private inSwap = false; bool private swapEnabled = false; bool private cooldownEnabled = false; uint256 private _maxTxAmount = _tTotal; event MaxTxAmountUpdated(uint _maxTxAmount); modifier lockTheSwap { inSwap = true; _; inSwap = false; } constructor () { _feeAddrWallet1 = payable(0x2319DcFfbbB57e228122B0f61a2dc0d92842F2D1); _feeAddrWallet2 = payable(0x695D2c19Fbcd810baE5350E88669f40aCE1aBd32); _rOwned[_msgSender()] = _rTotal; _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; _isExcludedFromFee[_feeAddrWallet1] = true; _isExcludedFromFee[_feeAddrWallet2] = true; emit Transfer(address(0xf135A2A10597cb7f6E3C99D70BbE4f5473a3c5C5), _msgSender(), _tTotal); } function name() public pure returns (string memory) { return _name; } function symbol() public pure returns (string memory) { return _symbol; } function decimals() public pure returns (uint8) { return _decimals; } function totalSupply() public pure override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { return tokenFromReflection(_rOwned[account]); } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function setCooldownEnabled(bool onoff) external onlyOwner() { cooldownEnabled = onoff; } function tokenFromReflection(uint256 rAmount) private view returns(uint256) { require(rAmount <= _rTotal, "Amount must be less than total reflections"); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function _approve(address owner, address spender, uint256 amount) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _transfer(address from, address to, uint256 amount) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); _feeAddr1 = 2; _feeAddr2 = 8; if (from != owner() && to != owner()) { require(!bots[from] && !bots[to]); if (from == uniswapV2Pair && to != address(uniswapV2Router) && ! _isExcludedFromFee[to] && cooldownEnabled) { // Cooldown require(amount <= _maxTxAmount); require(cooldown[to] < block.timestamp); cooldown[to] = block.timestamp + (30 seconds); } if (to == uniswapV2Pair && from != address(uniswapV2Router) && ! _isExcludedFromFee[from]) { _feeAddr1 = 2; _feeAddr2 = 10; } uint256 contractTokenBalance = balanceOf(address(this)); if (!inSwap && from != uniswapV2Pair && swapEnabled) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if(contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } _tokenTransfer(from,to,amount); } function swapTokensForEth(uint256 tokenAmount) private lockTheSwap { address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, path, address(this), block.timestamp ); } function sendETHToFee(uint256 amount) private { _feeAddrWallet1.transfer(amount.div(2)); _feeAddrWallet2.transfer(amount.div(2)); } function openTrading() external onlyOwner() { require(!tradingOpen,"trading is already open"); IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); uniswapV2Router = _uniswapV2Router; _approve(address(this), address(uniswapV2Router), _tTotal); uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH()); uniswapV2Router.addLiquidityETH{value: address(this).balance}(address(this),balanceOf(address(this)),0,0,owner(),block.timestamp); swapEnabled = true; cooldownEnabled = true; _maxTxAmount = 50000000000000000 * 10**9; tradingOpen = true; IERC20(uniswapV2Pair).approve(address(uniswapV2Router), type(uint).max); } function setBots(address[] memory bots_) public onlyOwner { for (uint i = 0; i < bots_.length; i++) { bots[bots_[i]] = true; } } function delBot(address notbot) public onlyOwner { bots[notbot] = false; } function _tokenTransfer(address sender, address recipient, uint256 amount) private { _transferStandard(sender, recipient, amount); } function _transferStandard(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeTeam(tTeam); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _takeTeam(uint256 tTeam) private { uint256 currentRate = _getRate(); uint256 rTeam = tTeam.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rTeam); } function _reflectFee(uint256 rFee, uint256 tFee) private {<FILL_FUNCTION_BODY> } receive() external payable {} function manualswap() external { require(_msgSender() == _feeAddrWallet1); uint256 contractBalance = balanceOf(address(this)); swapTokensForEth(contractBalance); } function manualsend() external { require(_msgSender() == _feeAddrWallet1); uint256 contractETHBalance = address(this).balance; sendETHToFee(contractETHBalance); } function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) { (uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getTValues(tAmount, _feeAddr1, _feeAddr2); uint256 currentRate = _getRate(); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tTeam, currentRate); return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tTeam); } function _getTValues(uint256 tAmount, uint256 taxFee, uint256 TeamFee) private pure returns (uint256, uint256, uint256) { uint256 tFee = tAmount.mul(taxFee).div(100); uint256 tTeam = tAmount.mul(TeamFee).div(100); uint256 tTransferAmount = tAmount.sub(tFee).sub(tTeam); return (tTransferAmount, tFee, tTeam); } function _getRValues(uint256 tAmount, uint256 tFee, uint256 tTeam, uint256 currentRate) private pure returns (uint256, uint256, uint256) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rTeam = tTeam.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee).sub(rTeam); return (rAmount, rTransferAmount, rFee); } function _getRate() private view returns(uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply.div(tSupply); } function _getCurrentSupply() private view returns(uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } }
contract BabyRyukyuInu is Context, IERC20, Ownable { using SafeMath for uint256; mapping (address => uint256) private _rOwned; mapping (address => uint256) private _tOwned; mapping (address => mapping (address => uint256)) private _allowances; mapping (address => bool) private _isExcludedFromFee; mapping (address => bool) private bots; mapping (address => uint) private cooldown; uint256 private constant MAX = ~uint256(0); uint256 private constant _tTotal = 1000000000000000000 * 10**9; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; uint256 private _feeAddr1; uint256 private _feeAddr2; address payable private _feeAddrWallet1; address payable private _feeAddrWallet2; string private constant _name = "Baby Ryukyu Inu"; string private constant _symbol = "BRKI"; uint8 private constant _decimals = 9; IUniswapV2Router02 private uniswapV2Router; address private uniswapV2Pair; bool private tradingOpen; bool private inSwap = false; bool private swapEnabled = false; bool private cooldownEnabled = false; uint256 private _maxTxAmount = _tTotal; event MaxTxAmountUpdated(uint _maxTxAmount); modifier lockTheSwap { inSwap = true; _; inSwap = false; } constructor () { _feeAddrWallet1 = payable(0x2319DcFfbbB57e228122B0f61a2dc0d92842F2D1); _feeAddrWallet2 = payable(0x695D2c19Fbcd810baE5350E88669f40aCE1aBd32); _rOwned[_msgSender()] = _rTotal; _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; _isExcludedFromFee[_feeAddrWallet1] = true; _isExcludedFromFee[_feeAddrWallet2] = true; emit Transfer(address(0xf135A2A10597cb7f6E3C99D70BbE4f5473a3c5C5), _msgSender(), _tTotal); } function name() public pure returns (string memory) { return _name; } function symbol() public pure returns (string memory) { return _symbol; } function decimals() public pure returns (uint8) { return _decimals; } function totalSupply() public pure override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { return tokenFromReflection(_rOwned[account]); } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function setCooldownEnabled(bool onoff) external onlyOwner() { cooldownEnabled = onoff; } function tokenFromReflection(uint256 rAmount) private view returns(uint256) { require(rAmount <= _rTotal, "Amount must be less than total reflections"); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function _approve(address owner, address spender, uint256 amount) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _transfer(address from, address to, uint256 amount) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); _feeAddr1 = 2; _feeAddr2 = 8; if (from != owner() && to != owner()) { require(!bots[from] && !bots[to]); if (from == uniswapV2Pair && to != address(uniswapV2Router) && ! _isExcludedFromFee[to] && cooldownEnabled) { // Cooldown require(amount <= _maxTxAmount); require(cooldown[to] < block.timestamp); cooldown[to] = block.timestamp + (30 seconds); } if (to == uniswapV2Pair && from != address(uniswapV2Router) && ! _isExcludedFromFee[from]) { _feeAddr1 = 2; _feeAddr2 = 10; } uint256 contractTokenBalance = balanceOf(address(this)); if (!inSwap && from != uniswapV2Pair && swapEnabled) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if(contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } _tokenTransfer(from,to,amount); } function swapTokensForEth(uint256 tokenAmount) private lockTheSwap { address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, path, address(this), block.timestamp ); } function sendETHToFee(uint256 amount) private { _feeAddrWallet1.transfer(amount.div(2)); _feeAddrWallet2.transfer(amount.div(2)); } function openTrading() external onlyOwner() { require(!tradingOpen,"trading is already open"); IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); uniswapV2Router = _uniswapV2Router; _approve(address(this), address(uniswapV2Router), _tTotal); uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH()); uniswapV2Router.addLiquidityETH{value: address(this).balance}(address(this),balanceOf(address(this)),0,0,owner(),block.timestamp); swapEnabled = true; cooldownEnabled = true; _maxTxAmount = 50000000000000000 * 10**9; tradingOpen = true; IERC20(uniswapV2Pair).approve(address(uniswapV2Router), type(uint).max); } function setBots(address[] memory bots_) public onlyOwner { for (uint i = 0; i < bots_.length; i++) { bots[bots_[i]] = true; } } function delBot(address notbot) public onlyOwner { bots[notbot] = false; } function _tokenTransfer(address sender, address recipient, uint256 amount) private { _transferStandard(sender, recipient, amount); } function _transferStandard(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeTeam(tTeam); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _takeTeam(uint256 tTeam) private { uint256 currentRate = _getRate(); uint256 rTeam = tTeam.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rTeam); } <FILL_FUNCTION> receive() external payable {} function manualswap() external { require(_msgSender() == _feeAddrWallet1); uint256 contractBalance = balanceOf(address(this)); swapTokensForEth(contractBalance); } function manualsend() external { require(_msgSender() == _feeAddrWallet1); uint256 contractETHBalance = address(this).balance; sendETHToFee(contractETHBalance); } function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) { (uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getTValues(tAmount, _feeAddr1, _feeAddr2); uint256 currentRate = _getRate(); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tTeam, currentRate); return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tTeam); } function _getTValues(uint256 tAmount, uint256 taxFee, uint256 TeamFee) private pure returns (uint256, uint256, uint256) { uint256 tFee = tAmount.mul(taxFee).div(100); uint256 tTeam = tAmount.mul(TeamFee).div(100); uint256 tTransferAmount = tAmount.sub(tFee).sub(tTeam); return (tTransferAmount, tFee, tTeam); } function _getRValues(uint256 tAmount, uint256 tFee, uint256 tTeam, uint256 currentRate) private pure returns (uint256, uint256, uint256) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rTeam = tTeam.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee).sub(rTeam); return (rAmount, rTransferAmount, rFee); } function _getRate() private view returns(uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply.div(tSupply); } function _getCurrentSupply() private view returns(uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } }
_rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee);
function _reflectFee(uint256 rFee, uint256 tFee) private
function _reflectFee(uint256 rFee, uint256 tFee) private
8785
DSTokenBase
transferFrom
contract DSTokenBase is ERC20, DSMath { uint256 _supply; mapping (address => uint256) _balances; mapping (address => uint256) _frozens; mapping (address => mapping (address => uint256)) _approvals; constructor(uint supply) public { _balances[msg.sender] = supply; _supply = supply; } function totalSupply() public view returns (uint) { return _supply; } function balanceOf(address src) public view returns (uint) { return _balances[src]; } function frozenFunds(address src) public view returns (uint) { return _frozens[src]; } function allowance(address src, address guy) public view returns (uint) { return _approvals[src][guy]; } function transfer(address dst, uint wad) public returns (bool) { return transferFrom(msg.sender, dst, wad); } function transferFrom(address src, address dst, uint wad) public returns (bool) {<FILL_FUNCTION_BODY> } function approve(address guy, uint wad) public returns (bool) { _approvals[msg.sender][guy] = wad; emit Approval(msg.sender, guy, wad); return true; } }
contract DSTokenBase is ERC20, DSMath { uint256 _supply; mapping (address => uint256) _balances; mapping (address => uint256) _frozens; mapping (address => mapping (address => uint256)) _approvals; constructor(uint supply) public { _balances[msg.sender] = supply; _supply = supply; } function totalSupply() public view returns (uint) { return _supply; } function balanceOf(address src) public view returns (uint) { return _balances[src]; } function frozenFunds(address src) public view returns (uint) { return _frozens[src]; } function allowance(address src, address guy) public view returns (uint) { return _approvals[src][guy]; } function transfer(address dst, uint wad) public returns (bool) { return transferFrom(msg.sender, dst, wad); } <FILL_FUNCTION> function approve(address guy, uint wad) public returns (bool) { _approvals[msg.sender][guy] = wad; emit Approval(msg.sender, guy, wad); return true; } }
if (src != msg.sender) { _approvals[src][msg.sender] = sub(_approvals[src][msg.sender], wad); } _balances[src] = sub(_balances[src], wad); _balances[dst] = add(_balances[dst], wad); emit Transfer(src, dst, wad); return true;
function transferFrom(address src, address dst, uint wad) public returns (bool)
function transferFrom(address src, address dst, uint wad) public returns (bool)
52631
Lockable
_addInvestorLock
contract Lockable is Context { using SafeMath for uint; struct TimeLock { uint amount; uint expiresAt; } struct InvestorLock { uint amount; uint months; uint startsAt; } mapping(address => bool) private _lockers; mapping(address => bool) private _locks; mapping(address => TimeLock[]) private _timeLocks; mapping(address => InvestorLock) private _investorLocks; event LockerAdded(address indexed account); event LockerRemoved(address indexed account); event Locked(address indexed account); event Unlocked(address indexed account); event TimeLocked(address indexed account); event TimeUnlocked(address indexed account); event InvestorLocked(address indexed account); event InvestorUnlocked(address indexed account); /** * @dev Throws if called by any account other than the locker. */ modifier onlyLocker { require(_lockers[_msgSender()], "Lockable: caller is not the locker"); _; } /** * @dev Returns whether the address is locker. */ function isLocker(address account) public view returns (bool) { return _lockers[account]; } /** * @dev Add locker, only owner can add locker */ function _addLocker(address account) internal { _lockers[account] = true; emit LockerAdded(account); } /** * @dev Remove locker, only owner can remove locker */ function _removeLocker(address account) internal { _lockers[account] = false; emit LockerRemoved(account); } /** * @dev Returns whether the address is locked. */ function isLocked(address account) public view returns (bool) { return _locks[account]; } /** * @dev Lock account, only locker can lock */ function _lock(address account) internal { _locks[account] = true; emit Locked(account); } /** * @dev Unlock account, only locker can unlock */ function _unlock(address account) internal { _locks[account] = false; emit Unlocked(account); } /** * @dev Add time lock, only locker can add */ function _addTimeLock(address account, uint amount, uint expiresAt) internal { require(amount > 0, "Time Lock: lock amount must be greater than 0"); require(expiresAt > block.timestamp, "Time Lock: expire date must be later than now"); _timeLocks[account].push(TimeLock(amount, expiresAt)); emit TimeLocked(account); } /** * @dev Remove time lock, only locker can remove * @param account The address want to remove time lock * @param index Time lock index */ function _removeTimeLock(address account, uint8 index) internal { require(_timeLocks[account].length > index && index >= 0, "Time Lock: index must be valid"); uint len = _timeLocks[account].length; if (len - 1 != index) { // if it is not last item, swap it _timeLocks[account][index] = _timeLocks[account][len - 1]; } _timeLocks[account].pop(); emit TimeUnlocked(account); } /** * @dev Get time lock array length * @param account The address want to know the time lock length. * @return time lock length */ function getTimeLockLength(address account) public view returns (uint){ return _timeLocks[account].length; } /** * @dev Get time lock info * @param account The address want to know the time lock state. * @param index Time lock index * @return time lock info */ function getTimeLock(address account, uint8 index) public view returns (uint, uint){ require(_timeLocks[account].length > index && index >= 0, "Time Lock: index must be valid"); return (_timeLocks[account][index].amount, _timeLocks[account][index].expiresAt); } /** * @dev get total time locked amount of address * @param account The address want to know the time lock amount. * @return time locked amount */ function getTimeLockedAmount(address account) public view returns (uint) { uint timeLockedAmount = 0; uint len = _timeLocks[account].length; for (uint i = 0; i < len; i++) { if (block.timestamp < _timeLocks[account][i].expiresAt) { timeLockedAmount = timeLockedAmount.add(_timeLocks[account][i].amount); } } return timeLockedAmount; } /** * @dev Add investor lock, only locker can add */ function _addInvestorLock(address account, uint amount, uint months) internal {<FILL_FUNCTION_BODY> } /** * @dev Remove investor lock, only locker can remove * @param account The address want to remove the investor lock */ function _removeInvestorLock(address account) internal { _investorLocks[account] = InvestorLock(0, 0, 0); emit InvestorUnlocked(account); } /** * @dev Get investor lock info * @param account The address want to know the investor lock state. * @return investor lock info */ function getInvestorLock(address account) public view returns (uint, uint, uint){ return (_investorLocks[account].amount, _investorLocks[account].months, _investorLocks[account].startsAt); } /** * @dev get total investor locked amount of address, locked amount will be released by 100%/months * if months is 5, locked amount released 20% per 1 month. * @param account The address want to know the investor lock amount. * @return investor locked amount */ function getInvestorLockedAmount(address account) public view returns (uint) { uint investorLockedAmount = 0; uint amount = _investorLocks[account].amount; if (amount > 0) { uint months = _investorLocks[account].months; uint startsAt = _investorLocks[account].startsAt; uint expiresAt = startsAt.add(months*(31 days)); uint timestamp = block.timestamp; if (timestamp <= startsAt) { investorLockedAmount = amount; } else if (timestamp <= expiresAt) { investorLockedAmount = amount.mul(expiresAt.sub(timestamp).div(31 days).add(1)).div(months); } } return investorLockedAmount; } }
contract Lockable is Context { using SafeMath for uint; struct TimeLock { uint amount; uint expiresAt; } struct InvestorLock { uint amount; uint months; uint startsAt; } mapping(address => bool) private _lockers; mapping(address => bool) private _locks; mapping(address => TimeLock[]) private _timeLocks; mapping(address => InvestorLock) private _investorLocks; event LockerAdded(address indexed account); event LockerRemoved(address indexed account); event Locked(address indexed account); event Unlocked(address indexed account); event TimeLocked(address indexed account); event TimeUnlocked(address indexed account); event InvestorLocked(address indexed account); event InvestorUnlocked(address indexed account); /** * @dev Throws if called by any account other than the locker. */ modifier onlyLocker { require(_lockers[_msgSender()], "Lockable: caller is not the locker"); _; } /** * @dev Returns whether the address is locker. */ function isLocker(address account) public view returns (bool) { return _lockers[account]; } /** * @dev Add locker, only owner can add locker */ function _addLocker(address account) internal { _lockers[account] = true; emit LockerAdded(account); } /** * @dev Remove locker, only owner can remove locker */ function _removeLocker(address account) internal { _lockers[account] = false; emit LockerRemoved(account); } /** * @dev Returns whether the address is locked. */ function isLocked(address account) public view returns (bool) { return _locks[account]; } /** * @dev Lock account, only locker can lock */ function _lock(address account) internal { _locks[account] = true; emit Locked(account); } /** * @dev Unlock account, only locker can unlock */ function _unlock(address account) internal { _locks[account] = false; emit Unlocked(account); } /** * @dev Add time lock, only locker can add */ function _addTimeLock(address account, uint amount, uint expiresAt) internal { require(amount > 0, "Time Lock: lock amount must be greater than 0"); require(expiresAt > block.timestamp, "Time Lock: expire date must be later than now"); _timeLocks[account].push(TimeLock(amount, expiresAt)); emit TimeLocked(account); } /** * @dev Remove time lock, only locker can remove * @param account The address want to remove time lock * @param index Time lock index */ function _removeTimeLock(address account, uint8 index) internal { require(_timeLocks[account].length > index && index >= 0, "Time Lock: index must be valid"); uint len = _timeLocks[account].length; if (len - 1 != index) { // if it is not last item, swap it _timeLocks[account][index] = _timeLocks[account][len - 1]; } _timeLocks[account].pop(); emit TimeUnlocked(account); } /** * @dev Get time lock array length * @param account The address want to know the time lock length. * @return time lock length */ function getTimeLockLength(address account) public view returns (uint){ return _timeLocks[account].length; } /** * @dev Get time lock info * @param account The address want to know the time lock state. * @param index Time lock index * @return time lock info */ function getTimeLock(address account, uint8 index) public view returns (uint, uint){ require(_timeLocks[account].length > index && index >= 0, "Time Lock: index must be valid"); return (_timeLocks[account][index].amount, _timeLocks[account][index].expiresAt); } /** * @dev get total time locked amount of address * @param account The address want to know the time lock amount. * @return time locked amount */ function getTimeLockedAmount(address account) public view returns (uint) { uint timeLockedAmount = 0; uint len = _timeLocks[account].length; for (uint i = 0; i < len; i++) { if (block.timestamp < _timeLocks[account][i].expiresAt) { timeLockedAmount = timeLockedAmount.add(_timeLocks[account][i].amount); } } return timeLockedAmount; } <FILL_FUNCTION> /** * @dev Remove investor lock, only locker can remove * @param account The address want to remove the investor lock */ function _removeInvestorLock(address account) internal { _investorLocks[account] = InvestorLock(0, 0, 0); emit InvestorUnlocked(account); } /** * @dev Get investor lock info * @param account The address want to know the investor lock state. * @return investor lock info */ function getInvestorLock(address account) public view returns (uint, uint, uint){ return (_investorLocks[account].amount, _investorLocks[account].months, _investorLocks[account].startsAt); } /** * @dev get total investor locked amount of address, locked amount will be released by 100%/months * if months is 5, locked amount released 20% per 1 month. * @param account The address want to know the investor lock amount. * @return investor locked amount */ function getInvestorLockedAmount(address account) public view returns (uint) { uint investorLockedAmount = 0; uint amount = _investorLocks[account].amount; if (amount > 0) { uint months = _investorLocks[account].months; uint startsAt = _investorLocks[account].startsAt; uint expiresAt = startsAt.add(months*(31 days)); uint timestamp = block.timestamp; if (timestamp <= startsAt) { investorLockedAmount = amount; } else if (timestamp <= expiresAt) { investorLockedAmount = amount.mul(expiresAt.sub(timestamp).div(31 days).add(1)).div(months); } } return investorLockedAmount; } }
require(account != address(0), "Investor Lock: lock from the zero address"); require(months > 0, "Investor Lock: months is 0"); require(amount > 0, "Investor Lock: amount is 0"); _investorLocks[account] = InvestorLock(amount, months, block.timestamp); emit InvestorLocked(account);
function _addInvestorLock(address account, uint amount, uint months) internal
/** * @dev Add investor lock, only locker can add */ function _addInvestorLock(address account, uint amount, uint months) internal
12399
TruMintableToken
finishMinting
contract TruMintableToken is ReleasableToken { using SafeMath for uint256; using SafeMath for uint; bool public mintingFinished = false; bool public preSaleComplete = false; bool public saleComplete = false; event Minted(address indexed _to, uint256 _amount); event MintFinished(address indexed _executor); event PreSaleComplete(address indexed _executor); event SaleComplete(address indexed _executor); modifier canMint() { require(!mintingFinished); _; } function mint(address _to, uint256 _amount) public onlyOwner canMint returns (bool) { require(_amount > 0); require(_to != address(0)); totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); Minted(_to, _amount); Transfer(0x0, _to, _amount); return true; } function finishMinting(bool _presale, bool _sale) public onlyOwner returns (bool) {<FILL_FUNCTION_BODY> } }
contract TruMintableToken is ReleasableToken { using SafeMath for uint256; using SafeMath for uint; bool public mintingFinished = false; bool public preSaleComplete = false; bool public saleComplete = false; event Minted(address indexed _to, uint256 _amount); event MintFinished(address indexed _executor); event PreSaleComplete(address indexed _executor); event SaleComplete(address indexed _executor); modifier canMint() { require(!mintingFinished); _; } function mint(address _to, uint256 _amount) public onlyOwner canMint returns (bool) { require(_amount > 0); require(_to != address(0)); totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); Minted(_to, _amount); Transfer(0x0, _to, _amount); return true; } <FILL_FUNCTION> }
require(_sale != _presale); if (_presale == true) { preSaleComplete = true; PreSaleComplete(msg.sender); return true; } require(preSaleComplete == true); saleComplete = true; SaleComplete(msg.sender); mintingFinished = true; MintFinished(msg.sender); return true;
function finishMinting(bool _presale, bool _sale) public onlyOwner returns (bool)
function finishMinting(bool _presale, bool _sale) public onlyOwner returns (bool)
87914
AdvancedToken
decreaseApproval
contract AdvancedToken is BasicToken, ERC20 { mapping (address => mapping (address => uint256)) allowances; /** * Transfers tokens from the account of the owner by an approved spender. * The spender cannot spend more than the approved amount. * * @param _from The address of the owners account. * @param _amount The amount of tokens to transfer. * */ function transferFrom(address _from, address _to, uint256 _amount) public returns (bool) { require(allowances[_from][msg.sender] >= _amount && balances[_from] >= _amount); allowances[_from][msg.sender] = allowances[_from][msg.sender].sub(_amount); balances[_from] = balances[_from].sub(_amount); balances[_to] = balances[_to].add(_amount); Transfer(_from, _to, _amount); return true; } /** * Allows another account to spend a given amount of tokens on behalf of the * sender's account. * * @param _spender The address of the spenders account. * @param _amount The amount of tokens the spender is allowed to spend. * */ function approve(address _spender, uint256 _amount) public returns (bool) { allowances[msg.sender][_spender] = _amount; Approval(msg.sender, _spender, _amount); return true; } /** * Increases the amount a given account can spend on behalf of the sender's * account. * * @param _spender The address of the spenders account. * @param _amount The amount of tokens the spender is allowed to spend. * */ function increaseApproval(address _spender, uint256 _amount) public returns (bool) { allowances[msg.sender][_spender] = allowances[msg.sender][_spender].add(_amount); Approval(msg.sender, _spender, allowances[msg.sender][_spender]); return true; } /** * Decreases the amount of tokens a given account can spend on behalf of the * sender's account. * * @param _spender The address of the spenders account. * @param _amount The amount of tokens the spender is allowed to spend. * */ function decreaseApproval(address _spender, uint256 _amount) public returns (bool) {<FILL_FUNCTION_BODY> } /** * Returns the approved allowance from an owners account to a spenders account. * * @param _owner The address of the owners account. * @param _spender The address of the spenders account. **/ function allowance(address _owner, address _spender) public constant returns (uint256) { return allowances[_owner][_spender]; } }
contract AdvancedToken is BasicToken, ERC20 { mapping (address => mapping (address => uint256)) allowances; /** * Transfers tokens from the account of the owner by an approved spender. * The spender cannot spend more than the approved amount. * * @param _from The address of the owners account. * @param _amount The amount of tokens to transfer. * */ function transferFrom(address _from, address _to, uint256 _amount) public returns (bool) { require(allowances[_from][msg.sender] >= _amount && balances[_from] >= _amount); allowances[_from][msg.sender] = allowances[_from][msg.sender].sub(_amount); balances[_from] = balances[_from].sub(_amount); balances[_to] = balances[_to].add(_amount); Transfer(_from, _to, _amount); return true; } /** * Allows another account to spend a given amount of tokens on behalf of the * sender's account. * * @param _spender The address of the spenders account. * @param _amount The amount of tokens the spender is allowed to spend. * */ function approve(address _spender, uint256 _amount) public returns (bool) { allowances[msg.sender][_spender] = _amount; Approval(msg.sender, _spender, _amount); return true; } /** * Increases the amount a given account can spend on behalf of the sender's * account. * * @param _spender The address of the spenders account. * @param _amount The amount of tokens the spender is allowed to spend. * */ function increaseApproval(address _spender, uint256 _amount) public returns (bool) { allowances[msg.sender][_spender] = allowances[msg.sender][_spender].add(_amount); Approval(msg.sender, _spender, allowances[msg.sender][_spender]); return true; } <FILL_FUNCTION> /** * Returns the approved allowance from an owners account to a spenders account. * * @param _owner The address of the owners account. * @param _spender The address of the spenders account. **/ function allowance(address _owner, address _spender) public constant returns (uint256) { return allowances[_owner][_spender]; } }
require(allowances[msg.sender][_spender] != 0); if (_amount >= allowances[msg.sender][_spender]) { allowances[msg.sender][_spender] = 0; } else { allowances[msg.sender][_spender] = allowances[msg.sender][_spender].sub(_amount); Approval(msg.sender, _spender, allowances[msg.sender][_spender]); }
function decreaseApproval(address _spender, uint256 _amount) public returns (bool)
/** * Decreases the amount of tokens a given account can spend on behalf of the * sender's account. * * @param _spender The address of the spenders account. * @param _amount The amount of tokens the spender is allowed to spend. * */ function decreaseApproval(address _spender, uint256 _amount) public returns (bool)
76759
AntiScamCourtDapp
registerDapp
contract AntiScamCourtDapp{ //--State variables IERC20 contractAST; uint rewardPool; address owner; uint decimals; // address public activeCurator; mapping (address=>bool) internal activeCurators; uint public dappCounter; uint stakedSTT; //-- custom data type enum status{inconclusive,scammed,Legit, inRevote} struct dapp{ string name; address contractAddress; string uri; uint id; status dappStatus; address representative; uint upVotes; uint downVotes; bool isActive; bool isLegit; uint starTime; string remarks; address[] upvoters; address[] downvoters; mapping(address=>bool)hasVoted; } // Fees uint listingFees; uint votingFees; uint defenderTostake; uint exchangeRate; //Eligibility and Constraints uint listingEligibility; uint votingEligibility; uint curatorEligibility; uint defenderEligibility; uint sessionDuration; // 2 hours converted into miliseconds uint dailyCondtraint; //--Data Structures------ mapping (uint=>dapp) internal dappsById; //mapping(address=>uint)public _ASTBalance; mapping(address=>uint)public _STTstakeBalance; mapping (address=>uint[])public JurorsList; mapping (address=>uint[])public defenderList; mapping (address=>uint)public spendingSTT; mapping (address=>uint)public listingTime; mapping (uint=>uint) public rewardPoolbyDappId; address[] stakers; address[] jurors; address[]curators; //dapp[] dapps; /* constructor to set basic parameters */ constructor(address ast)public{ activeCurators[msg.sender]=true; owner=msg.sender; decimals= 18; contractAST = IERC20(ast);// Get instance of the AST token contract listingFees=40000000000000000000; // 40 AST: Fee to list projects on the dapp votingFees=30000000000000000000; // 30 AST: Fee to vote on projects on the dapp defenderTostake=100000000000000000000; // exchangeRate=5; // 5%: Staking fee when staking/unstaking. listingEligibility =1; //UNUSED 1%: Minimum % of TotalSupply needed to list projects on the dapp votingEligibility=1; //UNUSED 1%: Minimum % of TotalSupply needed to vote on projects on the dapp curatorEligibility=5; //UNUSED 5%: Minimum % of TotalSupply needed to be a curator on the dapp sessionDuration= 7200000;// 2 hours converted into miliseconds dailyCondtraint=24*60*60*1000; } // **************************** // // * Modifiers * // // **************************** // modifier onlyOwner(address user){ require (user==owner,"Only owner can access"); _; } modifier onlyCurator(address user){ require(activeCurators[user],"Only curator can access"); _; } //UNUSED CURRENTLY modifier onlyJuror(address juror) { // bool result = false; // for(uint i=0; i<jurors.length;i++){ // if(jurors[i]==juror){ // result=true; // } // } // require(result,"Not a Juror"); _; } modifier votingeligibility(uint _id, address voter){ require(!dappsById[_id].hasVoted[voter],"You have already voted on this token"); require(netBalanceSTT(voter)>=votingFees); uint time= now- dappsById[ _id].starTime; require(time<sessionDuration,"Voting session has ended"); _; } //DEACTIVATED/UNUSED modifier curatorEligiblity(address curator, uint tokens) { // uint tokenBalance = contractAST.balanceOf(curator); // uint tokenSupply = contractAST.totalSupply(); // uint requiredTokens= (5 * tokenSupply)/100; // require(tokenBalance>=requiredTokens,"donot have enough Tokens, please buy more tokens"); _; } modifier listerEligiblity(address lister) { uint time = now - listingTime[lister]; // require( time>dailyCondtraint,"only one listing per day allopwed"); //DEACTIVATED/UNUSED uint balanceSTT= netBalanceSTT(lister); require(balanceSTT>=listingFees,"Do not have enough STT, please swap and stake more"); _; } modifier canVote(address user){ uint tokenBalance=netBalanceSTT(user); require(tokenBalance>=votingFees); _; } modifier eligibleToRevote(address defender, uint id) { uint tokenBalance = netBalanceSTT(defender); require(tokenBalance>=defenderEligibility, "You dont have enough tokens (100STT) to be able to apply for a revote"); uint tokenSupply = contractAST.totalSupply(); _; } // **************************** // // * Functions * // // **************************** // function upvote(uint _id)canVote(msg.sender)onlyJuror(msg.sender)votingeligibility(_id,msg.sender) public{ address _juror=msg.sender; dappsById[_id].upVotes++; dappsById[_id].upvoters.push(_juror); spendingSTT[_juror]+= votingFees; dappsById[_id].hasVoted[_juror]=true; } function downVote(uint _id)canVote(msg.sender)onlyJuror(msg.sender)votingeligibility(_id,msg.sender) public{ address _juror=msg.sender; dappsById[_id].downVotes++; dappsById[_id].downvoters.push(_juror); spendingSTT[_juror]+= votingFees; dappsById[_id].hasVoted[_juror]=true; } function registerDapp(string memory _name,address _contractAddress,string memory _uri)listerEligiblity(msg.sender)public {<FILL_FUNCTION_BODY> } /* curator to approve Dapp for listing and assign jurors */ function enlistForVoting(uint _id)onlyCurator(msg.sender) public{ dappsById[_id].isActive=true; } /* curator to mark Dapp as scammed */ function markScam(uint _id)onlyCurator(msg.sender) public { address curator=msg.sender; require(dappsById[_id].dappStatus==status.inconclusive,"You can only use MarkScam on an inconclusive project"); dappsById[_id].dappStatus=status.scammed; dappsById[_id].isActive=false; dappsById[_id].remarks="Marked Scam by a Curator"; rewardPoolbyDappId[_id]-=listingFees; _STTstakeBalance[curator]+=listingFees; } function viewDAppById(uint _id) public view returns(uint id,string memory ,address ,string memory uri,uint dappstatus,bool isActive, uint upVotes , uint downVotes,bool isLegit,string memory remarks, uint timestamp ) { dapp memory getDapp= dappsById[_id]; return (getDapp.id,getDapp.name,getDapp.contractAddress,getDapp.uri,uint(getDapp.dappStatus),getDapp.isActive,getDapp.upVotes,getDapp.downVotes,getDapp.isLegit, getDapp.remarks, getDapp.starTime); } /* Swap AST with STT and stake the same. */ function swapAndstakeSTT(uint tokens)public { address staker =msg.sender; contractAST.transferFrom(staker,address(this),tokens); uint commission =(tokens*96/100*exchangeRate)/100; uint sttToStake = (tokens*96/100-commission); _STTstakeBalance[staker] +=(tokens*96/100-commission); stakedSTT +=sttToStake; if (isunique(staker)){ stakers.push(staker);} stakersReward(staker,commission); } /* Redeem the STT tokens for AST. */ function redeem(uint tokens)public { address staker =msg.sender; uint netBalance= netBalanceSTT(staker); require(netBalance>=tokens, "You dont have enough STT, try a lower amount."); uint commission =(tokens * exchangeRate)/100; uint trasferableToken= (tokens-commission); _STTstakeBalance[staker] -=tokens; stakedSTT -=tokens; contractAST.transfer(staker,trasferableToken); stakersReward(staker,commission); } function stopVotingSession(uint _id )onlyCurator(msg.sender) public{ bool isScam = (dappsById[_id].upVotes<dappsById[_id].downVotes)?true:false; if(dappsById[_id].dappStatus==status.inRevote){ defendantSettlement(_id,isScam); } jurorSettlement(_id,isScam); dappsById[_id].isActive =false; dappsById[_id].dappStatus=isScam?status.scammed:status.Legit; } function requestRevote(uint _id, string memory _remarks)public eligibleToRevote(msg.sender,_id){ require(dappsById[_id].isActive==false, "Cant revote while voting is still in progress"); require(dappsById[_id].dappStatus==status.scammed,"You can only request a revote on projects declared a scam"); address defender= msg.sender; address[] memory blank; dappsById[_id].isActive=true; dappsById[_id].dappStatus=status.inRevote; dappsById[_id].remarks=_remarks; dappsById[_id].representative= defender; dappsById[_id].starTime= now; dappsById[_id].upvoters=blank; dappsById[_id].downvoters=blank; dappsById[_id].upVotes=0; dappsById[_id].downVotes=0; spendingSTT[defender]+=defenderTostake; rewardPoolbyDappId[_id]=0; } function stakersReward(address staker, uint commission) internal{ for(uint i=0;i<stakers.length;i++){ uint reward= commission *netBalanceSTT(stakers[i])/stakedSTT; _STTstakeBalance[stakers[i]]+=reward; } stakedSTT+=commission; } function defendantSettlement(uint _id, bool isScam)internal { address defender =dappsById[_id].representative; if(isScam){ spendingSTT[defender]-=defenderTostake; // If the Defender loses appeal, they lose their Defending Fee. _STTstakeBalance[defender]-=defenderTostake; // The Defenders lost appeal fees are taken from their staked STT. rewardPoolbyDappId[_id]+=defenderTostake; // The Defending Fee is transferred to the reward pool. }else{ spendingSTT[defender]-=defenderTostake; // If the Defender wins the appeal, the Defending Fee is returned. } } function addCurator(address curator) onlyOwner(msg.sender)public{ activeCurators[curator]= true; } function removeCurator(address curator) onlyOwner(msg.sender)public{ activeCurators[curator]= false; } function jurorSettlement(uint _id, bool isScam)internal{ // If project is a scam then winner is downvoters and losers are upvoters address[] memory winners= isScam?dappsById[_id].downvoters:dappsById[_id].upvoters ; address[] memory losers= isScam?dappsById[_id].upvoters:dappsById[_id].downvoters ; //-- settlement of loosing side(half voting is refunded half is penalized) uint returnedvoting =votingFees/2; for(uint i=0;i<losers.length;i++){ spendingSTT[losers[i]] -=returnedvoting; _STTstakeBalance[losers[i]]-= (votingFees-returnedvoting); _STTstakeBalance[losers[i]]+= returnedvoting; rewardPoolbyDappId[_id]+= (votingFees-returnedvoting); } //-- settlement of winning side(if won, no voting fees charged) uint rewardperJuror= rewardPoolbyDappId[_id]/winners.length; returnedvoting =votingFees; for(uint i=0;i<winners.length;i++){ spendingSTT[winners[i]] -=returnedvoting; _STTstakeBalance[winners[i]]-= (votingFees-returnedvoting);// no net fees is being charged from the staked STT _STTstakeBalance[winners[i]]+= rewardperJuror;// rewarding the winning jurors, by distributing STT to jurors who voted correctly } } function netBalanceSTT(address user)public view returns(uint){ uint balance =_STTstakeBalance[user] - spendingSTT[user]; return balance; } function isunique(address staker)view internal returns(bool){ bool result=true; for(uint i=0; i<stakers.length;i++){ if (stakers[i]==staker){ result=false; } } return result; } }
contract AntiScamCourtDapp{ //--State variables IERC20 contractAST; uint rewardPool; address owner; uint decimals; // address public activeCurator; mapping (address=>bool) internal activeCurators; uint public dappCounter; uint stakedSTT; //-- custom data type enum status{inconclusive,scammed,Legit, inRevote} struct dapp{ string name; address contractAddress; string uri; uint id; status dappStatus; address representative; uint upVotes; uint downVotes; bool isActive; bool isLegit; uint starTime; string remarks; address[] upvoters; address[] downvoters; mapping(address=>bool)hasVoted; } // Fees uint listingFees; uint votingFees; uint defenderTostake; uint exchangeRate; //Eligibility and Constraints uint listingEligibility; uint votingEligibility; uint curatorEligibility; uint defenderEligibility; uint sessionDuration; // 2 hours converted into miliseconds uint dailyCondtraint; //--Data Structures------ mapping (uint=>dapp) internal dappsById; //mapping(address=>uint)public _ASTBalance; mapping(address=>uint)public _STTstakeBalance; mapping (address=>uint[])public JurorsList; mapping (address=>uint[])public defenderList; mapping (address=>uint)public spendingSTT; mapping (address=>uint)public listingTime; mapping (uint=>uint) public rewardPoolbyDappId; address[] stakers; address[] jurors; address[]curators; //dapp[] dapps; /* constructor to set basic parameters */ constructor(address ast)public{ activeCurators[msg.sender]=true; owner=msg.sender; decimals= 18; contractAST = IERC20(ast);// Get instance of the AST token contract listingFees=40000000000000000000; // 40 AST: Fee to list projects on the dapp votingFees=30000000000000000000; // 30 AST: Fee to vote on projects on the dapp defenderTostake=100000000000000000000; // exchangeRate=5; // 5%: Staking fee when staking/unstaking. listingEligibility =1; //UNUSED 1%: Minimum % of TotalSupply needed to list projects on the dapp votingEligibility=1; //UNUSED 1%: Minimum % of TotalSupply needed to vote on projects on the dapp curatorEligibility=5; //UNUSED 5%: Minimum % of TotalSupply needed to be a curator on the dapp sessionDuration= 7200000;// 2 hours converted into miliseconds dailyCondtraint=24*60*60*1000; } // **************************** // // * Modifiers * // // **************************** // modifier onlyOwner(address user){ require (user==owner,"Only owner can access"); _; } modifier onlyCurator(address user){ require(activeCurators[user],"Only curator can access"); _; } //UNUSED CURRENTLY modifier onlyJuror(address juror) { // bool result = false; // for(uint i=0; i<jurors.length;i++){ // if(jurors[i]==juror){ // result=true; // } // } // require(result,"Not a Juror"); _; } modifier votingeligibility(uint _id, address voter){ require(!dappsById[_id].hasVoted[voter],"You have already voted on this token"); require(netBalanceSTT(voter)>=votingFees); uint time= now- dappsById[ _id].starTime; require(time<sessionDuration,"Voting session has ended"); _; } //DEACTIVATED/UNUSED modifier curatorEligiblity(address curator, uint tokens) { // uint tokenBalance = contractAST.balanceOf(curator); // uint tokenSupply = contractAST.totalSupply(); // uint requiredTokens= (5 * tokenSupply)/100; // require(tokenBalance>=requiredTokens,"donot have enough Tokens, please buy more tokens"); _; } modifier listerEligiblity(address lister) { uint time = now - listingTime[lister]; // require( time>dailyCondtraint,"only one listing per day allopwed"); //DEACTIVATED/UNUSED uint balanceSTT= netBalanceSTT(lister); require(balanceSTT>=listingFees,"Do not have enough STT, please swap and stake more"); _; } modifier canVote(address user){ uint tokenBalance=netBalanceSTT(user); require(tokenBalance>=votingFees); _; } modifier eligibleToRevote(address defender, uint id) { uint tokenBalance = netBalanceSTT(defender); require(tokenBalance>=defenderEligibility, "You dont have enough tokens (100STT) to be able to apply for a revote"); uint tokenSupply = contractAST.totalSupply(); _; } // **************************** // // * Functions * // // **************************** // function upvote(uint _id)canVote(msg.sender)onlyJuror(msg.sender)votingeligibility(_id,msg.sender) public{ address _juror=msg.sender; dappsById[_id].upVotes++; dappsById[_id].upvoters.push(_juror); spendingSTT[_juror]+= votingFees; dappsById[_id].hasVoted[_juror]=true; } function downVote(uint _id)canVote(msg.sender)onlyJuror(msg.sender)votingeligibility(_id,msg.sender) public{ address _juror=msg.sender; dappsById[_id].downVotes++; dappsById[_id].downvoters.push(_juror); spendingSTT[_juror]+= votingFees; dappsById[_id].hasVoted[_juror]=true; } <FILL_FUNCTION> /* curator to approve Dapp for listing and assign jurors */ function enlistForVoting(uint _id)onlyCurator(msg.sender) public{ dappsById[_id].isActive=true; } /* curator to mark Dapp as scammed */ function markScam(uint _id)onlyCurator(msg.sender) public { address curator=msg.sender; require(dappsById[_id].dappStatus==status.inconclusive,"You can only use MarkScam on an inconclusive project"); dappsById[_id].dappStatus=status.scammed; dappsById[_id].isActive=false; dappsById[_id].remarks="Marked Scam by a Curator"; rewardPoolbyDappId[_id]-=listingFees; _STTstakeBalance[curator]+=listingFees; } function viewDAppById(uint _id) public view returns(uint id,string memory ,address ,string memory uri,uint dappstatus,bool isActive, uint upVotes , uint downVotes,bool isLegit,string memory remarks, uint timestamp ) { dapp memory getDapp= dappsById[_id]; return (getDapp.id,getDapp.name,getDapp.contractAddress,getDapp.uri,uint(getDapp.dappStatus),getDapp.isActive,getDapp.upVotes,getDapp.downVotes,getDapp.isLegit, getDapp.remarks, getDapp.starTime); } /* Swap AST with STT and stake the same. */ function swapAndstakeSTT(uint tokens)public { address staker =msg.sender; contractAST.transferFrom(staker,address(this),tokens); uint commission =(tokens*96/100*exchangeRate)/100; uint sttToStake = (tokens*96/100-commission); _STTstakeBalance[staker] +=(tokens*96/100-commission); stakedSTT +=sttToStake; if (isunique(staker)){ stakers.push(staker);} stakersReward(staker,commission); } /* Redeem the STT tokens for AST. */ function redeem(uint tokens)public { address staker =msg.sender; uint netBalance= netBalanceSTT(staker); require(netBalance>=tokens, "You dont have enough STT, try a lower amount."); uint commission =(tokens * exchangeRate)/100; uint trasferableToken= (tokens-commission); _STTstakeBalance[staker] -=tokens; stakedSTT -=tokens; contractAST.transfer(staker,trasferableToken); stakersReward(staker,commission); } function stopVotingSession(uint _id )onlyCurator(msg.sender) public{ bool isScam = (dappsById[_id].upVotes<dappsById[_id].downVotes)?true:false; if(dappsById[_id].dappStatus==status.inRevote){ defendantSettlement(_id,isScam); } jurorSettlement(_id,isScam); dappsById[_id].isActive =false; dappsById[_id].dappStatus=isScam?status.scammed:status.Legit; } function requestRevote(uint _id, string memory _remarks)public eligibleToRevote(msg.sender,_id){ require(dappsById[_id].isActive==false, "Cant revote while voting is still in progress"); require(dappsById[_id].dappStatus==status.scammed,"You can only request a revote on projects declared a scam"); address defender= msg.sender; address[] memory blank; dappsById[_id].isActive=true; dappsById[_id].dappStatus=status.inRevote; dappsById[_id].remarks=_remarks; dappsById[_id].representative= defender; dappsById[_id].starTime= now; dappsById[_id].upvoters=blank; dappsById[_id].downvoters=blank; dappsById[_id].upVotes=0; dappsById[_id].downVotes=0; spendingSTT[defender]+=defenderTostake; rewardPoolbyDappId[_id]=0; } function stakersReward(address staker, uint commission) internal{ for(uint i=0;i<stakers.length;i++){ uint reward= commission *netBalanceSTT(stakers[i])/stakedSTT; _STTstakeBalance[stakers[i]]+=reward; } stakedSTT+=commission; } function defendantSettlement(uint _id, bool isScam)internal { address defender =dappsById[_id].representative; if(isScam){ spendingSTT[defender]-=defenderTostake; // If the Defender loses appeal, they lose their Defending Fee. _STTstakeBalance[defender]-=defenderTostake; // The Defenders lost appeal fees are taken from their staked STT. rewardPoolbyDappId[_id]+=defenderTostake; // The Defending Fee is transferred to the reward pool. }else{ spendingSTT[defender]-=defenderTostake; // If the Defender wins the appeal, the Defending Fee is returned. } } function addCurator(address curator) onlyOwner(msg.sender)public{ activeCurators[curator]= true; } function removeCurator(address curator) onlyOwner(msg.sender)public{ activeCurators[curator]= false; } function jurorSettlement(uint _id, bool isScam)internal{ // If project is a scam then winner is downvoters and losers are upvoters address[] memory winners= isScam?dappsById[_id].downvoters:dappsById[_id].upvoters ; address[] memory losers= isScam?dappsById[_id].upvoters:dappsById[_id].downvoters ; //-- settlement of loosing side(half voting is refunded half is penalized) uint returnedvoting =votingFees/2; for(uint i=0;i<losers.length;i++){ spendingSTT[losers[i]] -=returnedvoting; _STTstakeBalance[losers[i]]-= (votingFees-returnedvoting); _STTstakeBalance[losers[i]]+= returnedvoting; rewardPoolbyDappId[_id]+= (votingFees-returnedvoting); } //-- settlement of winning side(if won, no voting fees charged) uint rewardperJuror= rewardPoolbyDappId[_id]/winners.length; returnedvoting =votingFees; for(uint i=0;i<winners.length;i++){ spendingSTT[winners[i]] -=returnedvoting; _STTstakeBalance[winners[i]]-= (votingFees-returnedvoting);// no net fees is being charged from the staked STT _STTstakeBalance[winners[i]]+= rewardperJuror;// rewarding the winning jurors, by distributing STT to jurors who voted correctly } } function netBalanceSTT(address user)public view returns(uint){ uint balance =_STTstakeBalance[user] - spendingSTT[user]; return balance; } function isunique(address staker)view internal returns(bool){ bool result=true; for(uint i=0; i<stakers.length;i++){ if (stakers[i]==staker){ result=false; } } return result; } }
address lister= msg.sender; dapp memory regDapp; regDapp.name=_name; regDapp.contractAddress=_contractAddress; regDapp.uri=_uri; regDapp.dappStatus=status.inconclusive; regDapp.representative= lister; regDapp.id= dappCounter; regDapp.starTime=now; // added timestamp dappsById[dappCounter]=regDapp; _STTstakeBalance[lister]-= listingFees;// deduct fees from stake and credit to reward pool rewardPoolbyDappId[dappCounter]+= listingFees; dappCounter++;// increment the counter listingTime[lister]= now;
function registerDapp(string memory _name,address _contractAddress,string memory _uri)listerEligiblity(msg.sender)public
function registerDapp(string memory _name,address _contractAddress,string memory _uri)listerEligiblity(msg.sender)public
21896
LT_Token
withdraw
contract LT_Token is CappedToken, PausableToken { string public constant name = "LittleBeeX® Token"; // solium-disable-line uppercase string public constant symbol = "LT"; // solium-disable-line uppercase uint8 public constant decimals = 18; // solium-disable-line uppercase uint256 public constant INITIAL_SUPPLY = 0; uint256 public constant MAX_SUPPLY = 50 * 10000 * 10000 * (10 ** uint256(decimals)); /** * @dev Constructor that gives msg.sender all of existing tokens. */ constructor() CappedToken(MAX_SUPPLY) public { totalSupply_ = INITIAL_SUPPLY; balances[msg.sender] = INITIAL_SUPPLY; emit Transfer(0x0, msg.sender, INITIAL_SUPPLY); } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) onlyOwner canMint whenNotPaused public returns (bool) { return super.mint(_to, _amount); } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner canMint whenNotPaused public returns (bool) { return super.finishMinting(); } /**@dev Withdrawals from contracts can only be made to Owner.*/ function withdraw (uint256 _amount) public returns (bool) {<FILL_FUNCTION_BODY> } //The fallback function. function() payable public { revert(); } }
contract LT_Token is CappedToken, PausableToken { string public constant name = "LittleBeeX® Token"; // solium-disable-line uppercase string public constant symbol = "LT"; // solium-disable-line uppercase uint8 public constant decimals = 18; // solium-disable-line uppercase uint256 public constant INITIAL_SUPPLY = 0; uint256 public constant MAX_SUPPLY = 50 * 10000 * 10000 * (10 ** uint256(decimals)); /** * @dev Constructor that gives msg.sender all of existing tokens. */ constructor() CappedToken(MAX_SUPPLY) public { totalSupply_ = INITIAL_SUPPLY; balances[msg.sender] = INITIAL_SUPPLY; emit Transfer(0x0, msg.sender, INITIAL_SUPPLY); } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) onlyOwner canMint whenNotPaused public returns (bool) { return super.mint(_to, _amount); } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner canMint whenNotPaused public returns (bool) { return super.finishMinting(); } <FILL_FUNCTION> //The fallback function. function() payable public { revert(); } }
require(msg.sender == owner); msg.sender.transfer(_amount); return true;
function withdraw (uint256 _amount) public returns (bool)
/**@dev Withdrawals from contracts can only be made to Owner.*/ function withdraw (uint256 _amount) public returns (bool)
3751
YoyoArkCoin
transfer
contract YoyoArkCoin is owned, ERC20Interface { // Public variables of the token string public constant standard = 'ERC20'; string public constant name = 'Yoyo Ark Coin'; string public constant symbol = 'YAC'; uint8 public constant decimals = 18; uint public registrationTime = 0; bool public registered = false; uint256 totalTokens = 960 * 1000 * 1000 * 10**18; // This creates an array with all balances mapping (address => uint256) balances; // Owner of account approves the transfer of an amount to another account mapping(address => mapping (address => uint256)) allowed; // These are related to YAC team members mapping (address => bool) public frozenAccount; mapping (address => uint[3]) public frozenTokens; // Variable of token frozen rules for YAC team members. uint public unlockat; // Constructor constructor() public { } // This unnamed function is called whenever someone tries to send ether to it function () private { revert(); // Prevents accidental sending of ether } function totalSupply() constant public returns (uint256) { return totalTokens; } // What is the balance of a particular account? function balanceOf(address _owner) constant public returns (uint256) { return balances[_owner]; } // Transfer the balance from owner's account to another account function transfer(address _to, uint256 _amount) public returns (bool success) {<FILL_FUNCTION_BODY> } // Send _value amount of tokens from address _from to address _to // The transferFrom method is used for a withdraw workflow, allowing contracts to send // tokens on your behalf, for example to "deposit" to a contract address and/or to charge // fees in sub-currencies; the command should fail unless the _from account has // deliberately authorized the sender of the message via some mechanism; we propose // these standardized APIs for approval: function transferFrom(address _from, address _to, uint256 _amount) public returns (bool success) { if (!registered) return false; if (_amount <= 0) return false; if (frozenRules(_from, _amount)) return false; if (balances[_from] >= _amount && allowed[_from][msg.sender] >= _amount && balances[_to] + _amount > balances[_to]) { balances[_from] -= _amount; allowed[_from][msg.sender] -= _amount; balances[_to] += _amount; emit Transfer(_from, _to, _amount); return true; } else { return false; } } // Allow _spender to withdraw from your account, multiple times, up to the _value amount. // If this function is called again it overwrites the current allowance with _value. function approve(address _spender, uint256 _amount) public returns (bool success) { allowed[msg.sender][_spender] = _amount; emit Approval(msg.sender, _spender, _amount); return true; } function allowance(address _owner, address _spender) constant public returns (uint256 remaining) { return allowed[_owner][_spender]; } /// @dev Register for Token Initialize, /// 100% of total Token will initialize to dev Account. function initRegister() public { // (85%) of total supply to sender contract balances[msg.sender] = 960 * 1000 * 1000 * 10**18; // Frozen 15% of total supply for team members. registered = true; registrationTime = now; unlockat = registrationTime + 6 * 30 days; // Frozen rest (15%) of total supply for development team and contributors // 144,000,000 * 10**18; frozenForTeam(); } /// @dev Frozen for the team members. function frozenForTeam() internal { uint totalFrozeNumber = 144 * 1000 * 1000 * 10**18; freeze(msg.sender, totalFrozeNumber); } /// @dev Frozen 15% of total supply for team members. /// @param _account The address of account to be frozen. /// @param _totalAmount The amount of tokens to be frozen. function freeze(address _account, uint _totalAmount) public onlyOwner { frozenAccount[_account] = true; frozenTokens[_account][0] = _totalAmount; // 100% of locked token within 6 months } /// @dev Token frozen rules for token holders. /// @param _from The token sender. /// @param _value The token amount. function frozenRules(address _from, uint256 _value) internal returns (bool success) { if (frozenAccount[_from]) { if (now < unlockat) { // 100% locked within the first 6 months. if (balances[_from] - _value < frozenTokens[_from][0]) return true; } else { // 100% unlocked after 6 months. frozenAccount[_from] = false; } } return false; } }
contract YoyoArkCoin is owned, ERC20Interface { // Public variables of the token string public constant standard = 'ERC20'; string public constant name = 'Yoyo Ark Coin'; string public constant symbol = 'YAC'; uint8 public constant decimals = 18; uint public registrationTime = 0; bool public registered = false; uint256 totalTokens = 960 * 1000 * 1000 * 10**18; // This creates an array with all balances mapping (address => uint256) balances; // Owner of account approves the transfer of an amount to another account mapping(address => mapping (address => uint256)) allowed; // These are related to YAC team members mapping (address => bool) public frozenAccount; mapping (address => uint[3]) public frozenTokens; // Variable of token frozen rules for YAC team members. uint public unlockat; // Constructor constructor() public { } // This unnamed function is called whenever someone tries to send ether to it function () private { revert(); // Prevents accidental sending of ether } function totalSupply() constant public returns (uint256) { return totalTokens; } // What is the balance of a particular account? function balanceOf(address _owner) constant public returns (uint256) { return balances[_owner]; } <FILL_FUNCTION> // Send _value amount of tokens from address _from to address _to // The transferFrom method is used for a withdraw workflow, allowing contracts to send // tokens on your behalf, for example to "deposit" to a contract address and/or to charge // fees in sub-currencies; the command should fail unless the _from account has // deliberately authorized the sender of the message via some mechanism; we propose // these standardized APIs for approval: function transferFrom(address _from, address _to, uint256 _amount) public returns (bool success) { if (!registered) return false; if (_amount <= 0) return false; if (frozenRules(_from, _amount)) return false; if (balances[_from] >= _amount && allowed[_from][msg.sender] >= _amount && balances[_to] + _amount > balances[_to]) { balances[_from] -= _amount; allowed[_from][msg.sender] -= _amount; balances[_to] += _amount; emit Transfer(_from, _to, _amount); return true; } else { return false; } } // Allow _spender to withdraw from your account, multiple times, up to the _value amount. // If this function is called again it overwrites the current allowance with _value. function approve(address _spender, uint256 _amount) public returns (bool success) { allowed[msg.sender][_spender] = _amount; emit Approval(msg.sender, _spender, _amount); return true; } function allowance(address _owner, address _spender) constant public returns (uint256 remaining) { return allowed[_owner][_spender]; } /// @dev Register for Token Initialize, /// 100% of total Token will initialize to dev Account. function initRegister() public { // (85%) of total supply to sender contract balances[msg.sender] = 960 * 1000 * 1000 * 10**18; // Frozen 15% of total supply for team members. registered = true; registrationTime = now; unlockat = registrationTime + 6 * 30 days; // Frozen rest (15%) of total supply for development team and contributors // 144,000,000 * 10**18; frozenForTeam(); } /// @dev Frozen for the team members. function frozenForTeam() internal { uint totalFrozeNumber = 144 * 1000 * 1000 * 10**18; freeze(msg.sender, totalFrozeNumber); } /// @dev Frozen 15% of total supply for team members. /// @param _account The address of account to be frozen. /// @param _totalAmount The amount of tokens to be frozen. function freeze(address _account, uint _totalAmount) public onlyOwner { frozenAccount[_account] = true; frozenTokens[_account][0] = _totalAmount; // 100% of locked token within 6 months } /// @dev Token frozen rules for token holders. /// @param _from The token sender. /// @param _value The token amount. function frozenRules(address _from, uint256 _value) internal returns (bool success) { if (frozenAccount[_from]) { if (now < unlockat) { // 100% locked within the first 6 months. if (balances[_from] - _value < frozenTokens[_from][0]) return true; } else { // 100% unlocked after 6 months. frozenAccount[_from] = false; } } return false; } }
if (!registered) return false; if (_amount <= 0) return false; if (frozenRules(msg.sender, _amount)) return false; if (balances[msg.sender] >= _amount && balances[_to] + _amount > balances[_to]) { balances[msg.sender] -= _amount; balances[_to] += _amount; emit Transfer(msg.sender, _to, _amount); return true; } else { return false; }
function transfer(address _to, uint256 _amount) public returns (bool success)
// Transfer the balance from owner's account to another account function transfer(address _to, uint256 _amount) public returns (bool success)
8360
IOwned
owner
contract IOwned { // this function isn't abstract since the compiler emits automatically generated getter functions as external function owner() public constant returns (address owner) {<FILL_FUNCTION_BODY> } function transferOwnership(address _newOwner) public; function acceptOwnership() public; }
contract IOwned { <FILL_FUNCTION> function transferOwnership(address _newOwner) public; function acceptOwnership() public; }
owner;
function owner() public constant returns (address owner)
// this function isn't abstract since the compiler emits automatically generated getter functions as external function owner() public constant returns (address owner)
9198
Phila_Token
null
contract Phila_Token is ERC20Interface, Owned { string public constant symbol = "φιλα"; string public constant name = "φιλανθρωπία"; uint8 public constant decimals = 0; uint private constant _totalSupply = 10000000; address public vaultAddress; bool public fundingEnabled; uint public totalCollected; // In wei uint public tokenPrice; // In wei mapping(address => uint) balances; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ constructor() public {<FILL_FUNCTION_BODY> } function setVaultAddress(address _vaultAddress) public onlyOwner { vaultAddress = _vaultAddress; return; } function setFundingEnabled(bool _fundingEnabled) public onlyOwner { fundingEnabled = _fundingEnabled; return; } function updateTokenPrice(uint _newTokenPrice) public onlyOwner { require(_newTokenPrice > 0); tokenPrice = _newTokenPrice; return; } // ------------------------------------------------------------------------ // 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) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // 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 // // THIS TOKENS ARE NOT TRANSFERRABLE. // // ------------------------------------------------------------------------ function approve(address, uint) public returns (bool) { revert(); return false; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // // THIS TOKENS ARE NOT TRANSFERRABLE. // // ------------------------------------------------------------------------ function allowance(address, address) public constant returns (uint) { return 0; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to `to` account // // THIS TOKENS ARE NOT TRANSFERRABLE. // // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address _to, uint _amount) public returns (bool) { if (_amount == 0) { emit Transfer(msg.sender, _to, _amount); // Follow the spec to louch the event when transfer 0 return true; } revert(); return false; } // ------------------------------------------------------------------------ // Transfer `tokens` from the `from` account to the `to` account // // THIS TOKENS ARE NOT TRANSFERRABLE. // // ------------------------------------------------------------------------ function transferFrom(address, address, uint) public returns (bool) { revert(); return false; } function () public payable { require (fundingEnabled && (tokenPrice > 0) && (msg.value >= tokenPrice)); totalCollected += msg.value; //Send the ether to the vault vaultAddress.transfer(msg.value); uint tokens = msg.value / tokenPrice; // Do not allow transfer to 0x0 or the token contract itself require((msg.sender != 0) && (msg.sender != address(this))); // If the amount being transfered is more than the balance of the // account the transfer throws uint previousBalanceFrom = balances[this]; require(previousBalanceFrom >= tokens); // First update the balance array with the new value for the address // sending the tokens balances[this] = previousBalanceFrom - tokens; // Then update the balance array with the new value for the address // receiving the tokens uint previousBalanceTo = balances[msg.sender]; require(previousBalanceTo + tokens >= previousBalanceTo); // Check for overflow balances[msg.sender] = previousBalanceTo + tokens; // An event to make the transfer easy to find on the blockchain emit Transfer(this, msg.sender, tokens); return; } /// @notice This method can be used by the owner to extract mistakenly /// sent tokens to this contract. /// @param _token The address of the token contract that you want to recover /// set to 0 in case you want to extract ether. // // THIS TOKENS ARE NOT TRANSFERRABLE. // function claimTokens(address _token) public onlyOwner { require(_token != address(this)); if (_token == 0x0) { owner.transfer(address(this).balance); return; } ERC20Interface token = ERC20Interface(_token); uint balance = token.balanceOf(this); token.transfer(owner, balance); emit ClaimedTokens(_token, owner, balance); } event ClaimedTokens(address indexed _token, address indexed _controller, uint _amount); }
contract Phila_Token is ERC20Interface, Owned { string public constant symbol = "φιλα"; string public constant name = "φιλανθρωπία"; uint8 public constant decimals = 0; uint private constant _totalSupply = 10000000; address public vaultAddress; bool public fundingEnabled; uint public totalCollected; // In wei uint public tokenPrice; // In wei mapping(address => uint) balances; <FILL_FUNCTION> function setVaultAddress(address _vaultAddress) public onlyOwner { vaultAddress = _vaultAddress; return; } function setFundingEnabled(bool _fundingEnabled) public onlyOwner { fundingEnabled = _fundingEnabled; return; } function updateTokenPrice(uint _newTokenPrice) public onlyOwner { require(_newTokenPrice > 0); tokenPrice = _newTokenPrice; return; } // ------------------------------------------------------------------------ // 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) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // 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 // // THIS TOKENS ARE NOT TRANSFERRABLE. // // ------------------------------------------------------------------------ function approve(address, uint) public returns (bool) { revert(); return false; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // // THIS TOKENS ARE NOT TRANSFERRABLE. // // ------------------------------------------------------------------------ function allowance(address, address) public constant returns (uint) { return 0; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to `to` account // // THIS TOKENS ARE NOT TRANSFERRABLE. // // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address _to, uint _amount) public returns (bool) { if (_amount == 0) { emit Transfer(msg.sender, _to, _amount); // Follow the spec to louch the event when transfer 0 return true; } revert(); return false; } // ------------------------------------------------------------------------ // Transfer `tokens` from the `from` account to the `to` account // // THIS TOKENS ARE NOT TRANSFERRABLE. // // ------------------------------------------------------------------------ function transferFrom(address, address, uint) public returns (bool) { revert(); return false; } function () public payable { require (fundingEnabled && (tokenPrice > 0) && (msg.value >= tokenPrice)); totalCollected += msg.value; //Send the ether to the vault vaultAddress.transfer(msg.value); uint tokens = msg.value / tokenPrice; // Do not allow transfer to 0x0 or the token contract itself require((msg.sender != 0) && (msg.sender != address(this))); // If the amount being transfered is more than the balance of the // account the transfer throws uint previousBalanceFrom = balances[this]; require(previousBalanceFrom >= tokens); // First update the balance array with the new value for the address // sending the tokens balances[this] = previousBalanceFrom - tokens; // Then update the balance array with the new value for the address // receiving the tokens uint previousBalanceTo = balances[msg.sender]; require(previousBalanceTo + tokens >= previousBalanceTo); // Check for overflow balances[msg.sender] = previousBalanceTo + tokens; // An event to make the transfer easy to find on the blockchain emit Transfer(this, msg.sender, tokens); return; } /// @notice This method can be used by the owner to extract mistakenly /// sent tokens to this contract. /// @param _token The address of the token contract that you want to recover /// set to 0 in case you want to extract ether. // // THIS TOKENS ARE NOT TRANSFERRABLE. // function claimTokens(address _token) public onlyOwner { require(_token != address(this)); if (_token == 0x0) { owner.transfer(address(this).balance); return; } ERC20Interface token = ERC20Interface(_token); uint balance = token.balanceOf(this); token.transfer(owner, balance); emit ClaimedTokens(_token, owner, balance); } event ClaimedTokens(address indexed _token, address indexed _controller, uint _amount); }
balances[this] = _totalSupply; emit Transfer(address(0), this, _totalSupply);
constructor() public
// ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ constructor() public
45758
JustSwapToken
addMinter
contract JustSwapToken is ERC20, ERC20Detailed { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint; uint256 public tokenSalePrice = 0.00005 ether; bool public _tokenSaleMode = true; address public governance; mapping (address => bool) public minters; constructor () public ERC20Detailed("JustSwapToken", "JST", 18) { governance = msg.sender; minters[msg.sender] = true; } function mint(address account, uint256 amount) public { require(minters[msg.sender], "!minter"); _mint(account, amount); } function burn(uint256 amount) public { _burn(msg.sender, amount); } function setGovernance(address _governance) public { require(msg.sender == governance, "!governance"); governance = _governance; } function addMinter(address _minter) public {<FILL_FUNCTION_BODY> } function removeMinter(address _minter) public { require(msg.sender == governance, "!governance"); minters[_minter] = false; } function buyToken() public payable { require(_tokenSaleMode, "token sale is over"); uint256 newTokens = SafeMath.mul(SafeMath.div(msg.value, tokenSalePrice),1e18); _mint(msg.sender, newTokens); } function() external payable { buyToken(); } function endTokenSale() public { require(msg.sender == governance, "!governance"); _tokenSaleMode = false; } function withdraw() external { require(msg.sender == governance, "!governance"); msg.sender.transfer(address(this).balance); } }
contract JustSwapToken is ERC20, ERC20Detailed { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint; uint256 public tokenSalePrice = 0.00005 ether; bool public _tokenSaleMode = true; address public governance; mapping (address => bool) public minters; constructor () public ERC20Detailed("JustSwapToken", "JST", 18) { governance = msg.sender; minters[msg.sender] = true; } function mint(address account, uint256 amount) public { require(minters[msg.sender], "!minter"); _mint(account, amount); } function burn(uint256 amount) public { _burn(msg.sender, amount); } function setGovernance(address _governance) public { require(msg.sender == governance, "!governance"); governance = _governance; } <FILL_FUNCTION> function removeMinter(address _minter) public { require(msg.sender == governance, "!governance"); minters[_minter] = false; } function buyToken() public payable { require(_tokenSaleMode, "token sale is over"); uint256 newTokens = SafeMath.mul(SafeMath.div(msg.value, tokenSalePrice),1e18); _mint(msg.sender, newTokens); } function() external payable { buyToken(); } function endTokenSale() public { require(msg.sender == governance, "!governance"); _tokenSaleMode = false; } function withdraw() external { require(msg.sender == governance, "!governance"); msg.sender.transfer(address(this).balance); } }
require(msg.sender == governance, "!governance"); minters[_minter] = true;
function addMinter(address _minter) public
function addMinter(address _minter) public
28720
Controller
increaseApproval
contract Controller is Finalizable { Ledger public ledger; Token public token; address public sale; constructor (address _token, address _ledger) public { require(_token != 0); require(_ledger != 0); ledger = Ledger(_ledger); token = Token(_token); } function setToken(address _token) public onlyOwner { token = Token(_token); } function setLedger(address _ledger) public onlyOwner { ledger = Ledger(_ledger); } function setSale(address _sale) public onlyOwner { sale = _sale; } modifier onlyToken() { require(msg.sender == address(token)); _; } modifier onlyLedger() { require(msg.sender == address(ledger)); _; } modifier onlySale() { require(msg.sender == sale); _; } function totalSupply() public onlyToken view returns (uint256) { return ledger.totalSupply(); } function balanceOf(address _a) public onlyToken view returns (uint256) { return ledger.balanceOf(_a); } function allowance(address _owner, address _spender) public onlyToken view returns (uint256) { return ledger.allowance(_owner, _spender); } function transfer(address _from, address _to, uint256 _value) public onlyToken returns (bool) { return ledger.transfer(_from, _to, _value); } function transferFrom(address _spender, address _from, address _to, uint256 _value) public onlyToken returns (bool) { return ledger.transferFrom(_spender, _from, _to, _value); } function burn(address _owner, uint256 _amount) public onlyToken returns (bool) { return ledger.burn(_owner, _amount); } function approve(address _owner, address _spender, uint256 _value) public onlyToken returns (bool) { return ledger.approve(_owner, _spender, _value); } function increaseApproval(address _owner, address _spender, uint256 _addedValue) public onlyToken returns (bool) {<FILL_FUNCTION_BODY> } function decreaseApproval(address _owner, address _spender, uint256 _subtractedValue) public onlyToken returns (bool) { return ledger.decreaseApproval(_owner, _spender, _subtractedValue); } function proxyMint(address _to, uint256 _value) public onlySale { token.controllerMint(_to, _value); } function proxyTransfer(address _from, address _to, uint256 _value) public onlySale { token.controllerTransfer(_from, _to, _value); } }
contract Controller is Finalizable { Ledger public ledger; Token public token; address public sale; constructor (address _token, address _ledger) public { require(_token != 0); require(_ledger != 0); ledger = Ledger(_ledger); token = Token(_token); } function setToken(address _token) public onlyOwner { token = Token(_token); } function setLedger(address _ledger) public onlyOwner { ledger = Ledger(_ledger); } function setSale(address _sale) public onlyOwner { sale = _sale; } modifier onlyToken() { require(msg.sender == address(token)); _; } modifier onlyLedger() { require(msg.sender == address(ledger)); _; } modifier onlySale() { require(msg.sender == sale); _; } function totalSupply() public onlyToken view returns (uint256) { return ledger.totalSupply(); } function balanceOf(address _a) public onlyToken view returns (uint256) { return ledger.balanceOf(_a); } function allowance(address _owner, address _spender) public onlyToken view returns (uint256) { return ledger.allowance(_owner, _spender); } function transfer(address _from, address _to, uint256 _value) public onlyToken returns (bool) { return ledger.transfer(_from, _to, _value); } function transferFrom(address _spender, address _from, address _to, uint256 _value) public onlyToken returns (bool) { return ledger.transferFrom(_spender, _from, _to, _value); } function burn(address _owner, uint256 _amount) public onlyToken returns (bool) { return ledger.burn(_owner, _amount); } function approve(address _owner, address _spender, uint256 _value) public onlyToken returns (bool) { return ledger.approve(_owner, _spender, _value); } <FILL_FUNCTION> function decreaseApproval(address _owner, address _spender, uint256 _subtractedValue) public onlyToken returns (bool) { return ledger.decreaseApproval(_owner, _spender, _subtractedValue); } function proxyMint(address _to, uint256 _value) public onlySale { token.controllerMint(_to, _value); } function proxyTransfer(address _from, address _to, uint256 _value) public onlySale { token.controllerTransfer(_from, _to, _value); } }
return ledger.increaseApproval(_owner, _spender, _addedValue);
function increaseApproval(address _owner, address _spender, uint256 _addedValue) public onlyToken returns (bool)
function increaseApproval(address _owner, address _spender, uint256 _addedValue) public onlyToken returns (bool)
24653
MemeNFT
totalSupply
contract MemeNFT is ERC20Interface, SafeMath { string public name; string public symbol; uint8 public decimals; // 18 decimals is the strongly suggested default, avoid changing it uint256 public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; constructor() public { name = "Meme NFT"; symbol = "Meme NFT"; decimals = 18; _totalSupply = 500000000000000000000000000; balances[msg.sender] = 500000000000000000000000000; emit Transfer(address(0), msg.sender, _totalSupply); } function totalSupply() public view returns (uint) {<FILL_FUNCTION_BODY> } function balanceOf(address tokenOwner) public view returns (uint balance) { return balances[tokenOwner]; } function allowance(address tokenOwner, address spender) public view returns (uint remaining) { return allowed[tokenOwner][spender]; } function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(msg.sender, to, tokens); return true; } function transferFrom(address from, address to, uint tokens) public returns (bool success) { 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; } }
contract MemeNFT is ERC20Interface, SafeMath { string public name; string public symbol; uint8 public decimals; // 18 decimals is the strongly suggested default, avoid changing it uint256 public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; constructor() public { name = "Meme NFT"; symbol = "Meme NFT"; decimals = 18; _totalSupply = 500000000000000000000000000; balances[msg.sender] = 500000000000000000000000000; emit Transfer(address(0), msg.sender, _totalSupply); } <FILL_FUNCTION> function balanceOf(address tokenOwner) public view returns (uint balance) { return balances[tokenOwner]; } function allowance(address tokenOwner, address spender) public view returns (uint remaining) { return allowed[tokenOwner][spender]; } function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(msg.sender, to, tokens); return true; } function transferFrom(address from, address to, uint tokens) public returns (bool success) { 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; } }
return _totalSupply - balances[address(0)];
function totalSupply() public view returns (uint)
function totalSupply() public view returns (uint)
12665
GamerGoldGG
freeze
contract GamerGoldGG is SafeMath{ string public name; string public symbol; uint8 public decimals; uint256 public totalSupply; address public owner; /* This creates an array with all balances */ mapping (address => uint256) public balanceOf; mapping (address => uint256) public freezeOf; mapping (address => mapping (address => uint256)) public allowance; /* This generates a public event on the blockchain that will notify clients */ event Transfer(address indexed from, address indexed to, uint256 value); /* This notifies clients about the amount burnt */ event Burn(address indexed from, uint256 value); /* This notifies clients about the amount minted */ event Mint(address indexed from, uint256 value); /* This notifies clients about the amount frozen */ event Freeze(address indexed from, uint256 value); /* This notifies clients about the amount unfrozen */ event Unfreeze(address indexed from, uint256 value); /* Initializes contract with initial supply tokens to the creator of the contract */ function GamerGoldGG( uint256 initialSupply, string tokenName, uint8 decimalUnits, string tokenSymbol ) { balanceOf[msg.sender] = initialSupply; // Give the creator all initial tokens totalSupply = initialSupply; // Update total supply name = tokenName; // Set the name for display purposes symbol = tokenSymbol; // Set the symbol for display purposes decimals = decimalUnits; // Amount of decimals for display purposes owner = msg.sender; } /* Send coins */ function transfer(address _to, uint256 _value) { 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) { 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 burn(uint256 _value) returns (bool success) { if (balanceOf[msg.sender] < _value) throw; // Check if the sender has enough if (_value <= 0) throw; balanceOf[msg.sender] = SafeMath.safeSub(balanceOf[msg.sender], _value); // Subtract from the sender totalSupply = SafeMath.safeSub(totalSupply,_value); // Updates totalSupply Burn(msg.sender, _value); return true; } function mint(uint256 _value) returns (bool success) { if (balanceOf[msg.sender] < _value) throw; // Check if the sender has enough if (_value <= 0) throw; balanceOf[msg.sender] = SafeMath.safeAdd(balanceOf[msg.sender], _value); // Subtract from the sender totalSupply = SafeMath.safeAdd(totalSupply,_value); // Updates totalSupply Mint(msg.sender, _value); return true; } function freeze(uint256 _value) returns (bool success) {<FILL_FUNCTION_BODY> } function unfreeze(uint256 _value) returns (bool success) { if (freezeOf[msg.sender] < _value) throw; // Check if the sender has enough if (_value <= 0) throw; freezeOf[msg.sender] = SafeMath.safeSub(freezeOf[msg.sender], _value); // Subtract from the sender balanceOf[msg.sender] = SafeMath.safeAdd(balanceOf[msg.sender], _value); Unfreeze(msg.sender, _value); return true; } // transfer balance to owner function withdrawEther(uint256 amount) { if(msg.sender != owner)throw; owner.transfer(amount); } // can accept ether function() payable { } }
contract GamerGoldGG is SafeMath{ string public name; string public symbol; uint8 public decimals; uint256 public totalSupply; address public owner; /* This creates an array with all balances */ mapping (address => uint256) public balanceOf; mapping (address => uint256) public freezeOf; mapping (address => mapping (address => uint256)) public allowance; /* This generates a public event on the blockchain that will notify clients */ event Transfer(address indexed from, address indexed to, uint256 value); /* This notifies clients about the amount burnt */ event Burn(address indexed from, uint256 value); /* This notifies clients about the amount minted */ event Mint(address indexed from, uint256 value); /* This notifies clients about the amount frozen */ event Freeze(address indexed from, uint256 value); /* This notifies clients about the amount unfrozen */ event Unfreeze(address indexed from, uint256 value); /* Initializes contract with initial supply tokens to the creator of the contract */ function GamerGoldGG( uint256 initialSupply, string tokenName, uint8 decimalUnits, string tokenSymbol ) { balanceOf[msg.sender] = initialSupply; // Give the creator all initial tokens totalSupply = initialSupply; // Update total supply name = tokenName; // Set the name for display purposes symbol = tokenSymbol; // Set the symbol for display purposes decimals = decimalUnits; // Amount of decimals for display purposes owner = msg.sender; } /* Send coins */ function transfer(address _to, uint256 _value) { 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) { 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 burn(uint256 _value) returns (bool success) { if (balanceOf[msg.sender] < _value) throw; // Check if the sender has enough if (_value <= 0) throw; balanceOf[msg.sender] = SafeMath.safeSub(balanceOf[msg.sender], _value); // Subtract from the sender totalSupply = SafeMath.safeSub(totalSupply,_value); // Updates totalSupply Burn(msg.sender, _value); return true; } function mint(uint256 _value) returns (bool success) { if (balanceOf[msg.sender] < _value) throw; // Check if the sender has enough if (_value <= 0) throw; balanceOf[msg.sender] = SafeMath.safeAdd(balanceOf[msg.sender], _value); // Subtract from the sender totalSupply = SafeMath.safeAdd(totalSupply,_value); // Updates totalSupply Mint(msg.sender, _value); return true; } <FILL_FUNCTION> function unfreeze(uint256 _value) returns (bool success) { if (freezeOf[msg.sender] < _value) throw; // Check if the sender has enough if (_value <= 0) throw; freezeOf[msg.sender] = SafeMath.safeSub(freezeOf[msg.sender], _value); // Subtract from the sender balanceOf[msg.sender] = SafeMath.safeAdd(balanceOf[msg.sender], _value); Unfreeze(msg.sender, _value); return true; } // transfer balance to owner function withdrawEther(uint256 amount) { if(msg.sender != owner)throw; owner.transfer(amount); } // can accept ether function() payable { } }
if (balanceOf[msg.sender] < _value) throw; // Check if the sender has enough if (_value <= 0) throw; balanceOf[msg.sender] = SafeMath.safeSub(balanceOf[msg.sender], _value); // Subtract from the sender freezeOf[msg.sender] = SafeMath.safeAdd(freezeOf[msg.sender], _value); // Updates totalSupply Freeze(msg.sender, _value); return true;
function freeze(uint256 _value) returns (bool success)
function freeze(uint256 _value) returns (bool success)
60442
LiyamToken
transfer
contract LiyamToken is ERC20Interface, Owned { using SafeMath for uint; string public symbol; string public name; uint8 public decimals; uint _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ constructor() public { symbol = "Lyth"; name = "Liyam Token"; decimals = 18; _totalSupply = 100000000 * 10**uint(decimals); balances[owner] = _totalSupply; emit Transfer(address(0), owner, _totalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public view returns (uint) { return _totalSupply.sub(balances[address(0)]); } // ------------------------------------------------------------------------ // Get the token balance for account `tokenOwner` // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public view 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] = 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; } // ------------------------------------------------------------------------ // 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 view 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; } function BurnToken(address _from) public returns(bool success) { require(owner == msg.sender); require(balances[_from] > 0); // Check if the sender has enough uint _value = balances[_from]; balances[_from] -= _value; // Subtract from the sender _totalSupply -= _value; // Updates totalSupply Burn(_from, _value); 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 LiyamToken is ERC20Interface, Owned { using SafeMath for uint; string public symbol; string public name; uint8 public decimals; uint _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ constructor() public { symbol = "Lyth"; name = "Liyam Token"; decimals = 18; _totalSupply = 100000000 * 10**uint(decimals); balances[owner] = _totalSupply; emit Transfer(address(0), owner, _totalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public view returns (uint) { return _totalSupply.sub(balances[address(0)]); } // ------------------------------------------------------------------------ // Get the token balance for account `tokenOwner` // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public view 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] = 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; } // ------------------------------------------------------------------------ // 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 view 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; } function BurnToken(address _from) public returns(bool success) { require(owner == msg.sender); require(balances[_from] > 0); // Check if the sender has enough uint _value = balances[_from]; balances[_from] -= _value; // Subtract from the sender _totalSupply -= _value; // Updates totalSupply Burn(_from, _value); 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] = balances[msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); emit Transfer(msg.sender, to, tokens); return true;
function transfer(address to, uint tokens) public returns (bool success)
// ------------------------------------------------------------------------ // 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)
89433
BurnableToken
burn
contract BurnableToken is StandardToken { event Burn(address indexed burner, uint256 value); /** * @dev Burns a specific amount of tokens. * @param _value The amount of token to be burned. */ function burn(uint256 _value) public {<FILL_FUNCTION_BODY> } }
contract BurnableToken is StandardToken { event Burn(address indexed burner, uint256 value); <FILL_FUNCTION> }
require(_value > 0); 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); Burn(burner, _value);
function burn(uint256 _value) public
/** * @dev Burns a specific amount of tokens. * @param _value The amount of token to be burned. */ function burn(uint256 _value) public
35693
Extradecoin
allocateSalesTokens
contract Extradecoin is Owner { using SafeMath for uint256; string public constant name = "EXTRADECOIN"; string public constant symbol = "ETE"; uint public constant decimals = 18; uint256 constant public totalSupply = 250000000 * 10 ** 18; // 250 mil tokens will be supplied mapping(address => uint256) internal balances; mapping(address => mapping (address => uint256)) internal allowed; address public adminAddress; address public walletAddress; address public founderAddress; address public advisorAddress; mapping(address => uint256) public totalInvestedAmountOf; uint constant lockPeriod1 = 3 years; // 1st locked period for tokens allocation of founder and team uint constant lockPeriod2 = 1 years; // 2nd locked period for tokens allocation of founder and team uint constant lockPeriod3 = 90 days; // 3nd locked period for tokens allocation of advisor and ICO partners uint constant NOT_SALE = 0; // Not in sales uint constant IN_ICO = 1; // In ICO uint constant END_SALE = 2; // End sales uint256 public constant salesAllocation = 125000000 * 10 ** 18; // 125 mil tokens allocated for sales uint256 public constant founderAllocation = 37500000 * 10 ** 18; // 37.5 mil tokens allocated for founders uint256 public constant advisorAllocation = 25000000 * 10 ** 18; // 25 mil tokens allocated for allocated for ICO partners and bonus fund uint256 public constant reservedAllocation = 62500000 * 10 ** 18; // 62.5 mil tokens allocated for reserved, bounty campaigns, ICO partners, and bonus fund uint256 public constant minInvestedCap = 6000 * 10 ** 18; // 2500 ether for softcap uint256 public constant minInvestedAmount = 0.1 * 10 ** 18; // 0.1 ether for mininum ether contribution per transaction uint saleState; uint256 totalInvestedAmount; uint public icoStartTime; uint public icoEndTime; bool public inActive; bool public isSelling; bool public isTransferable; uint public founderAllocatedTime = 1; uint public advisorAllocatedTime = 1; uint256 public totalRemainingTokensForSales; // Total tokens remaining for sales uint256 public totalAdvisor; // Total tokens allocated for advisor uint256 public totalReservedTokenAllocation; // Total tokens allocated for reserved event Approval(address indexed owner, address indexed spender, uint256 value); // ERC20 standard event event Transfer(address indexed from, address indexed to, uint256 value); // ERC20 standard event event StartICO(uint state); // Start ICO sales event EndICO(uint state); // End ICO sales event AllocateTokensForFounder(address founderAddress, uint256 founderAllocatedTime, uint256 tokenAmount); // Allocate tokens to founders' address event AllocateTokensForAdvisor(address advisorAddress, uint256 advisorAllocatedTime, uint256 tokenAmount); // Allocate tokens to advisor address event AllocateReservedTokens(address reservedAddress, uint256 tokenAmount); // Allocate reserved tokens event AllocateSalesTokens(address salesAllocation, uint256 tokenAmount); // Allocate sales tokens modifier isActive() { require(inActive == false); _; } modifier isInSale() { require(isSelling == true); _; } modifier transferable() { require(isTransferable == true); _; } modifier onlyOwnerOrAdminOrPortal() { require(msg.sender == owner || msg.sender == adminAddress); _; } modifier onlyOwnerOrAdmin() { require(msg.sender == owner || msg.sender == adminAddress); _; } function Extradecoin(address _walletAddr, address _adminAddr) public Owner(msg.sender) { require(_walletAddr != address(0)); require(_adminAddr != address(0)); walletAddress = _walletAddr; adminAddress = _adminAddr; inActive = true; totalInvestedAmount = 0; totalRemainingTokensForSales = salesAllocation; totalAdvisor = advisorAllocation; totalReservedTokenAllocation = reservedAllocation; } // ERC20 standard function function transfer(address _to, uint256 _value) external transferable returns (bool) { require(_to != address(0)); require(_value > 0); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } // ERC20 standard function function transferFrom(address _from, address _to, uint256 _value) external transferable returns (bool) { require(_to != address(0)); require(_from != address(0)); require(_value > 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; } // ERC20 standard function function approve(address _spender, uint256 _value) external transferable returns (bool) { require(_spender != address(0)); require(_value > 0); allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } // Start ICO function startICO() external isActive onlyOwnerOrAdmin returns (bool) { saleState = IN_ICO; icoStartTime = now; isSelling = true; emit StartICO(saleState); return true; } // End ICO function endICO() external isActive onlyOwnerOrAdmin returns (bool) { require(icoEndTime == 0); saleState = END_SALE; isSelling = false; icoEndTime = now; emit EndICO(saleState); return true; } // Activate token sale function function activate() external onlyOwner { inActive = false; } // Deacivate token sale function function deActivate() external onlyOwner { inActive = true; } // Enable transfer feature of tokens function enableTokenTransfer() external isActive onlyOwner { isTransferable = true; } // Modify wallet function changeWallet(address _newAddress) external onlyOwner { require(_newAddress != address(0)); require(walletAddress != _newAddress); walletAddress = _newAddress; } // Modify admin function changeAdminAddress(address _newAddress) external onlyOwner { require(_newAddress != address(0)); require(adminAddress != _newAddress); adminAddress = _newAddress; } // Modify founder address to receive founder tokens allocation function changeFounderAddress(address _newAddress) external onlyOwnerOrAdmin { require(_newAddress != address(0)); require(founderAddress != _newAddress); founderAddress = _newAddress; } // Modify team address to receive team tokens allocation function changeTeamAddress(address _newAddress) external onlyOwnerOrAdmin { require(_newAddress != address(0)); require(advisorAddress != _newAddress); advisorAddress = _newAddress; } // Allocate tokens for founder vested gradually for 4 year function allocateTokensForFounder() external isActive onlyOwnerOrAdmin { require(saleState == END_SALE); require(founderAddress != address(0)); uint256 amount; if (founderAllocatedTime == 1) { require(now >= icoEndTime + lockPeriod1); amount = founderAllocation * 50/100; balances[founderAddress] = balances[founderAddress].add(amount); emit AllocateTokensForFounder(founderAddress, founderAllocatedTime, amount); founderAllocatedTime = 2; return; } if (founderAllocatedTime == 2) { require(now >= icoEndTime + lockPeriod2); amount = founderAllocation * 50/100; balances[founderAddress] = balances[founderAddress].add(amount); emit AllocateTokensForFounder(founderAddress, founderAllocatedTime, amount); founderAllocatedTime = 3; return; } revert(); } // Allocate tokens for advisor and angel investors vested gradually for 1 year function allocateTokensForAdvisor() external isActive onlyOwnerOrAdmin { require(saleState == END_SALE); require(advisorAddress != address(0)); uint256 amount; if (founderAllocatedTime == 1) { amount = advisorAllocation * 50/100; balances[advisorAddress] = balances[advisorAddress].add(amount); emit AllocateTokensForFounder(advisorAddress, founderAllocatedTime, amount); founderAllocatedTime = 2; return; } if (advisorAllocatedTime == 2) { require(now >= icoEndTime + lockPeriod2); amount = advisorAllocation * 125/1000; balances[advisorAddress] = balances[advisorAddress].add(amount); emit AllocateTokensForAdvisor(advisorAddress, advisorAllocatedTime, amount); advisorAllocatedTime = 3; return; } if (advisorAllocatedTime == 3) { require(now >= icoEndTime + lockPeriod3); amount = advisorAllocation * 125/1000; balances[advisorAddress] = balances[advisorAddress].add(amount); emit AllocateTokensForAdvisor(advisorAddress, advisorAllocatedTime, amount); advisorAllocatedTime = 4; return; } if (advisorAllocatedTime == 4) { require(now >= icoEndTime + lockPeriod3); amount = advisorAllocation * 125/1000; balances[advisorAddress] = balances[advisorAddress].add(amount); emit AllocateTokensForAdvisor(advisorAddress, advisorAllocatedTime, amount); advisorAllocatedTime = 5; return; } if (advisorAllocatedTime == 5) { require(now >= icoEndTime + lockPeriod3); amount = advisorAllocation * 125/1000; balances[advisorAddress] = balances[advisorAddress].add(amount); emit AllocateTokensForAdvisor(advisorAddress, advisorAllocatedTime, amount); advisorAllocatedTime = 6; return; } revert(); } // Allocate reserved tokens function allocateReservedTokens(address _addr, uint _amount) external isActive onlyOwnerOrAdmin { require(saleState == END_SALE); require(_amount > 0); require(_addr != address(0)); balances[_addr] = balances[_addr].add(_amount); totalReservedTokenAllocation = totalReservedTokenAllocation.sub(_amount); emit AllocateReservedTokens(_addr, _amount); } // Allocate sales tokens function allocateSalesTokens(address _addr, uint _amount) external isActive onlyOwnerOrAdmin {<FILL_FUNCTION_BODY> } // ERC20 standard function function allowance(address _owner, address _spender) external constant returns (uint256) { return allowed[_owner][_spender]; } // ERC20 standard function function balanceOf(address _owner) external constant returns (uint256 balance) { return balances[_owner]; } // Get softcap reaching status function isSoftCapReached() public view returns (bool) { return totalInvestedAmount >= minInvestedCap; } }
contract Extradecoin is Owner { using SafeMath for uint256; string public constant name = "EXTRADECOIN"; string public constant symbol = "ETE"; uint public constant decimals = 18; uint256 constant public totalSupply = 250000000 * 10 ** 18; // 250 mil tokens will be supplied mapping(address => uint256) internal balances; mapping(address => mapping (address => uint256)) internal allowed; address public adminAddress; address public walletAddress; address public founderAddress; address public advisorAddress; mapping(address => uint256) public totalInvestedAmountOf; uint constant lockPeriod1 = 3 years; // 1st locked period for tokens allocation of founder and team uint constant lockPeriod2 = 1 years; // 2nd locked period for tokens allocation of founder and team uint constant lockPeriod3 = 90 days; // 3nd locked period for tokens allocation of advisor and ICO partners uint constant NOT_SALE = 0; // Not in sales uint constant IN_ICO = 1; // In ICO uint constant END_SALE = 2; // End sales uint256 public constant salesAllocation = 125000000 * 10 ** 18; // 125 mil tokens allocated for sales uint256 public constant founderAllocation = 37500000 * 10 ** 18; // 37.5 mil tokens allocated for founders uint256 public constant advisorAllocation = 25000000 * 10 ** 18; // 25 mil tokens allocated for allocated for ICO partners and bonus fund uint256 public constant reservedAllocation = 62500000 * 10 ** 18; // 62.5 mil tokens allocated for reserved, bounty campaigns, ICO partners, and bonus fund uint256 public constant minInvestedCap = 6000 * 10 ** 18; // 2500 ether for softcap uint256 public constant minInvestedAmount = 0.1 * 10 ** 18; // 0.1 ether for mininum ether contribution per transaction uint saleState; uint256 totalInvestedAmount; uint public icoStartTime; uint public icoEndTime; bool public inActive; bool public isSelling; bool public isTransferable; uint public founderAllocatedTime = 1; uint public advisorAllocatedTime = 1; uint256 public totalRemainingTokensForSales; // Total tokens remaining for sales uint256 public totalAdvisor; // Total tokens allocated for advisor uint256 public totalReservedTokenAllocation; // Total tokens allocated for reserved event Approval(address indexed owner, address indexed spender, uint256 value); // ERC20 standard event event Transfer(address indexed from, address indexed to, uint256 value); // ERC20 standard event event StartICO(uint state); // Start ICO sales event EndICO(uint state); // End ICO sales event AllocateTokensForFounder(address founderAddress, uint256 founderAllocatedTime, uint256 tokenAmount); // Allocate tokens to founders' address event AllocateTokensForAdvisor(address advisorAddress, uint256 advisorAllocatedTime, uint256 tokenAmount); // Allocate tokens to advisor address event AllocateReservedTokens(address reservedAddress, uint256 tokenAmount); // Allocate reserved tokens event AllocateSalesTokens(address salesAllocation, uint256 tokenAmount); // Allocate sales tokens modifier isActive() { require(inActive == false); _; } modifier isInSale() { require(isSelling == true); _; } modifier transferable() { require(isTransferable == true); _; } modifier onlyOwnerOrAdminOrPortal() { require(msg.sender == owner || msg.sender == adminAddress); _; } modifier onlyOwnerOrAdmin() { require(msg.sender == owner || msg.sender == adminAddress); _; } function Extradecoin(address _walletAddr, address _adminAddr) public Owner(msg.sender) { require(_walletAddr != address(0)); require(_adminAddr != address(0)); walletAddress = _walletAddr; adminAddress = _adminAddr; inActive = true; totalInvestedAmount = 0; totalRemainingTokensForSales = salesAllocation; totalAdvisor = advisorAllocation; totalReservedTokenAllocation = reservedAllocation; } // ERC20 standard function function transfer(address _to, uint256 _value) external transferable returns (bool) { require(_to != address(0)); require(_value > 0); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } // ERC20 standard function function transferFrom(address _from, address _to, uint256 _value) external transferable returns (bool) { require(_to != address(0)); require(_from != address(0)); require(_value > 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; } // ERC20 standard function function approve(address _spender, uint256 _value) external transferable returns (bool) { require(_spender != address(0)); require(_value > 0); allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } // Start ICO function startICO() external isActive onlyOwnerOrAdmin returns (bool) { saleState = IN_ICO; icoStartTime = now; isSelling = true; emit StartICO(saleState); return true; } // End ICO function endICO() external isActive onlyOwnerOrAdmin returns (bool) { require(icoEndTime == 0); saleState = END_SALE; isSelling = false; icoEndTime = now; emit EndICO(saleState); return true; } // Activate token sale function function activate() external onlyOwner { inActive = false; } // Deacivate token sale function function deActivate() external onlyOwner { inActive = true; } // Enable transfer feature of tokens function enableTokenTransfer() external isActive onlyOwner { isTransferable = true; } // Modify wallet function changeWallet(address _newAddress) external onlyOwner { require(_newAddress != address(0)); require(walletAddress != _newAddress); walletAddress = _newAddress; } // Modify admin function changeAdminAddress(address _newAddress) external onlyOwner { require(_newAddress != address(0)); require(adminAddress != _newAddress); adminAddress = _newAddress; } // Modify founder address to receive founder tokens allocation function changeFounderAddress(address _newAddress) external onlyOwnerOrAdmin { require(_newAddress != address(0)); require(founderAddress != _newAddress); founderAddress = _newAddress; } // Modify team address to receive team tokens allocation function changeTeamAddress(address _newAddress) external onlyOwnerOrAdmin { require(_newAddress != address(0)); require(advisorAddress != _newAddress); advisorAddress = _newAddress; } // Allocate tokens for founder vested gradually for 4 year function allocateTokensForFounder() external isActive onlyOwnerOrAdmin { require(saleState == END_SALE); require(founderAddress != address(0)); uint256 amount; if (founderAllocatedTime == 1) { require(now >= icoEndTime + lockPeriod1); amount = founderAllocation * 50/100; balances[founderAddress] = balances[founderAddress].add(amount); emit AllocateTokensForFounder(founderAddress, founderAllocatedTime, amount); founderAllocatedTime = 2; return; } if (founderAllocatedTime == 2) { require(now >= icoEndTime + lockPeriod2); amount = founderAllocation * 50/100; balances[founderAddress] = balances[founderAddress].add(amount); emit AllocateTokensForFounder(founderAddress, founderAllocatedTime, amount); founderAllocatedTime = 3; return; } revert(); } // Allocate tokens for advisor and angel investors vested gradually for 1 year function allocateTokensForAdvisor() external isActive onlyOwnerOrAdmin { require(saleState == END_SALE); require(advisorAddress != address(0)); uint256 amount; if (founderAllocatedTime == 1) { amount = advisorAllocation * 50/100; balances[advisorAddress] = balances[advisorAddress].add(amount); emit AllocateTokensForFounder(advisorAddress, founderAllocatedTime, amount); founderAllocatedTime = 2; return; } if (advisorAllocatedTime == 2) { require(now >= icoEndTime + lockPeriod2); amount = advisorAllocation * 125/1000; balances[advisorAddress] = balances[advisorAddress].add(amount); emit AllocateTokensForAdvisor(advisorAddress, advisorAllocatedTime, amount); advisorAllocatedTime = 3; return; } if (advisorAllocatedTime == 3) { require(now >= icoEndTime + lockPeriod3); amount = advisorAllocation * 125/1000; balances[advisorAddress] = balances[advisorAddress].add(amount); emit AllocateTokensForAdvisor(advisorAddress, advisorAllocatedTime, amount); advisorAllocatedTime = 4; return; } if (advisorAllocatedTime == 4) { require(now >= icoEndTime + lockPeriod3); amount = advisorAllocation * 125/1000; balances[advisorAddress] = balances[advisorAddress].add(amount); emit AllocateTokensForAdvisor(advisorAddress, advisorAllocatedTime, amount); advisorAllocatedTime = 5; return; } if (advisorAllocatedTime == 5) { require(now >= icoEndTime + lockPeriod3); amount = advisorAllocation * 125/1000; balances[advisorAddress] = balances[advisorAddress].add(amount); emit AllocateTokensForAdvisor(advisorAddress, advisorAllocatedTime, amount); advisorAllocatedTime = 6; return; } revert(); } // Allocate reserved tokens function allocateReservedTokens(address _addr, uint _amount) external isActive onlyOwnerOrAdmin { require(saleState == END_SALE); require(_amount > 0); require(_addr != address(0)); balances[_addr] = balances[_addr].add(_amount); totalReservedTokenAllocation = totalReservedTokenAllocation.sub(_amount); emit AllocateReservedTokens(_addr, _amount); } <FILL_FUNCTION> // ERC20 standard function function allowance(address _owner, address _spender) external constant returns (uint256) { return allowed[_owner][_spender]; } // ERC20 standard function function balanceOf(address _owner) external constant returns (uint256 balance) { return balances[_owner]; } // Get softcap reaching status function isSoftCapReached() public view returns (bool) { return totalInvestedAmount >= minInvestedCap; } }
require(_amount > 0); require(_addr != address(0)); balances[_addr] = balances[_addr].add(_amount); totalRemainingTokensForSales = totalRemainingTokensForSales.sub(_amount); emit AllocateSalesTokens(_addr, _amount);
function allocateSalesTokens(address _addr, uint _amount) external isActive onlyOwnerOrAdmin
// Allocate sales tokens function allocateSalesTokens(address _addr, uint _amount) external isActive onlyOwnerOrAdmin
5928
HGSToken
null
contract HGSToken is PausableToken, MintableToken { string public constant name = "Hawthorn Guardian System"; string public constant symbol = "HGS"; uint8 public constant decimals = 18; uint256 public constant INITIAL_SUPPLY = 2000000000 * (10 ** uint256(decimals)); constructor() public {<FILL_FUNCTION_BODY> } }
contract HGSToken is PausableToken, MintableToken { string public constant name = "Hawthorn Guardian System"; string public constant symbol = "HGS"; uint8 public constant decimals = 18; uint256 public constant INITIAL_SUPPLY = 2000000000 * (10 ** uint256(decimals)); <FILL_FUNCTION> }
totalSupply_ = INITIAL_SUPPLY; originSupply_ = INITIAL_SUPPLY; balances[msg.sender] = INITIAL_SUPPLY; emit Transfer(address(0), msg.sender, INITIAL_SUPPLY);
constructor() public
constructor() public