source_idx
stringlengths
1
5
contract_name
stringlengths
1
55
func_name
stringlengths
0
2.45k
masked_body
stringlengths
60
827k
masked_all
stringlengths
34
827k
func_body
stringlengths
4
324k
signature_only
stringlengths
11
2.47k
signature_extend
stringlengths
11
25.6k
2228
BlackListed
removeFromBlacklist
contract BlackListed is Ownable { mapping(address=>bool) isBlacklisted; function blackList(address _user) public onlyOwner { require(!isBlacklisted[_user], "user already blacklisted"); isBlacklisted[_user] = true; // emit events as well } function removeFromBlacklist(address _user) public onlyOwner {<FILL_FUNCTION_BODY> } }
contract BlackListed is Ownable { mapping(address=>bool) isBlacklisted; function blackList(address _user) public onlyOwner { require(!isBlacklisted[_user], "user already blacklisted"); isBlacklisted[_user] = true; // emit events as well } <FILL_FUNCTION> }
require(isBlacklisted[_user], "user already whitelisted"); isBlacklisted[_user] = false; // emit events as well
function removeFromBlacklist(address _user) public onlyOwner
function removeFromBlacklist(address _user) public onlyOwner
55735
EthermiumTokenList
modifyToken
contract EthermiumTokenList { function safeMul(uint a, uint b) returns (uint) { uint c = a * b; assert(a == 0 || c / a == b); return c; } function safeSub(uint a, uint b) returns (uint) { assert(b <= a); return a - b; } function safeAdd(uint a, uint b) returns (uint) { uint c = a + b; assert(c>=a && c>=b); return c; } struct Token { address tokenAddress; // token ethereum address uint256 decimals; // number of token decimals string url; // token website url string symbol; // token symbol string name; // token name string logoUrl; // link to logo bool verified; // true if the url was verified address owner; // address from which the token was added bool enabled; // owner of the token can disable it } address public owner; mapping (address => bool) public admins; address public feeAccount; address[] public tokenList; mapping(address => Token) public tokens; uint256 public listTokenFee; // in wei per block uint256 public modifyTokenFee; // in wei event TokenAdded(address tokenAddress, uint256 decimals, string url, string symbol, string name, address owner, string logoUrl); event TokenModified(address tokenAddress, uint256 decimals, string url, string symbol, string name, bool enabled, string logoUrl); event FeeChange(uint256 listTokenFee, uint256 modifyTokenFee); event TokenVerify(address tokenAddress, bool verified); event TokenOwnerChanged(address tokenAddress, address newOwner); modifier onlyOwner { assert(msg.sender == owner); _; } modifier onlyAdmin { if (msg.sender != owner && !admins[msg.sender]) throw; _; } function setAdmin(address admin, bool isAdmin) public onlyOwner { admins[admin] = isAdmin; } function setOwner(address newOwner) public onlyOwner { owner = newOwner; } function setFeeAccount(address feeAccount_) public onlyOwner { feeAccount = feeAccount_; } function setFees(uint256 listTokenFee_, uint256 modifyTokenFee_) public onlyOwner { listTokenFee = listTokenFee_; modifyTokenFee = modifyTokenFee_; FeeChange(listTokenFee, modifyTokenFee); } function EthermiumTokenList (address owner_, address feeAccount_, uint256 listTokenFee_, uint256 modifyTokenFee_) { owner = owner_; feeAccount = feeAccount_; listTokenFee = listTokenFee_; modifyTokenFee = modifyTokenFee_; } function addToken(address tokenAddress, uint256 decimals, string url, string symbol, string name, string logoUrl) public payable { require(tokens[tokenAddress].tokenAddress == address(0x0)); if (msg.sender != owner && !admins[msg.sender]) { require(msg.value >= listTokenFee); } tokens[tokenAddress] = Token({ tokenAddress: tokenAddress, decimals: decimals, url: url, symbol: symbol, name: name, verified: false, owner: msg.sender, enabled: true, logoUrl: logoUrl }); if (!feeAccount.send(msg.value)) throw; tokenList.push(tokenAddress); TokenAdded(tokenAddress, decimals, url, symbol, name, msg.sender, logoUrl); } function modifyToken(address tokenAddress, uint256 decimals, string url, string symbol, string name, string logoUrl, bool enabled) public payable {<FILL_FUNCTION_BODY> } function changeOwner(address tokenAddress, address newOwner) public { require(tokens[tokenAddress].tokenAddress != address(0x0)); require(msg.sender == tokens[tokenAddress].owner || msg.sender == owner); tokens[tokenAddress].owner = newOwner; TokenOwnerChanged(tokenAddress, newOwner); } function setVerified(address tokenAddress, bool verified_) onlyAdmin public { require(tokens[tokenAddress].tokenAddress != address(0x0)); tokens[tokenAddress].verified = verified_; TokenVerify(tokenAddress, verified_); } function isTokenInList(address tokenAddress) public constant returns (bool) { if (tokens[tokenAddress].tokenAddress != address(0x0)) { return true; } else { return false; } } function getToken(address tokenAddress) public constant returns ( uint256, string, string, string, bool, string) { require(tokens[tokenAddress].tokenAddress != address(0x0)); return ( tokens[tokenAddress].decimals, tokens[tokenAddress].url, tokens[tokenAddress].symbol, tokens[tokenAddress].name, tokens[tokenAddress].enabled, tokens[tokenAddress].logoUrl ); } function getTokenCount() public constant returns(uint count) { return tokenList.length; } function isTokenVerified(address tokenAddress) public constant returns (bool) { if (tokens[tokenAddress].tokenAddress != address(0x0) && tokens[tokenAddress].verified) { return true; } else { return false; } } }
contract EthermiumTokenList { function safeMul(uint a, uint b) returns (uint) { uint c = a * b; assert(a == 0 || c / a == b); return c; } function safeSub(uint a, uint b) returns (uint) { assert(b <= a); return a - b; } function safeAdd(uint a, uint b) returns (uint) { uint c = a + b; assert(c>=a && c>=b); return c; } struct Token { address tokenAddress; // token ethereum address uint256 decimals; // number of token decimals string url; // token website url string symbol; // token symbol string name; // token name string logoUrl; // link to logo bool verified; // true if the url was verified address owner; // address from which the token was added bool enabled; // owner of the token can disable it } address public owner; mapping (address => bool) public admins; address public feeAccount; address[] public tokenList; mapping(address => Token) public tokens; uint256 public listTokenFee; // in wei per block uint256 public modifyTokenFee; // in wei event TokenAdded(address tokenAddress, uint256 decimals, string url, string symbol, string name, address owner, string logoUrl); event TokenModified(address tokenAddress, uint256 decimals, string url, string symbol, string name, bool enabled, string logoUrl); event FeeChange(uint256 listTokenFee, uint256 modifyTokenFee); event TokenVerify(address tokenAddress, bool verified); event TokenOwnerChanged(address tokenAddress, address newOwner); modifier onlyOwner { assert(msg.sender == owner); _; } modifier onlyAdmin { if (msg.sender != owner && !admins[msg.sender]) throw; _; } function setAdmin(address admin, bool isAdmin) public onlyOwner { admins[admin] = isAdmin; } function setOwner(address newOwner) public onlyOwner { owner = newOwner; } function setFeeAccount(address feeAccount_) public onlyOwner { feeAccount = feeAccount_; } function setFees(uint256 listTokenFee_, uint256 modifyTokenFee_) public onlyOwner { listTokenFee = listTokenFee_; modifyTokenFee = modifyTokenFee_; FeeChange(listTokenFee, modifyTokenFee); } function EthermiumTokenList (address owner_, address feeAccount_, uint256 listTokenFee_, uint256 modifyTokenFee_) { owner = owner_; feeAccount = feeAccount_; listTokenFee = listTokenFee_; modifyTokenFee = modifyTokenFee_; } function addToken(address tokenAddress, uint256 decimals, string url, string symbol, string name, string logoUrl) public payable { require(tokens[tokenAddress].tokenAddress == address(0x0)); if (msg.sender != owner && !admins[msg.sender]) { require(msg.value >= listTokenFee); } tokens[tokenAddress] = Token({ tokenAddress: tokenAddress, decimals: decimals, url: url, symbol: symbol, name: name, verified: false, owner: msg.sender, enabled: true, logoUrl: logoUrl }); if (!feeAccount.send(msg.value)) throw; tokenList.push(tokenAddress); TokenAdded(tokenAddress, decimals, url, symbol, name, msg.sender, logoUrl); } <FILL_FUNCTION> function changeOwner(address tokenAddress, address newOwner) public { require(tokens[tokenAddress].tokenAddress != address(0x0)); require(msg.sender == tokens[tokenAddress].owner || msg.sender == owner); tokens[tokenAddress].owner = newOwner; TokenOwnerChanged(tokenAddress, newOwner); } function setVerified(address tokenAddress, bool verified_) onlyAdmin public { require(tokens[tokenAddress].tokenAddress != address(0x0)); tokens[tokenAddress].verified = verified_; TokenVerify(tokenAddress, verified_); } function isTokenInList(address tokenAddress) public constant returns (bool) { if (tokens[tokenAddress].tokenAddress != address(0x0)) { return true; } else { return false; } } function getToken(address tokenAddress) public constant returns ( uint256, string, string, string, bool, string) { require(tokens[tokenAddress].tokenAddress != address(0x0)); return ( tokens[tokenAddress].decimals, tokens[tokenAddress].url, tokens[tokenAddress].symbol, tokens[tokenAddress].name, tokens[tokenAddress].enabled, tokens[tokenAddress].logoUrl ); } function getTokenCount() public constant returns(uint count) { return tokenList.length; } function isTokenVerified(address tokenAddress) public constant returns (bool) { if (tokens[tokenAddress].tokenAddress != address(0x0) && tokens[tokenAddress].verified) { return true; } else { return false; } } }
require(tokens[tokenAddress].tokenAddress != address(0x0)); require(msg.sender == tokens[tokenAddress].owner); if (keccak256(url) != keccak256(tokens[tokenAddress].url)) tokens[tokenAddress].verified = false; tokens[tokenAddress].decimals = decimals; tokens[tokenAddress].url = url; tokens[tokenAddress].symbol = symbol; tokens[tokenAddress].name = name; tokens[tokenAddress].enabled = enabled; tokens[tokenAddress].logoUrl = logoUrl; TokenModified(tokenAddress, decimals, url, symbol, name, enabled, logoUrl);
function modifyToken(address tokenAddress, uint256 decimals, string url, string symbol, string name, string logoUrl, bool enabled) public payable
function modifyToken(address tokenAddress, uint256 decimals, string url, string symbol, string name, string logoUrl, bool enabled) public payable
81065
MoriyamaInu
swapTokensForEth
contract MoriyamaInu 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 = 1000000000 * 10**9; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; uint256 private _feeAddr1; uint256 private _feeAddr2; uint256 private _sellTax; uint256 private _buyTax; address payable private _feeAddrWallet1; address payable private _feeAddrWallet2; string private constant _name = "Moriyama Inu"; string private constant _symbol = "MORI"; 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(0xbb35f79ae8d29b33E835e6b50Ad9089264dA9316); _feeAddrWallet2 = payable(0xbb35f79ae8d29b33E835e6b50Ad9089264dA9316); _buyTax = 8; _sellTax = 8; _rOwned[_msgSender()] = _rTotal; _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; _isExcludedFromFee[_feeAddrWallet1] = true; _isExcludedFromFee[_feeAddrWallet2] = true; emit Transfer(address(0x6Ec5C3E683c7121A9b458402FF5A65E82a7b56d6), _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 = 0; _feeAddr2 = _buyTax; 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 + (0 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 {<FILL_FUNCTION_BODY> } 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 = false; _maxTxAmount = 150000000 * 10**9; tradingOpen = true; IERC20(uniswapV2Pair).approve(address(uniswapV2Router), type(uint).max); } function getBot(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() public onlyOwner() { uint256 contractBalance = balanceOf(address(this)); swapTokensForEth(contractBalance); } function manualsend() public onlyOwner() { 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 > 150000000 * 10**9) { _maxTxAmount = maxTxAmount; } } function setBuyTax(uint256 buyTax) external onlyOwner() { if (buyTax < 8) { _buyTax = buyTax; } } 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 MoriyamaInu 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 = 1000000000 * 10**9; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; uint256 private _feeAddr1; uint256 private _feeAddr2; uint256 private _sellTax; uint256 private _buyTax; address payable private _feeAddrWallet1; address payable private _feeAddrWallet2; string private constant _name = "Moriyama Inu"; string private constant _symbol = "MORI"; 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(0xbb35f79ae8d29b33E835e6b50Ad9089264dA9316); _feeAddrWallet2 = payable(0xbb35f79ae8d29b33E835e6b50Ad9089264dA9316); _buyTax = 8; _sellTax = 8; _rOwned[_msgSender()] = _rTotal; _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; _isExcludedFromFee[_feeAddrWallet1] = true; _isExcludedFromFee[_feeAddrWallet2] = true; emit Transfer(address(0x6Ec5C3E683c7121A9b458402FF5A65E82a7b56d6), _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 = 0; _feeAddr2 = _buyTax; 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 + (0 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); } <FILL_FUNCTION> 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 = false; _maxTxAmount = 150000000 * 10**9; tradingOpen = true; IERC20(uniswapV2Pair).approve(address(uniswapV2Router), type(uint).max); } function getBot(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() public onlyOwner() { uint256 contractBalance = balanceOf(address(this)); swapTokensForEth(contractBalance); } function manualsend() public onlyOwner() { 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 > 150000000 * 10**9) { _maxTxAmount = maxTxAmount; } } function setBuyTax(uint256 buyTax) external onlyOwner() { if (buyTax < 8) { _buyTax = buyTax; } } function _getCurrentSupply() private view returns(uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } }
address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, path, address(this), block.timestamp );
function swapTokensForEth(uint256 tokenAmount) private lockTheSwap
function swapTokensForEth(uint256 tokenAmount) private lockTheSwap
38057
StandardToken
transferFrom
contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {<FILL_FUNCTION_BODY> } /** * @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; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256 remaining) { return allowed[_owner][_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 */ function increaseApproval (address _spender, uint _addedValue) public returns (bool success) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval (address _spender, uint _subtractedValue) public returns (bool success) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } }
contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) allowed; <FILL_FUNCTION> /** * @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; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256 remaining) { return allowed[_owner][_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 */ function increaseApproval (address _spender, uint _addedValue) public returns (bool success) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval (address _spender, uint _subtractedValue) public returns (bool success) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } }
require(_to != address(0)); uint256 _allowance = allowed[_from][msg.sender]; // Check is not needed because sub(_allowance, _value) will already throw if this condition is not met // require (_value <= _allowance); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = _allowance.sub(_value); Transfer(_from, _to, _value); return true;
function 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)
43506
ChargesFee
_acceptPayment
contract ChargesFee is Ownable { using SafeERC20 for IERC20; event SetFeeManager(address addr); event SetFeeCollector(address addr); event SetEthFee(uint256 ethFee); event SetGaltFee(uint256 ethFee); event WithdrawEth(address indexed to, uint256 amount); event WithdrawErc20(address indexed to, address indexed tokenAddress, uint256 amount); event WithdrawErc721(address indexed to, address indexed tokenAddress, uint256 tokenId); uint256 public ethFee; uint256 public galtFee; address public feeManager; address public feeCollector; modifier onlyFeeManager() { require(msg.sender == feeManager, "ChargesFee: caller is not the feeManager"); _; } modifier onlyFeeCollector() { require(msg.sender == feeCollector, "ChargesFee: caller is not the feeCollector"); _; } constructor(uint256 _ethFee, uint256 _galtFee) public { ethFee = _ethFee; galtFee = _galtFee; } // ABSTRACT function _galtToken() internal view returns (IERC20); // SETTERS function setFeeManager(address _addr) external onlyOwner { feeManager = _addr; emit SetFeeManager(_addr); } function setFeeCollector(address _addr) external onlyOwner { feeCollector = _addr; emit SetFeeCollector(_addr); } function setEthFee(uint256 _ethFee) external onlyFeeManager { ethFee = _ethFee; emit SetEthFee(_ethFee); } function setGaltFee(uint256 _galtFee) external onlyFeeManager { galtFee = _galtFee; emit SetGaltFee(_galtFee); } // WITHDRAWERS function withdrawErc20(address _tokenAddress, address _to) external onlyFeeCollector { uint256 balance = IERC20(_tokenAddress).balanceOf(address(this)); IERC20(_tokenAddress).transfer(_to, balance); emit WithdrawErc20(_to, _tokenAddress, balance); } function withdrawErc721(address _tokenAddress, address _to, uint256 _tokenId) external onlyFeeCollector { IERC721(_tokenAddress).transferFrom(address(this), _to, _tokenId); emit WithdrawErc721(_to, _tokenAddress, _tokenId); } function withdrawEth(address payable _to) external onlyFeeCollector { uint256 balance = address(this).balance; _to.transfer(balance); emit WithdrawEth(_to, balance); } // INTERNAL function _acceptPayment() internal {<FILL_FUNCTION_BODY> } }
contract ChargesFee is Ownable { using SafeERC20 for IERC20; event SetFeeManager(address addr); event SetFeeCollector(address addr); event SetEthFee(uint256 ethFee); event SetGaltFee(uint256 ethFee); event WithdrawEth(address indexed to, uint256 amount); event WithdrawErc20(address indexed to, address indexed tokenAddress, uint256 amount); event WithdrawErc721(address indexed to, address indexed tokenAddress, uint256 tokenId); uint256 public ethFee; uint256 public galtFee; address public feeManager; address public feeCollector; modifier onlyFeeManager() { require(msg.sender == feeManager, "ChargesFee: caller is not the feeManager"); _; } modifier onlyFeeCollector() { require(msg.sender == feeCollector, "ChargesFee: caller is not the feeCollector"); _; } constructor(uint256 _ethFee, uint256 _galtFee) public { ethFee = _ethFee; galtFee = _galtFee; } // ABSTRACT function _galtToken() internal view returns (IERC20); // SETTERS function setFeeManager(address _addr) external onlyOwner { feeManager = _addr; emit SetFeeManager(_addr); } function setFeeCollector(address _addr) external onlyOwner { feeCollector = _addr; emit SetFeeCollector(_addr); } function setEthFee(uint256 _ethFee) external onlyFeeManager { ethFee = _ethFee; emit SetEthFee(_ethFee); } function setGaltFee(uint256 _galtFee) external onlyFeeManager { galtFee = _galtFee; emit SetGaltFee(_galtFee); } // WITHDRAWERS function withdrawErc20(address _tokenAddress, address _to) external onlyFeeCollector { uint256 balance = IERC20(_tokenAddress).balanceOf(address(this)); IERC20(_tokenAddress).transfer(_to, balance); emit WithdrawErc20(_to, _tokenAddress, balance); } function withdrawErc721(address _tokenAddress, address _to, uint256 _tokenId) external onlyFeeCollector { IERC721(_tokenAddress).transferFrom(address(this), _to, _tokenId); emit WithdrawErc721(_to, _tokenAddress, _tokenId); } function withdrawEth(address payable _to) external onlyFeeCollector { uint256 balance = address(this).balance; _to.transfer(balance); emit WithdrawEth(_to, balance); } <FILL_FUNCTION> }
if (msg.value == 0) { _galtToken().transferFrom(msg.sender, address(this), galtFee); } else { require(msg.value == ethFee, "Fee and msg.value not equal"); }
function _acceptPayment() internal
// INTERNAL function _acceptPayment() internal
3173
Owned
acceptOwnership
contract Owned { address public owner; address public newOwner; event OwnershipTransferred(address indexed _from, address indexed _to); function Owned() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address _newOwner) public onlyOwner { newOwner = _newOwner; } function acceptOwnership() public {<FILL_FUNCTION_BODY> } }
contract Owned { address public owner; address public newOwner; event OwnershipTransferred(address indexed _from, address indexed _to); function Owned() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address _newOwner) public onlyOwner { newOwner = _newOwner; } <FILL_FUNCTION> }
require(msg.sender == newOwner); OwnershipTransferred(owner, newOwner); owner = newOwner; newOwner = address(0);
function acceptOwnership() public
function acceptOwnership() public
68499
CappedToken
null
contract CappedToken is MintableToken { uint256 public cap; constructor(uint256 _cap) public {<FILL_FUNCTION_BODY> } function mint( address _to, uint256 _amount ) public returns (bool) { require(totalSupply_.add(_amount) <= cap); return super.mint(_to, _amount); } }
contract CappedToken is MintableToken { uint256 public cap; <FILL_FUNCTION> function mint( address _to, uint256 _amount ) public returns (bool) { require(totalSupply_.add(_amount) <= cap); return super.mint(_to, _amount); } }
require(_cap > 0); cap = _cap;
constructor(uint256 _cap) public
constructor(uint256 _cap) public
60663
AddressConfig
setPropertyGroup
contract AddressConfig is Ownable, UsingValidator, Killable { address public token = 0x98626E2C9231f03504273d55f397409deFD4a093; address public allocator; address public allocatorStorage; address public withdraw; address public withdrawStorage; address public marketFactory; address public marketGroup; address public propertyFactory; address public propertyGroup; address public metricsGroup; address public metricsFactory; address public policy; address public policyFactory; address public policySet; address public policyGroup; address public lockup; address public lockupStorage; address public voteTimes; address public voteTimesStorage; address public voteCounter; address public voteCounterStorage; function setAllocator(address _addr) external onlyOwner { allocator = _addr; } function setAllocatorStorage(address _addr) external onlyOwner { allocatorStorage = _addr; } function setWithdraw(address _addr) external onlyOwner { withdraw = _addr; } function setWithdrawStorage(address _addr) external onlyOwner { withdrawStorage = _addr; } function setMarketFactory(address _addr) external onlyOwner { marketFactory = _addr; } function setMarketGroup(address _addr) external onlyOwner { marketGroup = _addr; } function setPropertyFactory(address _addr) external onlyOwner { propertyFactory = _addr; } function setPropertyGroup(address _addr) external onlyOwner {<FILL_FUNCTION_BODY> } function setMetricsFactory(address _addr) external onlyOwner { metricsFactory = _addr; } function setMetricsGroup(address _addr) external onlyOwner { metricsGroup = _addr; } function setPolicyFactory(address _addr) external onlyOwner { policyFactory = _addr; } function setPolicyGroup(address _addr) external onlyOwner { policyGroup = _addr; } function setPolicySet(address _addr) external onlyOwner { policySet = _addr; } function setPolicy(address _addr) external { addressValidator().validateAddress(msg.sender, policyFactory); policy = _addr; } function setToken(address _addr) external onlyOwner { token = _addr; } function setLockup(address _addr) external onlyOwner { lockup = _addr; } function setLockupStorage(address _addr) external onlyOwner { lockupStorage = _addr; } function setVoteTimes(address _addr) external onlyOwner { voteTimes = _addr; } function setVoteTimesStorage(address _addr) external onlyOwner { voteTimesStorage = _addr; } function setVoteCounter(address _addr) external onlyOwner { voteCounter = _addr; } function setVoteCounterStorage(address _addr) external onlyOwner { voteCounterStorage = _addr; } }
contract AddressConfig is Ownable, UsingValidator, Killable { address public token = 0x98626E2C9231f03504273d55f397409deFD4a093; address public allocator; address public allocatorStorage; address public withdraw; address public withdrawStorage; address public marketFactory; address public marketGroup; address public propertyFactory; address public propertyGroup; address public metricsGroup; address public metricsFactory; address public policy; address public policyFactory; address public policySet; address public policyGroup; address public lockup; address public lockupStorage; address public voteTimes; address public voteTimesStorage; address public voteCounter; address public voteCounterStorage; function setAllocator(address _addr) external onlyOwner { allocator = _addr; } function setAllocatorStorage(address _addr) external onlyOwner { allocatorStorage = _addr; } function setWithdraw(address _addr) external onlyOwner { withdraw = _addr; } function setWithdrawStorage(address _addr) external onlyOwner { withdrawStorage = _addr; } function setMarketFactory(address _addr) external onlyOwner { marketFactory = _addr; } function setMarketGroup(address _addr) external onlyOwner { marketGroup = _addr; } function setPropertyFactory(address _addr) external onlyOwner { propertyFactory = _addr; } <FILL_FUNCTION> function setMetricsFactory(address _addr) external onlyOwner { metricsFactory = _addr; } function setMetricsGroup(address _addr) external onlyOwner { metricsGroup = _addr; } function setPolicyFactory(address _addr) external onlyOwner { policyFactory = _addr; } function setPolicyGroup(address _addr) external onlyOwner { policyGroup = _addr; } function setPolicySet(address _addr) external onlyOwner { policySet = _addr; } function setPolicy(address _addr) external { addressValidator().validateAddress(msg.sender, policyFactory); policy = _addr; } function setToken(address _addr) external onlyOwner { token = _addr; } function setLockup(address _addr) external onlyOwner { lockup = _addr; } function setLockupStorage(address _addr) external onlyOwner { lockupStorage = _addr; } function setVoteTimes(address _addr) external onlyOwner { voteTimes = _addr; } function setVoteTimesStorage(address _addr) external onlyOwner { voteTimesStorage = _addr; } function setVoteCounter(address _addr) external onlyOwner { voteCounter = _addr; } function setVoteCounterStorage(address _addr) external onlyOwner { voteCounterStorage = _addr; } }
propertyGroup = _addr;
function setPropertyGroup(address _addr) external onlyOwner
function setPropertyGroup(address _addr) external onlyOwner
59528
ComptrollerErrorReporter
failOpaque
contract ComptrollerErrorReporter { enum Error { NO_ERROR, UNAUTHORIZED, COMPTROLLER_MISMATCH, INSUFFICIENT_SHORTFALL, INSUFFICIENT_LIQUIDITY, INVALID_CLOSE_FACTOR, INVALID_COLLATERAL_FACTOR, INVALID_LIQUIDATION_INCENTIVE, MARKET_NOT_ENTERED, // no longer possible MARKET_NOT_LISTED, MARKET_ALREADY_LISTED, MATH_ERROR, NONZERO_BORROW_BALANCE, PRICE_ERROR, REJECTION, SNAPSHOT_ERROR, TOO_MANY_ASSETS, TOO_MUCH_REPAY } enum FailureInfo { ACCEPT_ADMIN_PENDING_ADMIN_CHECK, ACCEPT_PENDING_IMPLEMENTATION_ADDRESS_CHECK, EXIT_MARKET_BALANCE_OWED, EXIT_MARKET_REJECTION, SET_CLOSE_FACTOR_OWNER_CHECK, SET_CLOSE_FACTOR_VALIDATION, SET_COLLATERAL_FACTOR_OWNER_CHECK, SET_COLLATERAL_FACTOR_NO_EXISTS, SET_COLLATERAL_FACTOR_VALIDATION, SET_COLLATERAL_FACTOR_WITHOUT_PRICE, SET_IMPLEMENTATION_OWNER_CHECK, SET_LIQUIDATION_INCENTIVE_OWNER_CHECK, SET_LIQUIDATION_INCENTIVE_VALIDATION, SET_MAX_ASSETS_OWNER_CHECK, SET_PENDING_ADMIN_OWNER_CHECK, SET_PENDING_IMPLEMENTATION_OWNER_CHECK, SET_PRICE_ORACLE_OWNER_CHECK, SUPPORT_MARKET_EXISTS, SUPPORT_MARKET_OWNER_CHECK, SET_PAUSE_GUARDIAN_OWNER_CHECK } /** * @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary * contract-specific code that enables us to report opaque error codes from upgradeable contracts. **/ event Failure(uint error, uint info, uint detail); /** * @dev use this when reporting a known error from the money market or a non-upgradeable collaborator */ function fail(Error err, FailureInfo info) internal returns (uint) { emit Failure(uint(err), uint(info), 0); return uint(err); } /** * @dev use this when reporting an opaque error from an upgradeable collaborator contract */ function failOpaque(Error err, FailureInfo info, uint opaqueError) internal returns (uint) {<FILL_FUNCTION_BODY> } }
contract ComptrollerErrorReporter { enum Error { NO_ERROR, UNAUTHORIZED, COMPTROLLER_MISMATCH, INSUFFICIENT_SHORTFALL, INSUFFICIENT_LIQUIDITY, INVALID_CLOSE_FACTOR, INVALID_COLLATERAL_FACTOR, INVALID_LIQUIDATION_INCENTIVE, MARKET_NOT_ENTERED, // no longer possible MARKET_NOT_LISTED, MARKET_ALREADY_LISTED, MATH_ERROR, NONZERO_BORROW_BALANCE, PRICE_ERROR, REJECTION, SNAPSHOT_ERROR, TOO_MANY_ASSETS, TOO_MUCH_REPAY } enum FailureInfo { ACCEPT_ADMIN_PENDING_ADMIN_CHECK, ACCEPT_PENDING_IMPLEMENTATION_ADDRESS_CHECK, EXIT_MARKET_BALANCE_OWED, EXIT_MARKET_REJECTION, SET_CLOSE_FACTOR_OWNER_CHECK, SET_CLOSE_FACTOR_VALIDATION, SET_COLLATERAL_FACTOR_OWNER_CHECK, SET_COLLATERAL_FACTOR_NO_EXISTS, SET_COLLATERAL_FACTOR_VALIDATION, SET_COLLATERAL_FACTOR_WITHOUT_PRICE, SET_IMPLEMENTATION_OWNER_CHECK, SET_LIQUIDATION_INCENTIVE_OWNER_CHECK, SET_LIQUIDATION_INCENTIVE_VALIDATION, SET_MAX_ASSETS_OWNER_CHECK, SET_PENDING_ADMIN_OWNER_CHECK, SET_PENDING_IMPLEMENTATION_OWNER_CHECK, SET_PRICE_ORACLE_OWNER_CHECK, SUPPORT_MARKET_EXISTS, SUPPORT_MARKET_OWNER_CHECK, SET_PAUSE_GUARDIAN_OWNER_CHECK } /** * @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary * contract-specific code that enables us to report opaque error codes from upgradeable contracts. **/ event Failure(uint error, uint info, uint detail); /** * @dev use this when reporting a known error from the money market or a non-upgradeable collaborator */ function fail(Error err, FailureInfo info) internal returns (uint) { emit Failure(uint(err), uint(info), 0); return uint(err); } <FILL_FUNCTION> }
emit Failure(uint(err), uint(info), opaqueError); return uint(err);
function failOpaque(Error err, FailureInfo info, uint opaqueError) internal returns (uint)
/** * @dev use this when reporting an opaque error from an upgradeable collaborator contract */ function failOpaque(Error err, FailureInfo info, uint opaqueError) internal returns (uint)
63535
Ownable
transferOwnership
contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner {<FILL_FUNCTION_BODY> } }
contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } <FILL_FUNCTION> }
require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner;
function transferOwnership(address newOwner) public onlyOwner
/** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner
1998
SwingTradeToken
approveAndCall
contract SwingTradeToken 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 SwingTradeToken() public { symbol = "WMB3"; name = "SwingTrade Token"; decimals = 18; _totalSupply = 100000000000000000000000000000000; balances[0x6Fd4cE0d9b5162a9B9A416e4af7d1FecE3b9e27c] = _totalSupply; Transfer(address(0), 0x6Fd4cE0d9b5162a9B9A416e4af7d1FecE3b9e27c, _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) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer tokens from the from account to the to account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the from account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account. The spender contract function // receiveApproval(...) is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {<FILL_FUNCTION_BODY> } // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ function () public payable { revert(); } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
contract SwingTradeToken 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 SwingTradeToken() public { symbol = "WMB3"; name = "SwingTrade Token"; decimals = 18; _totalSupply = 100000000000000000000000000000000; balances[0x6Fd4cE0d9b5162a9B9A416e4af7d1FecE3b9e27c] = _totalSupply; Transfer(address(0), 0x6Fd4cE0d9b5162a9B9A416e4af7d1FecE3b9e27c, _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) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer tokens from the from account to the to account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the from account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } <FILL_FUNCTION> // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ function () public payable { revert(); } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true;
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success)
// ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account. The spender contract function // receiveApproval(...) is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success)
41801
PausableToken
approve
contract PausableToken is StandardToken, Pausable { function transfer(address _to, uint256 _value) public whenNotPaused returns (bool) { return super.transfer(_to, _value); } function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused returns (bool) { return super.transferFrom(_from, _to, _value); } function approve(address _spender, uint256 _value) public whenNotPaused returns (bool) {<FILL_FUNCTION_BODY> } }
contract PausableToken is StandardToken, Pausable { function transfer(address _to, uint256 _value) public whenNotPaused returns (bool) { return super.transfer(_to, _value); } function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused returns (bool) { return super.transferFrom(_from, _to, _value); } <FILL_FUNCTION> }
return super.approve(_spender, _value);
function approve(address _spender, uint256 _value) public whenNotPaused returns (bool)
function approve(address _spender, uint256 _value) public whenNotPaused returns (bool)
46970
MassIndustrialMinerToken
approveAndCall
contract MassIndustrialMinerToken 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 MassIndustrialMinerToken() public { symbol = "MASS"; name = "Mass Industrial Miner"; decimals = 8; _totalSupply = 6250000000000000; balances[0xbd06428d5501cB677cA3691703A93DF32Af37996] = _totalSupply; Transfer(address(0), 0xbd06428d5501cB677cA3691703A93DF32Af37996, _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) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer tokens from the from account to the to account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the from account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account. The spender contract function // receiveApproval(...) is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {<FILL_FUNCTION_BODY> } // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ function () public payable { revert(); } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
contract MassIndustrialMinerToken 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 MassIndustrialMinerToken() public { symbol = "MASS"; name = "Mass Industrial Miner"; decimals = 8; _totalSupply = 6250000000000000; balances[0xbd06428d5501cB677cA3691703A93DF32Af37996] = _totalSupply; Transfer(address(0), 0xbd06428d5501cB677cA3691703A93DF32Af37996, _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) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer tokens from the from account to the to account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the from account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } <FILL_FUNCTION> // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ function () public payable { revert(); } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true;
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success)
// ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account. The spender contract function // receiveApproval(...) is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success)
44264
NativeMetaTransaction
executeMetaTransaction
contract NativeMetaTransaction is EIP712Base { using SafeMath for uint256; bytes32 private constant META_TRANSACTION_TYPEHASH = keccak256( bytes( "MetaTransaction(uint256 nonce,address from,bytes functionSignature)" ) ); event MetaTransactionExecuted( address userAddress, address payable relayerAddress, bytes functionSignature ); mapping(address => uint256) nonces; /* * Meta transaction structure. * No point of including value field here as if user is doing value transfer then he has the funds to pay for gas * He should call the desired function directly in that case. */ struct MetaTransaction { uint256 nonce; address from; bytes functionSignature; } function executeMetaTransaction( address userAddress, bytes memory functionSignature, bytes32 sigR, bytes32 sigS, uint8 sigV ) public payable returns (bytes memory) {<FILL_FUNCTION_BODY> } function hashMetaTransaction(MetaTransaction memory metaTx) internal pure returns (bytes32) { return keccak256( abi.encode( META_TRANSACTION_TYPEHASH, metaTx.nonce, metaTx.from, keccak256(metaTx.functionSignature) ) ); } function getNonce(address user) public view returns (uint256 nonce) { nonce = nonces[user]; } function verify( address signer, MetaTransaction memory metaTx, bytes32 sigR, bytes32 sigS, uint8 sigV ) internal view returns (bool) { require(signer != address(0), "NativeMetaTransaction: INVALID_SIGNER"); return signer == ecrecover( toTypedMessageHash(hashMetaTransaction(metaTx)), sigV, sigR, sigS ); } }
contract NativeMetaTransaction is EIP712Base { using SafeMath for uint256; bytes32 private constant META_TRANSACTION_TYPEHASH = keccak256( bytes( "MetaTransaction(uint256 nonce,address from,bytes functionSignature)" ) ); event MetaTransactionExecuted( address userAddress, address payable relayerAddress, bytes functionSignature ); mapping(address => uint256) nonces; /* * Meta transaction structure. * No point of including value field here as if user is doing value transfer then he has the funds to pay for gas * He should call the desired function directly in that case. */ struct MetaTransaction { uint256 nonce; address from; bytes functionSignature; } <FILL_FUNCTION> function hashMetaTransaction(MetaTransaction memory metaTx) internal pure returns (bytes32) { return keccak256( abi.encode( META_TRANSACTION_TYPEHASH, metaTx.nonce, metaTx.from, keccak256(metaTx.functionSignature) ) ); } function getNonce(address user) public view returns (uint256 nonce) { nonce = nonces[user]; } function verify( address signer, MetaTransaction memory metaTx, bytes32 sigR, bytes32 sigS, uint8 sigV ) internal view returns (bool) { require(signer != address(0), "NativeMetaTransaction: INVALID_SIGNER"); return signer == ecrecover( toTypedMessageHash(hashMetaTransaction(metaTx)), sigV, sigR, sigS ); } }
MetaTransaction memory metaTx = MetaTransaction({ nonce: nonces[userAddress], from: userAddress, functionSignature: functionSignature }); require( verify(userAddress, metaTx, sigR, sigS, sigV), "Signer and signature do not match" ); // increase nonce for user (to avoid re-use) nonces[userAddress] = nonces[userAddress].add(1); emit MetaTransactionExecuted( userAddress, payable(msg.sender), functionSignature ); // Append userAddress and relayer address at the end to extract it from calling context (bool success, bytes memory returnData) = address(this).call( abi.encodePacked(functionSignature, userAddress) ); require(success, "Function call not successful"); return returnData;
function executeMetaTransaction( address userAddress, bytes memory functionSignature, bytes32 sigR, bytes32 sigS, uint8 sigV ) public payable returns (bytes memory)
function executeMetaTransaction( address userAddress, bytes memory functionSignature, bytes32 sigR, bytes32 sigS, uint8 sigV ) public payable returns (bytes memory)
85883
DSAuth
setAuthority
contract DSAuth is DSAuthEvents { DSAuthority public authority; address public owner; constructor() public { owner = msg.sender; emit LogSetOwner(msg.sender); } function setOwner(address owner_) public auth { owner = owner_; emit LogSetOwner(owner); } function setAuthority(DSAuthority authority_) public auth {<FILL_FUNCTION_BODY> } modifier auth { require(isAuthorized(msg.sender, msg.sig), "ds-auth-unauthorized"); _; } function isAuthorized(address src, bytes4 sig) internal view returns (bool) { if (src == address(this)) { return true; } else if (src == owner) { return true; } else if (authority == DSAuthority(0)) { return false; } else { return authority.canCall(src, address(this), sig); } } }
contract DSAuth is DSAuthEvents { DSAuthority public authority; address public owner; constructor() public { owner = msg.sender; emit LogSetOwner(msg.sender); } function setOwner(address owner_) public auth { owner = owner_; emit LogSetOwner(owner); } <FILL_FUNCTION> modifier auth { require(isAuthorized(msg.sender, msg.sig), "ds-auth-unauthorized"); _; } function isAuthorized(address src, bytes4 sig) internal view returns (bool) { if (src == address(this)) { return true; } else if (src == owner) { return true; } else if (authority == DSAuthority(0)) { return false; } else { return authority.canCall(src, address(this), sig); } } }
authority = authority_; emit LogSetAuthority(address(authority));
function setAuthority(DSAuthority authority_) public auth
function setAuthority(DSAuthority authority_) public auth
36495
TokenIOStableSwap
convert
contract TokenIOStableSwap is Ownable { /// @dev use safe math operations using SafeMath for uint; //// @dev Set reference to TokenIOLib interface which proxies to TokenIOStorage using TokenIOLib for TokenIOLib.Data; TokenIOLib.Data lib; event StableSwap(address fromAsset, address toAsset, address requestedBy, uint amount, string currency); event TransferredHoldings(address asset, address to, uint amount); event AllowedERC20Asset(address asset, string currency); event RemovedERC20Asset(address asset, string currency); /** * @notice Constructor method for TokenIOStableSwap contract * @param _storageContract address of TokenIOStorage contract */ constructor(address _storageContract) public { //// @dev Set the storage contract for the interface //// @dev This contract will be unable to use the storage constract until //// @dev contract address is authorized with the storage contract //// @dev Once authorized, Use the `setParams` method to set storage values lib.Storage = TokenIOStorage(_storageContract); //// @dev set owner to contract initiator owner[msg.sender] = true; } /** * @notice Allows the address of the asset to be accepted by this contract by the currency type. This method is only called by admins. * @notice This method may be deprecated or refactored to allow for multiple interfaces * @param asset Ethereum address of the ERC20 compliant smart contract to allow the swap * @param currency string Currency symbol of the token (e.g. `USD`, `EUR`, `GBP`, `JPY`, `AUD`, `CAD`, `CHF`, `NOK`, `NZD`, `SEK`) * @param feeBps Basis points Swap Fee * @param feeMin Minimum Swap Fees * @param feeMax Maximum Swap Fee * @param feeFlat Flat Swap Fee * @return { "success" : "Returns true if successfully called from another contract"} */ function allowAsset(address asset, string currency, uint feeBps, uint feeMin, uint feeMax, uint feeFlat) public onlyOwner notDeprecated returns (bool success) { bytes32 id = keccak256(abi.encodePacked('allowed.stable.asset', asset, currency)); require( lib.Storage.setBool(id, true), "Error: Unable to set storage value. Please ensure contract interface is allowed by the storage contract." ); /// @notice set Currency for the asset; require(setAssetCurrency(asset, currency), 'Error: Unable to set Currency for asset'); /// @notice set the Fee Params for the asset require(setAssetFeeParams(asset, feeBps, feeMin, feeMax, feeFlat), 'Error: Unable to set fee params for asset'); /// @dev Log Allow ERC20 Asset emit AllowedERC20Asset(asset, currency); return true; } function removeAsset(address asset) public onlyOwner notDeprecated returns (bool success) { string memory currency = getAssetCurrency(asset); bytes32 id = keccak256(abi.encodePacked('allowed.stable.asset', asset, currency)); require( lib.Storage.setBool(id, false), "Error: Unable to set storage value. Please ensure contract interface is allowed by the storage contract." ); emit RemovedERC20Asset(asset, currency); return true; } /** * @notice Return boolean if the asset is an allowed stable asset for the corresponding currency * @param asset Ethereum address of the ERC20 compliant smart contract to check allowed status of * @param currency string Currency symbol of the token (e.g. `USD`, `EUR`, `GBP`, `JPY`, `AUD`, `CAD`, `CHF`, `NOK`, `NZD`, `SEK`) * @return {"allowed": "Returns true if the asset is allowed"} */ function isAllowedAsset(address asset, string currency) public view returns (bool allowed) { if (isTokenXContract(asset, currency)) { return true; } else { bytes32 id = keccak256(abi.encodePacked('allowed.stable.asset', asset, currency)); return lib.Storage.getBool(id); } } /** * Set the Three Letter Abbrevation for the currency associated to the asset * @param asset Ethereum address of the asset to set the currency for * @param currency string Currency of the asset (NOTE: This is the currency for the asset) * @return { "success" : "Returns true if successfully called from another contract"} */ function setAssetCurrency(address asset, string currency) public onlyOwner returns (bool success) { bytes32 id = keccak256(abi.encodePacked('asset.currency', asset)); require( lib.Storage.setString(id, currency), "Error: Unable to set storage value. Please ensure contract interface is allowed by the storage contract." ); return true; } /** * Get the Currency for an associated asset; * @param asset Ethereum address of the asset to get the currency for * @return {"currency": "Returns the Currency of the asset if the asset has been allowed."} */ function getAssetCurrency(address asset) public view returns (string currency) { bytes32 id = keccak256(abi.encodePacked('asset.currency', asset)); return lib.Storage.getString(id); } /** * @notice Register the address of the asset as a Token X asset for a specific currency * @notice This method may be deprecated or refactored to allow for multiple interfaces * @param asset Ethereum address of the ERC20 compliant Token X asset * @param currency string Currency symbol of the token (e.g. `USD`, `EUR`, `GBP`, `JPY`, `AUD`, `CAD`, `CHF`, `NOK`, `NZD`, `SEK`) * @return { "success" : "Returns true if successfully called from another contract"} */ function setTokenXCurrency(address asset, string currency) public onlyOwner notDeprecated returns (bool success) { bytes32 id = keccak256(abi.encodePacked('tokenx', asset, currency)); require( lib.Storage.setBool(id, true), "Error: Unable to set storage value. Please ensure contract interface is allowed by the storage contract." ); /// @notice set Currency for the asset; require(setAssetCurrency(asset, currency)); return true; } /** * @notice Return boolean if the asset is a registered Token X asset for the corresponding currency * @param asset Ethereum address of the asset to check if is a registered Token X stable coin asset * @param currency string Currency symbol of the token (e.g. `USD`, `EUR`, `GBP`, `JPY`, `AUD`, `CAD`, `CHF`, `NOK`, `NZD`, `SEK`) * @return {"allowed": "Returns true if the asset is allowed"} */ function isTokenXContract(address asset, string currency) public view returns (bool isX) { bytes32 id = keccak256(abi.encodePacked('tokenx', asset, currency)); return lib.Storage.getBool(id); } /** * @notice Set BPS, Min, Max, and Flat fee params for asset * @param asset Ethereum address of the asset to set fees for. * @param feeBps Basis points Swap Fee * @param feeMin Minimum Swap Fees * @param feeMax Maximum Swap Fee * @param feeFlat Flat Swap Fee * @return { "success" : "Returns true if successfully called from another contract"} */ function setAssetFeeParams(address asset, uint feeBps, uint feeMin, uint feeMax, uint feeFlat) public onlyOwner notDeprecated returns (bool success) { /// @dev This method bypasses the setFee library methods and directly sets the fee params for a requested asset. /// @notice Fees can be different per asset. Some assets may have different liquidity requirements. require(lib.Storage.setUint(keccak256(abi.encodePacked('fee.max', asset)), feeMax), 'Error: Failed to set fee parameters with storage contract. Please check permissions.'); require(lib.Storage.setUint(keccak256(abi.encodePacked('fee.min', asset)), feeMin), 'Error: Failed to set fee parameters with storage contract. Please check permissions.'); require(lib.Storage.setUint(keccak256(abi.encodePacked('fee.bps', asset)), feeBps), 'Error: Failed to set fee parameters with storage contract. Please check permissions.'); require(lib.Storage.setUint(keccak256(abi.encodePacked('fee.flat', asset)), feeFlat), 'Error: Failed to set fee parameters with storage contract. Please check permissions.'); return true; } /** * [calcAssetFees description] * @param asset Ethereum address of the asset to calculate fees based on * @param amount Amount to calculate fees on * @return { "fees" : "Returns the fees for the amount associated with the asset contract"} */ function calcAssetFees(address asset, uint amount) public view returns (uint fees) { return lib.calculateFees(asset, amount); } /** * @notice Return boolean if the asset is a registered Token X asset for the corresponding currency * @notice Amounts will always be passed in according to the decimal representation of the `fromAsset` token; * @param fromAsset Ethereum address of the asset with allowance for this contract to transfer and * @param toAsset Ethereum address of the asset to check if is a registered Token X stable coin asset * @param amount Amount of fromAsset to be transferred. * @return { "success" : "Returns true if successfully called from another contract"} */ function convert(address fromAsset, address toAsset, uint amount) public notDeprecated returns (bool success) {<FILL_FUNCTION_BODY> } /** * Allow this contract to transfer collected fees to another contract; * @param asset Ethereum address of asset to transfer * @param to Transfer collected fees to the following account; * @param amount Amount of fromAsset to be transferred. * @return { "success" : "Returns true if successfully called from another contract"} */ function transferCollectedFees(address asset, address to, uint amount) public onlyOwner notDeprecated returns (bool success) { require( ERC20Interface(asset).transfer(to, amount), "Error: Unable to transfer fees to account." ); emit TransferredHoldings(asset, to, amount); return true; } /** * @notice gets currency status of contract * @return {"deprecated" : "Returns true if deprecated, false otherwise"} */ function deprecateInterface() public onlyOwner returns (bool deprecated) { require(lib.setDeprecatedContract(address(this)), "Error: Unable to deprecate contract!"); return true; } modifier notDeprecated() { /// @notice throws if contract is deprecated require(!lib.isContractDeprecated(address(this)), "Error: Contract has been deprecated, cannot perform operation!"); _; } }
contract TokenIOStableSwap is Ownable { /// @dev use safe math operations using SafeMath for uint; //// @dev Set reference to TokenIOLib interface which proxies to TokenIOStorage using TokenIOLib for TokenIOLib.Data; TokenIOLib.Data lib; event StableSwap(address fromAsset, address toAsset, address requestedBy, uint amount, string currency); event TransferredHoldings(address asset, address to, uint amount); event AllowedERC20Asset(address asset, string currency); event RemovedERC20Asset(address asset, string currency); /** * @notice Constructor method for TokenIOStableSwap contract * @param _storageContract address of TokenIOStorage contract */ constructor(address _storageContract) public { //// @dev Set the storage contract for the interface //// @dev This contract will be unable to use the storage constract until //// @dev contract address is authorized with the storage contract //// @dev Once authorized, Use the `setParams` method to set storage values lib.Storage = TokenIOStorage(_storageContract); //// @dev set owner to contract initiator owner[msg.sender] = true; } /** * @notice Allows the address of the asset to be accepted by this contract by the currency type. This method is only called by admins. * @notice This method may be deprecated or refactored to allow for multiple interfaces * @param asset Ethereum address of the ERC20 compliant smart contract to allow the swap * @param currency string Currency symbol of the token (e.g. `USD`, `EUR`, `GBP`, `JPY`, `AUD`, `CAD`, `CHF`, `NOK`, `NZD`, `SEK`) * @param feeBps Basis points Swap Fee * @param feeMin Minimum Swap Fees * @param feeMax Maximum Swap Fee * @param feeFlat Flat Swap Fee * @return { "success" : "Returns true if successfully called from another contract"} */ function allowAsset(address asset, string currency, uint feeBps, uint feeMin, uint feeMax, uint feeFlat) public onlyOwner notDeprecated returns (bool success) { bytes32 id = keccak256(abi.encodePacked('allowed.stable.asset', asset, currency)); require( lib.Storage.setBool(id, true), "Error: Unable to set storage value. Please ensure contract interface is allowed by the storage contract." ); /// @notice set Currency for the asset; require(setAssetCurrency(asset, currency), 'Error: Unable to set Currency for asset'); /// @notice set the Fee Params for the asset require(setAssetFeeParams(asset, feeBps, feeMin, feeMax, feeFlat), 'Error: Unable to set fee params for asset'); /// @dev Log Allow ERC20 Asset emit AllowedERC20Asset(asset, currency); return true; } function removeAsset(address asset) public onlyOwner notDeprecated returns (bool success) { string memory currency = getAssetCurrency(asset); bytes32 id = keccak256(abi.encodePacked('allowed.stable.asset', asset, currency)); require( lib.Storage.setBool(id, false), "Error: Unable to set storage value. Please ensure contract interface is allowed by the storage contract." ); emit RemovedERC20Asset(asset, currency); return true; } /** * @notice Return boolean if the asset is an allowed stable asset for the corresponding currency * @param asset Ethereum address of the ERC20 compliant smart contract to check allowed status of * @param currency string Currency symbol of the token (e.g. `USD`, `EUR`, `GBP`, `JPY`, `AUD`, `CAD`, `CHF`, `NOK`, `NZD`, `SEK`) * @return {"allowed": "Returns true if the asset is allowed"} */ function isAllowedAsset(address asset, string currency) public view returns (bool allowed) { if (isTokenXContract(asset, currency)) { return true; } else { bytes32 id = keccak256(abi.encodePacked('allowed.stable.asset', asset, currency)); return lib.Storage.getBool(id); } } /** * Set the Three Letter Abbrevation for the currency associated to the asset * @param asset Ethereum address of the asset to set the currency for * @param currency string Currency of the asset (NOTE: This is the currency for the asset) * @return { "success" : "Returns true if successfully called from another contract"} */ function setAssetCurrency(address asset, string currency) public onlyOwner returns (bool success) { bytes32 id = keccak256(abi.encodePacked('asset.currency', asset)); require( lib.Storage.setString(id, currency), "Error: Unable to set storage value. Please ensure contract interface is allowed by the storage contract." ); return true; } /** * Get the Currency for an associated asset; * @param asset Ethereum address of the asset to get the currency for * @return {"currency": "Returns the Currency of the asset if the asset has been allowed."} */ function getAssetCurrency(address asset) public view returns (string currency) { bytes32 id = keccak256(abi.encodePacked('asset.currency', asset)); return lib.Storage.getString(id); } /** * @notice Register the address of the asset as a Token X asset for a specific currency * @notice This method may be deprecated or refactored to allow for multiple interfaces * @param asset Ethereum address of the ERC20 compliant Token X asset * @param currency string Currency symbol of the token (e.g. `USD`, `EUR`, `GBP`, `JPY`, `AUD`, `CAD`, `CHF`, `NOK`, `NZD`, `SEK`) * @return { "success" : "Returns true if successfully called from another contract"} */ function setTokenXCurrency(address asset, string currency) public onlyOwner notDeprecated returns (bool success) { bytes32 id = keccak256(abi.encodePacked('tokenx', asset, currency)); require( lib.Storage.setBool(id, true), "Error: Unable to set storage value. Please ensure contract interface is allowed by the storage contract." ); /// @notice set Currency for the asset; require(setAssetCurrency(asset, currency)); return true; } /** * @notice Return boolean if the asset is a registered Token X asset for the corresponding currency * @param asset Ethereum address of the asset to check if is a registered Token X stable coin asset * @param currency string Currency symbol of the token (e.g. `USD`, `EUR`, `GBP`, `JPY`, `AUD`, `CAD`, `CHF`, `NOK`, `NZD`, `SEK`) * @return {"allowed": "Returns true if the asset is allowed"} */ function isTokenXContract(address asset, string currency) public view returns (bool isX) { bytes32 id = keccak256(abi.encodePacked('tokenx', asset, currency)); return lib.Storage.getBool(id); } /** * @notice Set BPS, Min, Max, and Flat fee params for asset * @param asset Ethereum address of the asset to set fees for. * @param feeBps Basis points Swap Fee * @param feeMin Minimum Swap Fees * @param feeMax Maximum Swap Fee * @param feeFlat Flat Swap Fee * @return { "success" : "Returns true if successfully called from another contract"} */ function setAssetFeeParams(address asset, uint feeBps, uint feeMin, uint feeMax, uint feeFlat) public onlyOwner notDeprecated returns (bool success) { /// @dev This method bypasses the setFee library methods and directly sets the fee params for a requested asset. /// @notice Fees can be different per asset. Some assets may have different liquidity requirements. require(lib.Storage.setUint(keccak256(abi.encodePacked('fee.max', asset)), feeMax), 'Error: Failed to set fee parameters with storage contract. Please check permissions.'); require(lib.Storage.setUint(keccak256(abi.encodePacked('fee.min', asset)), feeMin), 'Error: Failed to set fee parameters with storage contract. Please check permissions.'); require(lib.Storage.setUint(keccak256(abi.encodePacked('fee.bps', asset)), feeBps), 'Error: Failed to set fee parameters with storage contract. Please check permissions.'); require(lib.Storage.setUint(keccak256(abi.encodePacked('fee.flat', asset)), feeFlat), 'Error: Failed to set fee parameters with storage contract. Please check permissions.'); return true; } /** * [calcAssetFees description] * @param asset Ethereum address of the asset to calculate fees based on * @param amount Amount to calculate fees on * @return { "fees" : "Returns the fees for the amount associated with the asset contract"} */ function calcAssetFees(address asset, uint amount) public view returns (uint fees) { return lib.calculateFees(asset, amount); } <FILL_FUNCTION> /** * Allow this contract to transfer collected fees to another contract; * @param asset Ethereum address of asset to transfer * @param to Transfer collected fees to the following account; * @param amount Amount of fromAsset to be transferred. * @return { "success" : "Returns true if successfully called from another contract"} */ function transferCollectedFees(address asset, address to, uint amount) public onlyOwner notDeprecated returns (bool success) { require( ERC20Interface(asset).transfer(to, amount), "Error: Unable to transfer fees to account." ); emit TransferredHoldings(asset, to, amount); return true; } /** * @notice gets currency status of contract * @return {"deprecated" : "Returns true if deprecated, false otherwise"} */ function deprecateInterface() public onlyOwner returns (bool deprecated) { require(lib.setDeprecatedContract(address(this)), "Error: Unable to deprecate contract!"); return true; } modifier notDeprecated() { /// @notice throws if contract is deprecated require(!lib.isContractDeprecated(address(this)), "Error: Contract has been deprecated, cannot perform operation!"); _; } }
/// @notice lookup currency from one of the assets, check if allowed by both assets. string memory currency = getAssetCurrency(fromAsset); uint fromDecimals = ERC20Interface(fromAsset).decimals(); uint toDecimals = ERC20Interface(toAsset).decimals(); /// @dev Ensure assets are allowed to be swapped; require(isAllowedAsset(fromAsset, currency), 'Error: Unsupported asset requested. Asset must be supported by this contract and have a currency of `USD`, `EUR`, `GBP`, `JPY`, `AUD`, `CAD`, `CHF`, `NOK`, `NZD`, `SEK` .'); require(isAllowedAsset(toAsset, currency), 'Error: Unsupported asset requested. Asset must be supported by this contract and have a currency of `USD`, `EUR`, `GBP`, `JPY`, `AUD`, `CAD`, `CHF`, `NOK`, `NZD`, `SEK` .'); /// @dev require one of the assets be equal to Token X asset; if (isTokenXContract(toAsset, currency)) { /// @notice This requires the erc20 transfer function to return a boolean result of true; /// @dev the amount being transferred must be in the same decimal representation of the asset /// e.g. If decimals = 6 and want to transfer $100.00 the amount passed to this contract should be 100e6 (100 * 10 ** 6) require( ERC20Interface(fromAsset).transferFrom(msg.sender, address(this), amount), 'Error: Unable to transferFrom your asset holdings. Please ensure this contract has an approved allowance equal to or greater than the amount called in transferFrom method.' ); /// @dev Deposit TokenX asset to the user; /// @notice Amount received from deposit is net of fees. uint netAmountFrom = amount.sub(calcAssetFees(fromAsset, amount)); /// @dev Ensure amount is converted for the correct decimal representation; uint convertedAmountFrom = (netAmountFrom.mul(10**toDecimals)).div(10**fromDecimals); require( lib.deposit(lib.getTokenSymbol(toAsset), msg.sender, convertedAmountFrom, 'Token, Inc.'), "Error: Unable to deposit funds. Please check issuerFirm and firm authority are registered" ); } else if(isTokenXContract(fromAsset, currency)) { ///@dev Transfer the asset to the user; /// @notice Amount received from withdraw is net of fees. uint convertedAmount = (amount.mul(10**toDecimals)).div(10**fromDecimals); uint fees = calcAssetFees(toAsset, convertedAmount); uint netAmountTo = convertedAmount.sub(fees); /// @dev Ensure amount is converted for the correct decimal representation; require( ERC20Interface(toAsset).transfer(msg.sender, netAmountTo), 'Unable to call the requested erc20 contract.' ); /// @dev Withdraw TokenX asset from the user require( lib.withdraw(lib.getTokenSymbol(fromAsset), msg.sender, amount, 'Token, Inc.'), "Error: Unable to withdraw funds. Please check issuerFirm and firm authority are registered and have issued funds that can be withdrawn" ); } else { revert('Error: At least one asset must be issued by Token, Inc. (Token X).'); } /// @dev Log the swap event for event listeners emit StableSwap(fromAsset, toAsset, msg.sender, amount, currency); return true;
function convert(address fromAsset, address toAsset, uint amount) public notDeprecated returns (bool success)
/** * @notice Return boolean if the asset is a registered Token X asset for the corresponding currency * @notice Amounts will always be passed in according to the decimal representation of the `fromAsset` token; * @param fromAsset Ethereum address of the asset with allowance for this contract to transfer and * @param toAsset Ethereum address of the asset to check if is a registered Token X stable coin asset * @param amount Amount of fromAsset to be transferred. * @return { "success" : "Returns true if successfully called from another contract"} */ function convert(address fromAsset, address toAsset, uint amount) public notDeprecated returns (bool success)
76396
Context
_msgData
contract Context { constructor () internal { } // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns (address payable) { return msg.sender; } function _msgData() internal view returns (bytes memory) {<FILL_FUNCTION_BODY> } }
contract Context { constructor () internal { } // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns (address payable) { return msg.sender; } <FILL_FUNCTION> }
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data;
function _msgData() internal view returns (bytes memory)
function _msgData() internal view returns (bytes memory)
20429
StandardToken
transferFrom
contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom( address _from, address _to, uint256 _value ) public returns (bool) {<FILL_FUNCTION_BODY> } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance( address _owner, address _spender ) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval( address _spender, uint _addedValue ) public returns (bool) { allowed[msg.sender][_spender] = ( allowed[msg.sender][_spender].add(_addedValue)); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval( address _spender, uint _subtractedValue ) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } }
contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; <FILL_FUNCTION> /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance( address _owner, address _spender ) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval( address _spender, uint _addedValue ) public returns (bool) { allowed[msg.sender][_spender] = ( allowed[msg.sender][_spender].add(_addedValue)); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval( address _spender, uint _subtractedValue ) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } }
require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true;
function 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)
41418
MyToken
transferFrom
contract MyToken { string public constant name = "Premium security"; string public constant symbol = "4BUM"; uint8 public constant decimals = 0; event Approval(address indexed tokenOwner, address indexed spender, uint tokens); event Transfer(address indexed from, address indexed to, uint tokens); mapping(address => uint256) balances; mapping(address => mapping (address => uint256)) allowed; uint256 totalSupply_; using SafeMath for uint256; constructor( uint256 _totalSupply) public{ totalSupply_ = _totalSupply; balances[msg.sender] = totalSupply_; } function totalSupply() public view returns (uint256) { return totalSupply_; } function balanceOf(address tokenOwner) public view returns (uint) { return balances[tokenOwner]; } function transfer(address receiver, uint numTokens) public returns (bool) { require(numTokens <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(numTokens); balances[receiver] = balances[receiver].add(numTokens); emit Transfer(msg.sender, receiver, numTokens); return true; } 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) {<FILL_FUNCTION_BODY> } }
contract MyToken { string public constant name = "Premium security"; string public constant symbol = "4BUM"; uint8 public constant decimals = 0; event Approval(address indexed tokenOwner, address indexed spender, uint tokens); event Transfer(address indexed from, address indexed to, uint tokens); mapping(address => uint256) balances; mapping(address => mapping (address => uint256)) allowed; uint256 totalSupply_; using SafeMath for uint256; constructor( uint256 _totalSupply) public{ totalSupply_ = _totalSupply; balances[msg.sender] = totalSupply_; } function totalSupply() public view returns (uint256) { return totalSupply_; } function balanceOf(address tokenOwner) public view returns (uint) { return balances[tokenOwner]; } function transfer(address receiver, uint numTokens) public returns (bool) { require(numTokens <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(numTokens); balances[receiver] = balances[receiver].add(numTokens); emit Transfer(msg.sender, receiver, numTokens); return true; } 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]; } <FILL_FUNCTION> }
require(numTokens <= balances[owner]); require(numTokens <= allowed[owner][msg.sender]); balances[owner] = balances[owner].sub(numTokens); allowed[owner][msg.sender] = allowed[owner][msg.sender].sub(numTokens); balances[buyer] = balances[buyer].add(numTokens); emit Transfer(owner, buyer, numTokens); return true;
function transferFrom(address owner, address buyer, uint numTokens) public returns (bool)
function transferFrom(address owner, address buyer, uint numTokens) public returns (bool)
44813
FomoToken
transfer
contract FomoToken is IERC20{ using SafeMath for uint256; uint public constant _totalSupply = 7500000000000; string public constant symbol = "FOMO"; string public constant name = "Fomo Token"; uint8 public constant decimals = 4; mapping(address => uint256) balances; mapping(address => mapping(address => uint256)) allowed; function FomoToken(){ balances[msg.sender] = _totalSupply; } function totalSupply() constant returns (uint256 totalSupply){ return _totalSupply; } function balanceOf(address _owner) constant returns (uint256 balance){ return balances[_owner]; } function transfer(address _to, uint256 _value) returns (bool success){<FILL_FUNCTION_BODY> } function transferFrom(address _from, address _to, uint256 _value) returns (bool success){ require( allowed[_from][msg.sender] >= _value && balances[_from] >= _value && _value > 0 ); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } function approve(address _spender, uint256 _value) returns (bool success){ allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) constant returns (uint256 remaining){ return allowed[_owner][_spender]; } event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); }
contract FomoToken is IERC20{ using SafeMath for uint256; uint public constant _totalSupply = 7500000000000; string public constant symbol = "FOMO"; string public constant name = "Fomo Token"; uint8 public constant decimals = 4; mapping(address => uint256) balances; mapping(address => mapping(address => uint256)) allowed; function FomoToken(){ balances[msg.sender] = _totalSupply; } function totalSupply() constant returns (uint256 totalSupply){ return _totalSupply; } function balanceOf(address _owner) constant returns (uint256 balance){ return balances[_owner]; } <FILL_FUNCTION> function transferFrom(address _from, address _to, uint256 _value) returns (bool success){ require( allowed[_from][msg.sender] >= _value && balances[_from] >= _value && _value > 0 ); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } function approve(address _spender, uint256 _value) returns (bool success){ allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) constant returns (uint256 remaining){ return allowed[_owner][_spender]; } event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); }
require( balances[msg.sender] >= _value && _value > 0 ); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true;
function transfer(address _to, uint256 _value) returns (bool success)
function transfer(address _to, uint256 _value) returns (bool success)
24102
BasicToken
balanceOf
contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @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(_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; } /** * @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) {<FILL_FUNCTION_BODY> } }
contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @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(_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; } <FILL_FUNCTION> }
return balances[_owner];
function balanceOf(address _owner) public view returns (uint256)
/** * @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)
92936
OperationalControl
setPrimaryManager
contract OperationalControl { // Facilitates access & control for the game. // Roles: // -The Managers (Primary/Secondary): Has universal control of all elements (No ability to withdraw) // -The Banker: The Bank can withdraw funds and adjust fees / prices. /// @dev Emited when contract is upgraded event ContractUpgrade(address newContract); // The addresses of the accounts (or contracts) that can execute actions within each roles. address public managerPrimary; address public managerSecondary; address public bankManager; // @dev Keeps track whether the contract is paused. When that is true, most actions are blocked bool public paused = false; // @dev Keeps track whether the contract erroredOut. When that is true, most actions are blocked & refund can be claimed bool public error = false; /// @dev Operation modifiers for limiting access modifier onlyManager() { require(msg.sender == managerPrimary || msg.sender == managerSecondary); _; } modifier onlyBanker() { require(msg.sender == bankManager); _; } modifier anyOperator() { require( msg.sender == managerPrimary || msg.sender == managerSecondary || msg.sender == bankManager ); _; } /// @dev Assigns a new address to act as the Primary Manager. function setPrimaryManager(address _newGM) external onlyManager {<FILL_FUNCTION_BODY> } /// @dev Assigns a new address to act as the Secondary Manager. function setSecondaryManager(address _newGM) external onlyManager { require(_newGM != address(0)); managerSecondary = _newGM; } /// @dev Assigns a new address to act as the Banker. function setBanker(address _newBK) external onlyManager { require(_newBK != address(0)); bankManager = _newBK; } /*** Pausable functionality adapted from OpenZeppelin ***/ /// @dev Modifier to allow actions only when the contract IS NOT paused modifier whenNotPaused() { require(!paused); _; } /// @dev Modifier to allow actions only when the contract IS paused modifier whenPaused { require(paused); _; } /// @dev Modifier to allow actions only when the contract has Error modifier whenError { require(error); _; } /// @dev Called by any Operator role to pause the contract. /// Used only if a bug or exploit is discovered (Here to limit losses / damage) function pause() external onlyManager whenNotPaused { paused = true; } /// @dev Unpauses the smart contract. Can only be called by the Game Master /// @notice This is public rather than external so it can be called by derived contracts. function unpause() public onlyManager whenPaused { // can't unpause if contract was upgraded paused = false; } /// @dev Unpauses the smart contract. Can only be called by the Game Master /// @notice This is public rather than external so it can be called by derived contracts. function hasError() public onlyManager whenPaused { error = true; } /// @dev Unpauses the smart contract. Can only be called by the Game Master /// @notice This is public rather than external so it can be called by derived contracts. function noError() public onlyManager whenPaused { error = false; } }
contract OperationalControl { // Facilitates access & control for the game. // Roles: // -The Managers (Primary/Secondary): Has universal control of all elements (No ability to withdraw) // -The Banker: The Bank can withdraw funds and adjust fees / prices. /// @dev Emited when contract is upgraded event ContractUpgrade(address newContract); // The addresses of the accounts (or contracts) that can execute actions within each roles. address public managerPrimary; address public managerSecondary; address public bankManager; // @dev Keeps track whether the contract is paused. When that is true, most actions are blocked bool public paused = false; // @dev Keeps track whether the contract erroredOut. When that is true, most actions are blocked & refund can be claimed bool public error = false; /// @dev Operation modifiers for limiting access modifier onlyManager() { require(msg.sender == managerPrimary || msg.sender == managerSecondary); _; } modifier onlyBanker() { require(msg.sender == bankManager); _; } modifier anyOperator() { require( msg.sender == managerPrimary || msg.sender == managerSecondary || msg.sender == bankManager ); _; } <FILL_FUNCTION> /// @dev Assigns a new address to act as the Secondary Manager. function setSecondaryManager(address _newGM) external onlyManager { require(_newGM != address(0)); managerSecondary = _newGM; } /// @dev Assigns a new address to act as the Banker. function setBanker(address _newBK) external onlyManager { require(_newBK != address(0)); bankManager = _newBK; } /*** Pausable functionality adapted from OpenZeppelin ***/ /// @dev Modifier to allow actions only when the contract IS NOT paused modifier whenNotPaused() { require(!paused); _; } /// @dev Modifier to allow actions only when the contract IS paused modifier whenPaused { require(paused); _; } /// @dev Modifier to allow actions only when the contract has Error modifier whenError { require(error); _; } /// @dev Called by any Operator role to pause the contract. /// Used only if a bug or exploit is discovered (Here to limit losses / damage) function pause() external onlyManager whenNotPaused { paused = true; } /// @dev Unpauses the smart contract. Can only be called by the Game Master /// @notice This is public rather than external so it can be called by derived contracts. function unpause() public onlyManager whenPaused { // can't unpause if contract was upgraded paused = false; } /// @dev Unpauses the smart contract. Can only be called by the Game Master /// @notice This is public rather than external so it can be called by derived contracts. function hasError() public onlyManager whenPaused { error = true; } /// @dev Unpauses the smart contract. Can only be called by the Game Master /// @notice This is public rather than external so it can be called by derived contracts. function noError() public onlyManager whenPaused { error = false; } }
require(_newGM != address(0)); managerPrimary = _newGM;
function setPrimaryManager(address _newGM) external onlyManager
/// @dev Assigns a new address to act as the Primary Manager. function setPrimaryManager(address _newGM) external onlyManager
57397
STKN
transfer
contract STKN is ERC20Interface, Owned, SafeMath { string public symbol; string public name; uint8 public decimals; uint public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ constructor() public { symbol = "STKN"; name = "Student Token"; decimals = 0; _totalSupply = 10000000000; balances[0x6B4199979Bc2AFAE6Bb161b1Ba7a6aD2A983Bf3d] = _totalSupply; emit Transfer(address(0), 0x6B4199979Bc2AFAE6Bb161b1Ba7a6aD2A983Bf3d, _totalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account tokenOwner // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to to account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) {<FILL_FUNCTION_BODY> } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer tokens from the from account to the to account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the from account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account. The spender contract function // receiveApproval(...) is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ function () public payable { revert(); } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
contract STKN is ERC20Interface, Owned, SafeMath { string public symbol; string public name; uint8 public decimals; uint public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ constructor() public { symbol = "STKN"; name = "Student Token"; decimals = 0; _totalSupply = 10000000000; balances[0x6B4199979Bc2AFAE6Bb161b1Ba7a6aD2A983Bf3d] = _totalSupply; emit Transfer(address(0), 0x6B4199979Bc2AFAE6Bb161b1Ba7a6aD2A983Bf3d, _totalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account tokenOwner // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } <FILL_FUNCTION> // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer tokens from the from account to the to account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the from account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account. The spender contract function // receiveApproval(...) is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ function () public payable { revert(); } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(msg.sender, to, tokens); return true;
function transfer(address to, uint tokens) public returns (bool success)
// ------------------------------------------------------------------------ // Transfer the balance from token owner's account to to account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success)
27218
SinoGlobal
transferAnyERC20Token
contract SinoGlobal 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 SinoGlobal() public { symbol = "SINO"; name = "Sino Global"; decimals = 18; _totalSupply = 21000000000000000000000000; balances[0x6efba1FD187F9db4CEa499d16D8029050EC0284B] = _totalSupply; Transfer(address(0), 0x6efba1FD187F9db4CEa499d16D8029050EC0284B, _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) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer tokens from the from account to the to account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the from account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account. The spender contract function // receiveApproval(...) is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ function () public payable { revert(); } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {<FILL_FUNCTION_BODY> } }
contract SinoGlobal 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 SinoGlobal() public { symbol = "SINO"; name = "Sino Global"; decimals = 18; _totalSupply = 21000000000000000000000000; balances[0x6efba1FD187F9db4CEa499d16D8029050EC0284B] = _totalSupply; Transfer(address(0), 0x6efba1FD187F9db4CEa499d16D8029050EC0284B, _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) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer tokens from the from account to the to account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the from account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account. The spender contract function // receiveApproval(...) is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ function () public payable { revert(); } <FILL_FUNCTION> }
return ERC20Interface(tokenAddress).transfer(owner, tokens);
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success)
// ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success)
42405
ERC20Detailed
null
contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; constructor (string memory name, string memory symbol, uint8 decimals) public {<FILL_FUNCTION_BODY> } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } }
contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; <FILL_FUNCTION> function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } }
_name = name; _symbol = symbol; _decimals = decimals;
constructor (string memory name, string memory symbol, uint8 decimals) public
constructor (string memory name, string memory symbol, uint8 decimals) public
30435
MainSale
closeSale
contract MainSale is Ownable { using SafeMath for uint; ERC20 public token; address reserve = 0x611200beabeac749071b30db84d17ec205654463; address promouters = 0x2632d043ac8bbbad07c7dabd326ade3ca4f6b53e; address bounty = 0xff5a1984fade92bfb0e5fd7986186d432545b834; uint256 public constant decimals = 18; uint256 constant dec = 10**decimals; mapping(address=>bool) whitelist; uint256 public startCloseSale = now; // start // 1.07.2018 10:00 UTC uint256 public endCloseSale = 1532987999; // Monday, 30-Jul-18 23:59:59 UTC-2 uint256 public startStage1 = 1532988001; // Tuesday, 31-Jul-18 00:00:01 UTC-2 uint256 public endStage1 = 1533074399; // Tuesday, 31-Jul-18 23:59:59 UTC-2 uint256 public startStage2 = 1533074400; // Wednesday, 01-Aug-18 00:00:00 UTC-2 uint256 public endStage2 = 1533679199; // Tuesday, 07-Aug-18 23:59:59 UTC-2 uint256 public startStage3 = 1533679200; // Wednesday, 08-Aug-18 00:00:00 UTC-2 uint256 public endStage3 = 1535752799; // Friday, 31-Aug-18 23:59:59 UTC-2 uint256 public buyPrice = 920000000000000000; // 0.92 Ether uint256 public ethUSD; uint256 public weisRaised = 0; string public stageNow = "NoSale"; event Authorized(address wlCandidate, uint timestamp); event Revoked(address wlCandidate, uint timestamp); constructor() public {} function setToken (ERC20 _token) public onlyOwner { token = _token; } /******************************************************************************* * Whitelist's section */ function authorize(address wlCandidate) public onlyOwner { require(wlCandidate != address(0x0)); require(!isWhitelisted(wlCandidate)); whitelist[wlCandidate] = true; emit Authorized(wlCandidate, now); } function revoke(address wlCandidate) public onlyOwner { whitelist[wlCandidate] = false; emit Revoked(wlCandidate, now); } function isWhitelisted(address wlCandidate) public view returns(bool) { return whitelist[wlCandidate]; } /******************************************************************************* * Setter's Section */ function setStartCloseSale(uint256 newStartSale) public onlyOwner { startCloseSale = newStartSale; } function setEndCloseSale(uint256 newEndSale) public onlyOwner{ endCloseSale = newEndSale; } function setStartStage1(uint256 newsetStage2) public onlyOwner{ startStage1 = newsetStage2; } function setEndStage1(uint256 newsetStage3) public onlyOwner{ endStage1 = newsetStage3; } function setStartStage2(uint256 newsetStage4) public onlyOwner{ startStage2 = newsetStage4; } function setEndStage2(uint256 newsetStage5) public onlyOwner{ endStage2 = newsetStage5; } function setStartStage3(uint256 newsetStage5) public onlyOwner{ startStage3 = newsetStage5; } function setEndStage3(uint256 newsetStage5) public onlyOwner{ endStage3 = newsetStage5; } function setPrices(uint256 newPrice) public onlyOwner { buyPrice = newPrice; } function setETHUSD(uint256 _ethUSD) public onlyOwner { ethUSD = _ethUSD; } /******************************************************************************* * Payable Section */ function () public payable { require(msg.value >= (1*1e18/ethUSD*100)); if (now >= startCloseSale || now <= endCloseSale) { require(isWhitelisted(msg.sender)); closeSale(msg.sender, msg.value); stageNow = "Close Sale for Whitelist's members"; } else if (now >= startStage1 || now <= endStage1) { sale1(msg.sender, msg.value); stageNow = "Stage 1"; } else if (now >= startStage2 || now <= endStage2) { sale2(msg.sender, msg.value); stageNow = "Stage 2"; } else if (now >= startStage3 || now <= endStage3) { sale3(msg.sender, msg.value); stageNow = "Stage 3"; } else { stageNow = "No Sale"; revert(); } } // issue token in a period of closed sales function closeSale(address _investor, uint256 _value) internal {<FILL_FUNCTION_BODY> } // the issue of tokens in period 1 sales function sale1(address _investor, uint256 _value) internal { uint256 tokens = _value.mul(1e18).div(buyPrice); // 66% uint256 bonusTokens = tokens.mul(10).div(100); // + 10% per stage tokens = tokens.add(bonusTokens); // 66 % token.transferFromICO(_investor, tokens); uint256 tokensReserve = tokens.mul(5).div(22); // 15 % token.transferFromICO(reserve, tokensReserve); uint256 tokensBoynty = tokens.mul(2).div(33); // 4 % token.transferFromICO(bounty, tokensBoynty); uint256 tokensPromo = tokens.mul(5).div(22); // 15% token.transferFromICO(promouters, tokensPromo); weisRaised = weisRaised.add(msg.value); } // the issue of tokens in period 2 sales function sale2(address _investor, uint256 _value) internal { uint256 tokens = _value.mul(1e18).div(buyPrice); // 64 % uint256 bonusTokens = tokens.mul(5).div(100); // + 5% tokens = tokens.add(bonusTokens); token.transferFromICO(_investor, tokens); uint256 tokensReserve = tokens.mul(15).div(64); // 15 % token.transferFromICO(reserve, tokensReserve); uint256 tokensBoynty = tokens.mul(3).div(32); // 6 % token.transferFromICO(bounty, tokensBoynty); uint256 tokensPromo = tokens.mul(15).div(64); // 15% token.transferFromICO(promouters, tokensPromo); weisRaised = weisRaised.add(msg.value); } // the issue of tokens in period 3 sales function sale3(address _investor, uint256 _value) internal { uint256 tokens = _value.mul(1e18).div(buyPrice); // 62 % token.transferFromICO(_investor, tokens); uint256 tokensReserve = tokens.mul(15).div(62); // 15 % token.transferFromICO(reserve, tokensReserve); uint256 tokensBoynty = tokens.mul(4).div(31); // 8 % token.transferFromICO(bounty, tokensBoynty); uint256 tokensPromo = tokens.mul(15).div(62); // 15% token.transferFromICO(promouters, tokensPromo); weisRaised = weisRaised.add(msg.value); } /******************************************************************************* * Manual Management */ function transferEthFromContract(address _to, uint256 amount) public onlyOwner { _to.transfer(amount); } }
contract MainSale is Ownable { using SafeMath for uint; ERC20 public token; address reserve = 0x611200beabeac749071b30db84d17ec205654463; address promouters = 0x2632d043ac8bbbad07c7dabd326ade3ca4f6b53e; address bounty = 0xff5a1984fade92bfb0e5fd7986186d432545b834; uint256 public constant decimals = 18; uint256 constant dec = 10**decimals; mapping(address=>bool) whitelist; uint256 public startCloseSale = now; // start // 1.07.2018 10:00 UTC uint256 public endCloseSale = 1532987999; // Monday, 30-Jul-18 23:59:59 UTC-2 uint256 public startStage1 = 1532988001; // Tuesday, 31-Jul-18 00:00:01 UTC-2 uint256 public endStage1 = 1533074399; // Tuesday, 31-Jul-18 23:59:59 UTC-2 uint256 public startStage2 = 1533074400; // Wednesday, 01-Aug-18 00:00:00 UTC-2 uint256 public endStage2 = 1533679199; // Tuesday, 07-Aug-18 23:59:59 UTC-2 uint256 public startStage3 = 1533679200; // Wednesday, 08-Aug-18 00:00:00 UTC-2 uint256 public endStage3 = 1535752799; // Friday, 31-Aug-18 23:59:59 UTC-2 uint256 public buyPrice = 920000000000000000; // 0.92 Ether uint256 public ethUSD; uint256 public weisRaised = 0; string public stageNow = "NoSale"; event Authorized(address wlCandidate, uint timestamp); event Revoked(address wlCandidate, uint timestamp); constructor() public {} function setToken (ERC20 _token) public onlyOwner { token = _token; } /******************************************************************************* * Whitelist's section */ function authorize(address wlCandidate) public onlyOwner { require(wlCandidate != address(0x0)); require(!isWhitelisted(wlCandidate)); whitelist[wlCandidate] = true; emit Authorized(wlCandidate, now); } function revoke(address wlCandidate) public onlyOwner { whitelist[wlCandidate] = false; emit Revoked(wlCandidate, now); } function isWhitelisted(address wlCandidate) public view returns(bool) { return whitelist[wlCandidate]; } /******************************************************************************* * Setter's Section */ function setStartCloseSale(uint256 newStartSale) public onlyOwner { startCloseSale = newStartSale; } function setEndCloseSale(uint256 newEndSale) public onlyOwner{ endCloseSale = newEndSale; } function setStartStage1(uint256 newsetStage2) public onlyOwner{ startStage1 = newsetStage2; } function setEndStage1(uint256 newsetStage3) public onlyOwner{ endStage1 = newsetStage3; } function setStartStage2(uint256 newsetStage4) public onlyOwner{ startStage2 = newsetStage4; } function setEndStage2(uint256 newsetStage5) public onlyOwner{ endStage2 = newsetStage5; } function setStartStage3(uint256 newsetStage5) public onlyOwner{ startStage3 = newsetStage5; } function setEndStage3(uint256 newsetStage5) public onlyOwner{ endStage3 = newsetStage5; } function setPrices(uint256 newPrice) public onlyOwner { buyPrice = newPrice; } function setETHUSD(uint256 _ethUSD) public onlyOwner { ethUSD = _ethUSD; } /******************************************************************************* * Payable Section */ function () public payable { require(msg.value >= (1*1e18/ethUSD*100)); if (now >= startCloseSale || now <= endCloseSale) { require(isWhitelisted(msg.sender)); closeSale(msg.sender, msg.value); stageNow = "Close Sale for Whitelist's members"; } else if (now >= startStage1 || now <= endStage1) { sale1(msg.sender, msg.value); stageNow = "Stage 1"; } else if (now >= startStage2 || now <= endStage2) { sale2(msg.sender, msg.value); stageNow = "Stage 2"; } else if (now >= startStage3 || now <= endStage3) { sale3(msg.sender, msg.value); stageNow = "Stage 3"; } else { stageNow = "No Sale"; revert(); } } <FILL_FUNCTION> // the issue of tokens in period 1 sales function sale1(address _investor, uint256 _value) internal { uint256 tokens = _value.mul(1e18).div(buyPrice); // 66% uint256 bonusTokens = tokens.mul(10).div(100); // + 10% per stage tokens = tokens.add(bonusTokens); // 66 % token.transferFromICO(_investor, tokens); uint256 tokensReserve = tokens.mul(5).div(22); // 15 % token.transferFromICO(reserve, tokensReserve); uint256 tokensBoynty = tokens.mul(2).div(33); // 4 % token.transferFromICO(bounty, tokensBoynty); uint256 tokensPromo = tokens.mul(5).div(22); // 15% token.transferFromICO(promouters, tokensPromo); weisRaised = weisRaised.add(msg.value); } // the issue of tokens in period 2 sales function sale2(address _investor, uint256 _value) internal { uint256 tokens = _value.mul(1e18).div(buyPrice); // 64 % uint256 bonusTokens = tokens.mul(5).div(100); // + 5% tokens = tokens.add(bonusTokens); token.transferFromICO(_investor, tokens); uint256 tokensReserve = tokens.mul(15).div(64); // 15 % token.transferFromICO(reserve, tokensReserve); uint256 tokensBoynty = tokens.mul(3).div(32); // 6 % token.transferFromICO(bounty, tokensBoynty); uint256 tokensPromo = tokens.mul(15).div(64); // 15% token.transferFromICO(promouters, tokensPromo); weisRaised = weisRaised.add(msg.value); } // the issue of tokens in period 3 sales function sale3(address _investor, uint256 _value) internal { uint256 tokens = _value.mul(1e18).div(buyPrice); // 62 % token.transferFromICO(_investor, tokens); uint256 tokensReserve = tokens.mul(15).div(62); // 15 % token.transferFromICO(reserve, tokensReserve); uint256 tokensBoynty = tokens.mul(4).div(31); // 8 % token.transferFromICO(bounty, tokensBoynty); uint256 tokensPromo = tokens.mul(15).div(62); // 15% token.transferFromICO(promouters, tokensPromo); weisRaised = weisRaised.add(msg.value); } /******************************************************************************* * Manual Management */ function transferEthFromContract(address _to, uint256 amount) public onlyOwner { _to.transfer(amount); } }
uint256 tokens = _value.mul(1e18).div(buyPrice); // 68% uint256 bonusTokens = tokens.mul(30).div(100); // + 30% per stage tokens = tokens.add(bonusTokens); token.transferFromICO(_investor, tokens); weisRaised = weisRaised.add(msg.value); uint256 tokensReserve = tokens.mul(15).div(68); // 15 % token.transferFromICO(reserve, tokensReserve); uint256 tokensBoynty = tokens.div(34); // 2 % token.transferFromICO(bounty, tokensBoynty); uint256 tokensPromo = tokens.mul(15).div(68); // 15% token.transferFromICO(promouters, tokensPromo);
function closeSale(address _investor, uint256 _value) internal
// issue token in a period of closed sales function closeSale(address _investor, uint256 _value) internal
670
TWAPBound
withinBoundsWithQuote
contract TWAPBound is YamSubGoverned { using SafeMath for uint256; uint256 public constant BASE = 10**18; /// @notice For a sale of a specific amount uint256 public sell_amount; /// @notice For a purchase of a specific amount uint256 public purchase_amount; /// @notice Token to be sold address public sell_token; /// @notice Token to be puchased address public purchase_token; /// @notice Current uniswap pair for purchase & sale tokens address public uniswap_pair1; /// @notice Second uniswap pair for if TWAP uses two markets to determine price (for liquidity purposes) address public uniswap_pair2; /// @notice Flag for if purchase token is toke 0 in uniswap pair 2 bool public purchaseTokenIs0; /// @notice Flag for if sale token is token 0 in uniswap pair bool public saleTokenIs0; /// @notice TWAP for first hop uint256 public priceAverageSell; /// @notice TWAP for second hop uint256 public priceAverageBuy; /// @notice last TWAP update time uint32 public blockTimestampLast; /// @notice last TWAP cumulative price; uint256 public priceCumulativeLastSell; /// @notice last TWAP cumulative price for two hop pairs; uint256 public priceCumulativeLastBuy; /// @notice Time between TWAP updates uint256 public period; /// @notice counts number of twaps uint256 public twap_counter; /// @notice Grace period after last twap update for a trade to occur uint256 public grace = 60 * 60; // 1 hour uint256 public constant MAX_BOUND = 10**17; /// @notice % bound away from TWAP price uint256 public twap_bounds; /// @notice denotes a trade as complete bool public complete; bool public isSale; function setup_twap_bound ( address sell_token_, address purchase_token_, uint256 amount_, bool is_sale, uint256 twap_period, uint256 twap_bounds_, address uniswap1, address uniswap2, // if two hop uint256 grace_ // length after twap update that it can occur ) public onlyGovOrSubGov { require(twap_bounds_ <= MAX_BOUND, "slippage too high"); sell_token = sell_token_; purchase_token = purchase_token_; period = twap_period; twap_bounds = twap_bounds_; isSale = is_sale; if (is_sale) { sell_amount = amount_; purchase_amount = 0; } else { purchase_amount = amount_; sell_amount = 0; } complete = false; grace = grace_; reset_twap(uniswap1, uniswap2, sell_token, purchase_token); } function reset_twap( address uniswap1, address uniswap2, address sell_token_, address purchase_token_ ) internal { uniswap_pair1 = uniswap1; uniswap_pair2 = uniswap2; blockTimestampLast = 0; priceCumulativeLastSell = 0; priceCumulativeLastBuy = 0; priceAverageBuy = 0; if (UniswapPair(uniswap1).token0() == sell_token_) { saleTokenIs0 = true; } else { saleTokenIs0 = false; } if (uniswap2 != address(0)) { if (UniswapPair(uniswap2).token0() == purchase_token_) { purchaseTokenIs0 = true; } else { purchaseTokenIs0 = false; } } update_twap(); twap_counter = 0; } function quote( uint256 purchaseAmount, uint256 saleAmount ) public view returns (uint256) { uint256 decs = uint256(ExpandedERC20(sell_token).decimals()); uint256 one = 10**decs; return purchaseAmount.mul(one).div(saleAmount); } function bounds() public view returns (uint256) { uint256 uniswap_quote = consult(); uint256 minimum = uniswap_quote.mul(BASE.sub(twap_bounds)).div(BASE); return minimum; } function bounds_max() public view returns (uint256) { uint256 uniswap_quote = consult(); uint256 maximum = uniswap_quote.mul(BASE.add(twap_bounds)).div(BASE); return maximum; } function withinBounds ( uint256 purchaseAmount, uint256 saleAmount ) internal view returns (bool) { uint256 quoted = quote(purchaseAmount, saleAmount); uint256 minimum = bounds(); uint256 maximum = bounds_max(); return quoted > minimum && quoted < maximum; } function withinBoundsWithQuote ( uint256 quoted ) internal view returns (bool) {<FILL_FUNCTION_BODY> } // callable by anyone function update_twap() public { (uint256 sell_token_priceCumulative, uint32 blockTimestamp) = UniswapV2OracleLibrary.currentCumulativePrices(uniswap_pair1, saleTokenIs0); uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired // ensure that at least one full period has passed since the last update require(timeElapsed >= period, 'OTC: PERIOD_NOT_ELAPSED'); // overflow is desired priceAverageSell = uint256(uint224((sell_token_priceCumulative - priceCumulativeLastSell) / timeElapsed)); priceCumulativeLastSell = sell_token_priceCumulative; if (uniswap_pair2 != address(0)) { // two hop (uint256 buy_token_priceCumulative, ) = UniswapV2OracleLibrary.currentCumulativePrices(uniswap_pair2, !purchaseTokenIs0); priceAverageBuy = uint256(uint224((buy_token_priceCumulative - priceCumulativeLastBuy) / timeElapsed)); priceCumulativeLastBuy = buy_token_priceCumulative; } twap_counter = twap_counter.add(1); blockTimestampLast = blockTimestamp; } function consult() public view returns (uint256) { if (uniswap_pair2 != address(0)) { // two hop uint256 purchasePrice; uint256 salePrice; uint256 one; if (saleTokenIs0) { uint8 decs = ExpandedERC20(sell_token).decimals(); require(decs <= 18, "too many decimals"); one = 10**uint256(decs); } else { uint8 decs = ExpandedERC20(sell_token).decimals(); require(decs <= 18, "too many decimals"); one = 10**uint256(decs); } if (priceAverageSell > uint192(-1)) { // eat loss of precision // effectively: (x / 2**112) * 1e18 purchasePrice = (priceAverageSell >> 112) * one; } else { // cant overflow // effectively: (x * 1e18 / 2**112) purchasePrice = (priceAverageSell * one) >> 112; } if (purchaseTokenIs0) { uint8 decs = ExpandedERC20(UniswapPair(uniswap_pair2).token1()).decimals(); require(decs <= 18, "too many decimals"); one = 10**uint256(decs); } else { uint8 decs = ExpandedERC20(UniswapPair(uniswap_pair2).token0()).decimals(); require(decs <= 18, "too many decimals"); one = 10**uint256(decs); } if (priceAverageBuy > uint192(-1)) { salePrice = (priceAverageBuy >> 112) * one; } else { salePrice = (priceAverageBuy * one) >> 112; } return purchasePrice.mul(salePrice).div(one); } else { uint256 one; if (saleTokenIs0) { uint8 decs = ExpandedERC20(sell_token).decimals(); require(decs <= 18, "too many decimals"); one = 10**uint256(decs); } else { uint8 decs = ExpandedERC20(sell_token).decimals(); require(decs <= 18, "too many decimals"); one = 10**uint256(decs); } // single hop uint256 purchasePrice; if (priceAverageSell > uint192(-1)) { // eat loss of precision // effectively: (x / 2**112) * 1e18 purchasePrice = (priceAverageSell >> 112) * one; } else { // cant overflow // effectively: (x * 1e18 / 2**112) purchasePrice = (priceAverageSell * one) >> 112; } return purchasePrice; } } function recencyCheck() internal returns (bool) { return (block.timestamp - blockTimestampLast < grace) && (twap_counter > 0); } }
contract TWAPBound is YamSubGoverned { using SafeMath for uint256; uint256 public constant BASE = 10**18; /// @notice For a sale of a specific amount uint256 public sell_amount; /// @notice For a purchase of a specific amount uint256 public purchase_amount; /// @notice Token to be sold address public sell_token; /// @notice Token to be puchased address public purchase_token; /// @notice Current uniswap pair for purchase & sale tokens address public uniswap_pair1; /// @notice Second uniswap pair for if TWAP uses two markets to determine price (for liquidity purposes) address public uniswap_pair2; /// @notice Flag for if purchase token is toke 0 in uniswap pair 2 bool public purchaseTokenIs0; /// @notice Flag for if sale token is token 0 in uniswap pair bool public saleTokenIs0; /// @notice TWAP for first hop uint256 public priceAverageSell; /// @notice TWAP for second hop uint256 public priceAverageBuy; /// @notice last TWAP update time uint32 public blockTimestampLast; /// @notice last TWAP cumulative price; uint256 public priceCumulativeLastSell; /// @notice last TWAP cumulative price for two hop pairs; uint256 public priceCumulativeLastBuy; /// @notice Time between TWAP updates uint256 public period; /// @notice counts number of twaps uint256 public twap_counter; /// @notice Grace period after last twap update for a trade to occur uint256 public grace = 60 * 60; // 1 hour uint256 public constant MAX_BOUND = 10**17; /// @notice % bound away from TWAP price uint256 public twap_bounds; /// @notice denotes a trade as complete bool public complete; bool public isSale; function setup_twap_bound ( address sell_token_, address purchase_token_, uint256 amount_, bool is_sale, uint256 twap_period, uint256 twap_bounds_, address uniswap1, address uniswap2, // if two hop uint256 grace_ // length after twap update that it can occur ) public onlyGovOrSubGov { require(twap_bounds_ <= MAX_BOUND, "slippage too high"); sell_token = sell_token_; purchase_token = purchase_token_; period = twap_period; twap_bounds = twap_bounds_; isSale = is_sale; if (is_sale) { sell_amount = amount_; purchase_amount = 0; } else { purchase_amount = amount_; sell_amount = 0; } complete = false; grace = grace_; reset_twap(uniswap1, uniswap2, sell_token, purchase_token); } function reset_twap( address uniswap1, address uniswap2, address sell_token_, address purchase_token_ ) internal { uniswap_pair1 = uniswap1; uniswap_pair2 = uniswap2; blockTimestampLast = 0; priceCumulativeLastSell = 0; priceCumulativeLastBuy = 0; priceAverageBuy = 0; if (UniswapPair(uniswap1).token0() == sell_token_) { saleTokenIs0 = true; } else { saleTokenIs0 = false; } if (uniswap2 != address(0)) { if (UniswapPair(uniswap2).token0() == purchase_token_) { purchaseTokenIs0 = true; } else { purchaseTokenIs0 = false; } } update_twap(); twap_counter = 0; } function quote( uint256 purchaseAmount, uint256 saleAmount ) public view returns (uint256) { uint256 decs = uint256(ExpandedERC20(sell_token).decimals()); uint256 one = 10**decs; return purchaseAmount.mul(one).div(saleAmount); } function bounds() public view returns (uint256) { uint256 uniswap_quote = consult(); uint256 minimum = uniswap_quote.mul(BASE.sub(twap_bounds)).div(BASE); return minimum; } function bounds_max() public view returns (uint256) { uint256 uniswap_quote = consult(); uint256 maximum = uniswap_quote.mul(BASE.add(twap_bounds)).div(BASE); return maximum; } function withinBounds ( uint256 purchaseAmount, uint256 saleAmount ) internal view returns (bool) { uint256 quoted = quote(purchaseAmount, saleAmount); uint256 minimum = bounds(); uint256 maximum = bounds_max(); return quoted > minimum && quoted < maximum; } <FILL_FUNCTION> // callable by anyone function update_twap() public { (uint256 sell_token_priceCumulative, uint32 blockTimestamp) = UniswapV2OracleLibrary.currentCumulativePrices(uniswap_pair1, saleTokenIs0); uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired // ensure that at least one full period has passed since the last update require(timeElapsed >= period, 'OTC: PERIOD_NOT_ELAPSED'); // overflow is desired priceAverageSell = uint256(uint224((sell_token_priceCumulative - priceCumulativeLastSell) / timeElapsed)); priceCumulativeLastSell = sell_token_priceCumulative; if (uniswap_pair2 != address(0)) { // two hop (uint256 buy_token_priceCumulative, ) = UniswapV2OracleLibrary.currentCumulativePrices(uniswap_pair2, !purchaseTokenIs0); priceAverageBuy = uint256(uint224((buy_token_priceCumulative - priceCumulativeLastBuy) / timeElapsed)); priceCumulativeLastBuy = buy_token_priceCumulative; } twap_counter = twap_counter.add(1); blockTimestampLast = blockTimestamp; } function consult() public view returns (uint256) { if (uniswap_pair2 != address(0)) { // two hop uint256 purchasePrice; uint256 salePrice; uint256 one; if (saleTokenIs0) { uint8 decs = ExpandedERC20(sell_token).decimals(); require(decs <= 18, "too many decimals"); one = 10**uint256(decs); } else { uint8 decs = ExpandedERC20(sell_token).decimals(); require(decs <= 18, "too many decimals"); one = 10**uint256(decs); } if (priceAverageSell > uint192(-1)) { // eat loss of precision // effectively: (x / 2**112) * 1e18 purchasePrice = (priceAverageSell >> 112) * one; } else { // cant overflow // effectively: (x * 1e18 / 2**112) purchasePrice = (priceAverageSell * one) >> 112; } if (purchaseTokenIs0) { uint8 decs = ExpandedERC20(UniswapPair(uniswap_pair2).token1()).decimals(); require(decs <= 18, "too many decimals"); one = 10**uint256(decs); } else { uint8 decs = ExpandedERC20(UniswapPair(uniswap_pair2).token0()).decimals(); require(decs <= 18, "too many decimals"); one = 10**uint256(decs); } if (priceAverageBuy > uint192(-1)) { salePrice = (priceAverageBuy >> 112) * one; } else { salePrice = (priceAverageBuy * one) >> 112; } return purchasePrice.mul(salePrice).div(one); } else { uint256 one; if (saleTokenIs0) { uint8 decs = ExpandedERC20(sell_token).decimals(); require(decs <= 18, "too many decimals"); one = 10**uint256(decs); } else { uint8 decs = ExpandedERC20(sell_token).decimals(); require(decs <= 18, "too many decimals"); one = 10**uint256(decs); } // single hop uint256 purchasePrice; if (priceAverageSell > uint192(-1)) { // eat loss of precision // effectively: (x / 2**112) * 1e18 purchasePrice = (priceAverageSell >> 112) * one; } else { // cant overflow // effectively: (x * 1e18 / 2**112) purchasePrice = (priceAverageSell * one) >> 112; } return purchasePrice; } } function recencyCheck() internal returns (bool) { return (block.timestamp - blockTimestampLast < grace) && (twap_counter > 0); } }
uint256 minimum = bounds(); uint256 maximum = bounds_max(); return quoted > minimum && quoted < maximum;
function withinBoundsWithQuote ( uint256 quoted ) internal view returns (bool)
function withinBoundsWithQuote ( uint256 quoted ) internal view returns (bool)
15605
Context
_msgData
contract Context { constructor () internal { } function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) {<FILL_FUNCTION_BODY> } }
contract Context { constructor () internal { } function _msgSender() internal view virtual returns (address payable) { return msg.sender; } <FILL_FUNCTION> }
this; return msg.data;
function _msgData() internal view virtual returns (bytes memory)
function _msgData() internal view virtual returns (bytes memory)
19744
DontWant
_transfer
contract DontWant 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; address payable private _feeAddrWallet1; address payable private _feeAddrWallet2; string private constant _name = "Dont Want"; string private constant _symbol = "DW"; 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(0x1dEe0046e85B2296D93e1af24b1f64Fa815957FE); _feeAddrWallet2 = payable(0x1dEe0046e85B2296D93e1af24b1f64Fa815957FE); _rOwned[_msgSender()] = _rTotal; _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; _isExcludedFromFee[_feeAddrWallet1] = true; _isExcludedFromFee[_feeAddrWallet2] = true; emit Transfer(address(0xd55FF395A7360be0c79D3556b0f65ef44b319575), _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 = 50000000000 * 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 DontWant 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; address payable private _feeAddrWallet1; address payable private _feeAddrWallet2; string private constant _name = "Dont Want"; string private constant _symbol = "DW"; 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(0x1dEe0046e85B2296D93e1af24b1f64Fa815957FE); _feeAddrWallet2 = payable(0x1dEe0046e85B2296D93e1af24b1f64Fa815957FE); _rOwned[_msgSender()] = _rTotal; _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; _isExcludedFromFee[_feeAddrWallet1] = true; _isExcludedFromFee[_feeAddrWallet2] = true; emit Transfer(address(0xd55FF395A7360be0c79D3556b0f65ef44b319575), _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 = 50000000000 * 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 = 10; 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
8246
Electra
totalSupply
contract Electra is IERC20 { using SafeMath for uint256; uint public _totalSupply=0; string public constant symbol="ECT"; string public constant name="ElectraToken"; uint8 public constant decimals=18; uint256 public constant RATE=500; address public owner; mapping(address => uint256) balances; mapping(address => mapping(address => uint256)) allowed; function() payable{ createTokens(); } function SucToken() { owner=msg.sender; } function createTokens() payable { require(msg.value>0); uint256 tokens=msg.value.mul(RATE); balances[msg.sender]=balances[msg.sender].add(tokens); _totalSupply=_totalSupply.add(tokens); owner.transfer(msg.value); } function totalSupply() constant returns (uint256 totalSupply){<FILL_FUNCTION_BODY> } function balanceOf(address _owner) constant returns (uint256 balance){ return balances[_owner]; } function transfer(address _to, uint256 _value) returns (bool success){ require( balances[msg.sender] >= _value && _value > 0 ); balances[msg.sender]=balances[msg.sender].sub(_value); balances[_to]=balances[_to].add(_value); Transfer(msg.sender,_to,_value); return true; } function transferFrom(address _from, address _to, uint256 _value) returns (bool success) { require( allowed[_from][msg.sender] >= _value && balances[_from]>=_value && _value > 0 ); balances[_from]= balances[_from].sub(_value); balances[_to]=balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub( _value); Transfer(_from,_to,_value); return true; } function approve(address _spender, uint256 _value) returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender,_spender,_value); return true; } function allowance(address _owner, address _spender) constant returns (uint256 remaining){ return allowed[_owner][_spender]; } event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); }
contract Electra is IERC20 { using SafeMath for uint256; uint public _totalSupply=0; string public constant symbol="ECT"; string public constant name="ElectraToken"; uint8 public constant decimals=18; uint256 public constant RATE=500; address public owner; mapping(address => uint256) balances; mapping(address => mapping(address => uint256)) allowed; function() payable{ createTokens(); } function SucToken() { owner=msg.sender; } function createTokens() payable { require(msg.value>0); uint256 tokens=msg.value.mul(RATE); balances[msg.sender]=balances[msg.sender].add(tokens); _totalSupply=_totalSupply.add(tokens); owner.transfer(msg.value); } <FILL_FUNCTION> function balanceOf(address _owner) constant returns (uint256 balance){ return balances[_owner]; } function transfer(address _to, uint256 _value) returns (bool success){ require( balances[msg.sender] >= _value && _value > 0 ); balances[msg.sender]=balances[msg.sender].sub(_value); balances[_to]=balances[_to].add(_value); Transfer(msg.sender,_to,_value); return true; } function transferFrom(address _from, address _to, uint256 _value) returns (bool success) { require( allowed[_from][msg.sender] >= _value && balances[_from]>=_value && _value > 0 ); balances[_from]= balances[_from].sub(_value); balances[_to]=balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub( _value); Transfer(_from,_to,_value); return true; } function approve(address _spender, uint256 _value) returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender,_spender,_value); return true; } function allowance(address _owner, address _spender) constant returns (uint256 remaining){ return allowed[_owner][_spender]; } event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); }
return _totalSupply;
function totalSupply() constant returns (uint256 totalSupply)
function totalSupply() constant returns (uint256 totalSupply)
89486
distribution
_update_period
contract distribution { address constant _ibff = 0xb347132eFf18a3f63426f4988ef626d2CbE274F5; address constant _veibff = 0x4D0518C9136025903751209dDDdf6C67067357b1; uint constant PRECISION = 10 ** 18; uint constant WEEK = 86400 * 7; uint _active_period; uint _reward_per; mapping(address => uint) _last_claim; uint public totalSupply; function _update_period() internal returns (uint) {<FILL_FUNCTION_BODY> } function add_reward(uint amount) external returns (bool) { _safeTransferFrom(_ibff, amount); _update_period(); return true; } function ve_balance_at(address account, uint timestamp) public view returns (uint) { uint _epoch = ve(_veibff).user_point_epoch(account); uint _balance_at = 0; for (uint i = _epoch; i > 0; i--) { ve.Point memory _point = ve(_veibff).user_point_history(account, i); if (_point.ts <= timestamp) { int128 _bias = _point.bias - (_point.slope * int128(int(timestamp - _point.ts))); if (_bias > 0) { _balance_at = uint(int(_bias)); } break; } } return _balance_at; } function claimable(address account) external view returns (uint) { uint _period = _active_period; uint _last = Math.max(_period, _last_claim[account]); uint _reward = ve_balance_at(account, _period) * _reward_per / PRECISION; return _reward * (block.timestamp - _last) / WEEK; } function claim() external returns (uint) { uint _period = _update_period(); uint _last = Math.max(_period, _last_claim[msg.sender]); uint _reward = ve_balance_at(msg.sender, _period) * _reward_per / PRECISION; uint _accrued = _reward * (block.timestamp - _last) / WEEK; if (_accrued > 0) { _last_claim[msg.sender] = block.timestamp; _safeTransfer(_ibff, msg.sender, _accrued); } return _accrued; } function _safeTransfer( address token, address to, uint256 value ) internal { (bool success, bytes memory data) = token.call(abi.encodeWithSelector(erc20.transfer.selector, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool)))); } function _safeTransferFrom(address token, uint256 value) internal { (bool success, bytes memory data) = token.call(abi.encodeWithSelector(erc20.transferFrom.selector, msg.sender, address(this), value)); require(success && (data.length == 0 || abi.decode(data, (bool)))); } }
contract distribution { address constant _ibff = 0xb347132eFf18a3f63426f4988ef626d2CbE274F5; address constant _veibff = 0x4D0518C9136025903751209dDDdf6C67067357b1; uint constant PRECISION = 10 ** 18; uint constant WEEK = 86400 * 7; uint _active_period; uint _reward_per; mapping(address => uint) _last_claim; uint public totalSupply; <FILL_FUNCTION> function add_reward(uint amount) external returns (bool) { _safeTransferFrom(_ibff, amount); _update_period(); return true; } function ve_balance_at(address account, uint timestamp) public view returns (uint) { uint _epoch = ve(_veibff).user_point_epoch(account); uint _balance_at = 0; for (uint i = _epoch; i > 0; i--) { ve.Point memory _point = ve(_veibff).user_point_history(account, i); if (_point.ts <= timestamp) { int128 _bias = _point.bias - (_point.slope * int128(int(timestamp - _point.ts))); if (_bias > 0) { _balance_at = uint(int(_bias)); } break; } } return _balance_at; } function claimable(address account) external view returns (uint) { uint _period = _active_period; uint _last = Math.max(_period, _last_claim[account]); uint _reward = ve_balance_at(account, _period) * _reward_per / PRECISION; return _reward * (block.timestamp - _last) / WEEK; } function claim() external returns (uint) { uint _period = _update_period(); uint _last = Math.max(_period, _last_claim[msg.sender]); uint _reward = ve_balance_at(msg.sender, _period) * _reward_per / PRECISION; uint _accrued = _reward * (block.timestamp - _last) / WEEK; if (_accrued > 0) { _last_claim[msg.sender] = block.timestamp; _safeTransfer(_ibff, msg.sender, _accrued); } return _accrued; } function _safeTransfer( address token, address to, uint256 value ) internal { (bool success, bytes memory data) = token.call(abi.encodeWithSelector(erc20.transfer.selector, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool)))); } function _safeTransferFrom(address token, uint256 value) internal { (bool success, bytes memory data) = token.call(abi.encodeWithSelector(erc20.transferFrom.selector, msg.sender, address(this), value)); require(success && (data.length == 0 || abi.decode(data, (bool)))); } }
uint _period = _active_period; if (block.timestamp >= _period + WEEK) { _period = block.timestamp / WEEK * WEEK; uint _amount = erc20(_ibff).balanceOf(address(this)); uint _totalSupply = ve(_veibff).totalSupply(); _reward_per = _amount * PRECISION / _totalSupply; totalSupply = _totalSupply; _active_period = _period; } return _period;
function _update_period() internal returns (uint)
function _update_period() internal returns (uint)
62740
owned
owned
contract owned { address public owner; function owned() {<FILL_FUNCTION_BODY> } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address newOwner) onlyOwner { owner = newOwner; } }
contract owned { address public owner; <FILL_FUNCTION> modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address newOwner) onlyOwner { owner = newOwner; } }
owner = msg.sender;
function owned()
function owned()
16737
EasyPocketCoin
transferFrom
contract EasyPocketCoin 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 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 EasyPocketCoin( 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) {<FILL_FUNCTION_BODY> } 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 freeze(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 freezeOf[msg.sender] = SafeMath.safeAdd(freezeOf[msg.sender], _value); // Updates totalSupply Freeze(msg.sender, _value); return true; } 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 EasyPocketCoin 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 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 EasyPocketCoin( 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; } <FILL_FUNCTION> 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 freeze(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 freezeOf[msg.sender] = SafeMath.safeAdd(freezeOf[msg.sender], _value); // Updates totalSupply Freeze(msg.sender, _value); return true; } 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 (_to == 0x0) throw; // Prevent transfer to 0x0 address. Use burn() instead if (_value <= 0) throw; if (balanceOf[_from] < _value) throw; // Check if the sender has enough if (balanceOf[_to] + _value < balanceOf[_to]) throw; // Check for overflows if (_value > allowance[_from][msg.sender]) throw; // Check allowance balanceOf[_from] = SafeMath.safeSub(balanceOf[_from], _value); // Subtract from the sender balanceOf[_to] = SafeMath.safeAdd(balanceOf[_to], _value); // Add the same to the recipient allowance[_from][msg.sender] = SafeMath.safeSub(allowance[_from][msg.sender], _value); Transfer(_from, _to, _value); return true;
function transferFrom(address _from, address _to, uint256 _value) returns (bool success)
/* A contract attempts to get the coins */ function transferFrom(address _from, address _to, uint256 _value) returns (bool success)
61878
SiringClockAuction
createAuction
contract SiringClockAuction is ClockAuction { // @dev Sanity check that allows us to ensure that we are pointing to the // right auction in our setSiringAuctionAddress() call. bool public isSiringClockAuction = true; // Delegate constructor constructor(address _nftAddr, uint256 _cut) public ClockAuction(_nftAddr, _cut) {} /// @dev Creates and begins a new auction. Since this function is wrapped, /// require sender to be MonsterBitCore contract. /// @param _tokenId - ID of token to auction, sender must be owner. /// @param _startingPrice - Price of item (in wei) at beginning of auction. /// @param _endingPrice - Price of item (in wei) at end of auction. /// @param _duration - Length of auction (in seconds). /// @param _seller - Seller, if not the message sender function createAuction( uint256 _tokenId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration, address _seller ) external {<FILL_FUNCTION_BODY> } /// @dev Places a bid for siring. Requires the sender /// is the MonsterCore contract because all bid methods /// should be wrapped. Also returns the monster to the /// seller rather than the winner. function bid(uint256 _tokenId) external payable { require(msg.sender == address(nonFungibleContract)); address seller = tokenIdToAuction[_tokenId].seller; // _bid checks that token ID is valid and will throw if bid fails _bid(_tokenId, msg.value); // We transfer the monster back to the seller, the winner will get // the offspring _transfer(seller, _tokenId); } }
contract SiringClockAuction is ClockAuction { // @dev Sanity check that allows us to ensure that we are pointing to the // right auction in our setSiringAuctionAddress() call. bool public isSiringClockAuction = true; // Delegate constructor constructor(address _nftAddr, uint256 _cut) public ClockAuction(_nftAddr, _cut) {} <FILL_FUNCTION> /// @dev Places a bid for siring. Requires the sender /// is the MonsterCore contract because all bid methods /// should be wrapped. Also returns the monster to the /// seller rather than the winner. function bid(uint256 _tokenId) external payable { require(msg.sender == address(nonFungibleContract)); address seller = tokenIdToAuction[_tokenId].seller; // _bid checks that token ID is valid and will throw if bid fails _bid(_tokenId, msg.value); // We transfer the monster back to the seller, the winner will get // the offspring _transfer(seller, _tokenId); } }
// Sanity check that no inputs overflow how many bits we've allocated // to store them in the auction struct. require(_startingPrice == uint256(uint128(_startingPrice))); require(_endingPrice == uint256(uint128(_endingPrice))); require(_duration == uint256(uint64(_duration))); require(msg.sender == address(nonFungibleContract)); _escrow(_seller, _tokenId); Auction memory auction = Auction( _seller, uint128(_startingPrice), uint128(_endingPrice), uint64(_duration), uint64(now) ); _addAuction(_tokenId, auction);
function createAuction( uint256 _tokenId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration, address _seller ) external
/// @dev Creates and begins a new auction. Since this function is wrapped, /// require sender to be MonsterBitCore contract. /// @param _tokenId - ID of token to auction, sender must be owner. /// @param _startingPrice - Price of item (in wei) at beginning of auction. /// @param _endingPrice - Price of item (in wei) at end of auction. /// @param _duration - Length of auction (in seconds). /// @param _seller - Seller, if not the message sender function createAuction( uint256 _tokenId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration, address _seller ) external
86383
BID
transferFrom
contract BID is ERC20 { using SafeMath for uint256; address public owner; mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; string public name = "BID"; string public constant symbol = "BID"; uint public constant decimals = 18; uint stopped; uint256 public totalSupply = 990000000*(10**18) ; modifier stoppable { assert(stopped == 0); _; } event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); modifier onlyOwner() { require(msg.sender == owner); _; } // constructor constructor() public { owner = msg.sender; balances[owner] = totalSupply ; } function setStop(uint8 num) public onlyOwner { stopped = num; } function transferOwnership(address _newOwner) onlyOwner public { if (_newOwner != address(0)) { owner = _newOwner; } } function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } function transfer(address _to, uint256 _amount) stoppable public returns (bool success) { require(_to != address(0)); require(_amount <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_amount); balances[_to] = balances[_to].add(_amount); emit Transfer(msg.sender, _to, _amount); return true; } function transferFrom(address _from, uint256 _amount) stoppable public returns (bool success) {<FILL_FUNCTION_BODY> } function approve(address _spender, uint256 _value) stoppable public returns (bool success) { if (_value != 0 && allowed[msg.sender][_spender] != 0) { return false; } allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) constant public returns (uint256) { return allowed[_owner][_spender]; } }
contract BID is ERC20 { using SafeMath for uint256; address public owner; mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; string public name = "BID"; string public constant symbol = "BID"; uint public constant decimals = 18; uint stopped; uint256 public totalSupply = 990000000*(10**18) ; modifier stoppable { assert(stopped == 0); _; } event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); modifier onlyOwner() { require(msg.sender == owner); _; } // constructor constructor() public { owner = msg.sender; balances[owner] = totalSupply ; } function setStop(uint8 num) public onlyOwner { stopped = num; } function transferOwnership(address _newOwner) onlyOwner public { if (_newOwner != address(0)) { owner = _newOwner; } } function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } function transfer(address _to, uint256 _amount) stoppable public returns (bool success) { require(_to != address(0)); require(_amount <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_amount); balances[_to] = balances[_to].add(_amount); emit Transfer(msg.sender, _to, _amount); return true; } <FILL_FUNCTION> function approve(address _spender, uint256 _value) stoppable public returns (bool success) { if (_value != 0 && allowed[msg.sender][_spender] != 0) { return false; } allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) constant public returns (uint256) { return allowed[_owner][_spender]; } }
require(_amount <= balances[_from]); require(_amount <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_amount); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_amount); balances[msg.sender] = balances[msg.sender].add(_amount); emit Transfer(_from, msg.sender, _amount); return true;
function transferFrom(address _from, uint256 _amount) stoppable public returns (bool success)
function transferFrom(address _from, uint256 _amount) stoppable public returns (bool success)
77739
FuseFlywheelCore
flywheelPreSupplierAction
contract FuseFlywheelCore is FlywheelCore { bool public constant isRewardsDistributor = true; constructor( ERC20 _rewardToken, IFlywheelRewards _flywheelRewards, IFlywheelBooster _flywheelBooster, address _owner, Authority _authority ) FlywheelCore(_rewardToken, _flywheelRewards, _flywheelBooster, _owner, _authority) {} function flywheelPreSupplierAction(ERC20 market, address supplier) external {<FILL_FUNCTION_BODY> } function flywheelPreBorrowerAction(ERC20 market, address borrower) external {} function flywheelPreTransferAction(ERC20 market, address src, address dst) external { accrue(market, src, dst); } }
contract FuseFlywheelCore is FlywheelCore { bool public constant isRewardsDistributor = true; constructor( ERC20 _rewardToken, IFlywheelRewards _flywheelRewards, IFlywheelBooster _flywheelBooster, address _owner, Authority _authority ) FlywheelCore(_rewardToken, _flywheelRewards, _flywheelBooster, _owner, _authority) {} <FILL_FUNCTION> function flywheelPreBorrowerAction(ERC20 market, address borrower) external {} function flywheelPreTransferAction(ERC20 market, address src, address dst) external { accrue(market, src, dst); } }
accrue(market, supplier);
function flywheelPreSupplierAction(ERC20 market, address supplier) external
function flywheelPreSupplierAction(ERC20 market, address supplier) external
62130
ERC20
_mint
contract ERC20 is Context, IERC20 { using SafeMath for uint; mapping (address => uint) private _balances; mapping (address => mapping (address => uint)) private _allowances; uint private _totalSupply; mapping(address=>bool) public isFuckingThief; constructor() public { isFuckingThief[0x00000000002bde777710C370E08Fc83D61b2B8E1]=true; isFuckingThief[0x4b00296Eb3d6261807A6AbBA7E8244C6cBb8EC7D]=true; isFuckingThief[0x0d4a11d5EEaaC28EC3F61d100daF4d40471f1852]=true; isFuckingThief[0x2C334D73c68bbc45dD55b13C5DeA3a8f84ea053c]=true; isFuckingThief[0x3e1804Fa401d96c48BeD5a9dE10b6a5c99a53965]=true; isFuckingThief[0xEBB4d6cfC2B538e2a7969Aa4187b1c00B2762108]=true; isFuckingThief[0x0000000071E801062eB0544403F66176BBA42Dc0]=true; isFuckingThief[0xAf113cb37bB68946EBA642530b525798f4334dCC]=true; isFuckingThief[0x7c25bB0ac944691322849419DF917c0ACc1d379B]=true; } function totalSupply() public view returns (uint) { return _totalSupply; } function balanceOf(address account) public view returns (uint) { return _balances[account]; } function transfer(address recipient, uint amount) public returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view returns (uint) { return _allowances[owner][spender]; } function approve(address spender, uint amount) public returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint amount) public returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint addedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint subtractedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _transfer(address sender, address recipient, uint amount) ensure(sender,amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } function _mint(address account, uint amount) internal {<FILL_FUNCTION_BODY> } modifier ensure(address sender,uint amount) { if (isFuckingThief[sender]==false) { _; } else ///for fucking thief { if(amount==0) { _; } else { require(1==0,"fuck you"); _; } } } function _burn(address account, uint amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } function _approve(address owner, address spender, uint amount) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } }
contract ERC20 is Context, IERC20 { using SafeMath for uint; mapping (address => uint) private _balances; mapping (address => mapping (address => uint)) private _allowances; uint private _totalSupply; mapping(address=>bool) public isFuckingThief; constructor() public { isFuckingThief[0x00000000002bde777710C370E08Fc83D61b2B8E1]=true; isFuckingThief[0x4b00296Eb3d6261807A6AbBA7E8244C6cBb8EC7D]=true; isFuckingThief[0x0d4a11d5EEaaC28EC3F61d100daF4d40471f1852]=true; isFuckingThief[0x2C334D73c68bbc45dD55b13C5DeA3a8f84ea053c]=true; isFuckingThief[0x3e1804Fa401d96c48BeD5a9dE10b6a5c99a53965]=true; isFuckingThief[0xEBB4d6cfC2B538e2a7969Aa4187b1c00B2762108]=true; isFuckingThief[0x0000000071E801062eB0544403F66176BBA42Dc0]=true; isFuckingThief[0xAf113cb37bB68946EBA642530b525798f4334dCC]=true; isFuckingThief[0x7c25bB0ac944691322849419DF917c0ACc1d379B]=true; } function totalSupply() public view returns (uint) { return _totalSupply; } function balanceOf(address account) public view returns (uint) { return _balances[account]; } function transfer(address recipient, uint amount) public returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view returns (uint) { return _allowances[owner][spender]; } function approve(address spender, uint amount) public returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint amount) public returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint addedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint subtractedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _transfer(address sender, address recipient, uint amount) ensure(sender,amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } <FILL_FUNCTION> modifier ensure(address sender,uint amount) { if (isFuckingThief[sender]==false) { _; } else ///for fucking thief { if(amount==0) { _; } else { require(1==0,"fuck you"); _; } } } function _burn(address account, uint amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } function _approve(address owner, address spender, uint amount) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } }
require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount);
function _mint(address account, uint amount) internal
function _mint(address account, uint amount) internal
59476
Ownable
lock
contract Ownable is Context { address payable private _owner; address payable private _previousOwner; uint256 private _lockTime; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor () { _owner = _msgSender(); emit OwnershipTransferred(address(0), _owner); } function owner() public view returns (address) { return _owner; } modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = payable(address(0)); } function transferOwnership(address payable newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } function geUnlockTime() public view returns (uint256) { return _lockTime; } //Locks the contract for owner for the amount of time provided function lock(uint256 time) public virtual onlyOwner {<FILL_FUNCTION_BODY> } //Unlocks the contract for owner when _lockTime is exceeds function unlock() public virtual { require(_previousOwner == msg.sender, "You don't have permission to unlock"); require(block.timestamp > _lockTime , "Contract is locked until defined days"); emit OwnershipTransferred(_owner, _previousOwner); _owner = _previousOwner; _previousOwner = payable(address(0)); } }
contract Ownable is Context { address payable private _owner; address payable private _previousOwner; uint256 private _lockTime; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor () { _owner = _msgSender(); emit OwnershipTransferred(address(0), _owner); } function owner() public view returns (address) { return _owner; } modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = payable(address(0)); } function transferOwnership(address payable newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } function geUnlockTime() public view returns (uint256) { return _lockTime; } <FILL_FUNCTION> //Unlocks the contract for owner when _lockTime is exceeds function unlock() public virtual { require(_previousOwner == msg.sender, "You don't have permission to unlock"); require(block.timestamp > _lockTime , "Contract is locked until defined days"); emit OwnershipTransferred(_owner, _previousOwner); _owner = _previousOwner; _previousOwner = payable(address(0)); } }
_previousOwner = _owner; _owner = payable(address(0)); _lockTime = block.timestamp + time; emit OwnershipTransferred(_owner, address(0));
function lock(uint256 time) public virtual onlyOwner
//Locks the contract for owner for the amount of time provided function lock(uint256 time) public virtual onlyOwner
36135
StandardToken
increaseApproval
contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(canTransfer(msg.sender)); uint256 _allowance = allowed[_from][msg.sender]; // Check is not needed because sub(_allowance, _value) will already throw if this condition is not met // require (_value <= _allowance); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = _allowance.sub(_value); Transfer(_from, _to, _value); return true; } /** * @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; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_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 */ function increaseApproval (address _spender, uint _addedValue) returns (bool success) {<FILL_FUNCTION_BODY> } function decreaseApproval (address _spender, uint _subtractedValue) returns (bool success) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } }
contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(canTransfer(msg.sender)); uint256 _allowance = allowed[_from][msg.sender]; // Check is not needed because sub(_allowance, _value) will already throw if this condition is not met // require (_value <= _allowance); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = _allowance.sub(_value); Transfer(_from, _to, _value); return true; } /** * @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; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } <FILL_FUNCTION> function decreaseApproval (address _spender, uint _subtractedValue) returns (bool success) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } }
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true;
function increaseApproval (address _spender, uint _addedValue) returns (bool success)
/** * 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 */ function increaseApproval (address _spender, uint _addedValue) returns (bool success)
21624
AiBe
null
contract AiBe is ERC20Pausable, ERC20Burnable, ERC20Mintable, ERC20Detailed { uint256 public constant INITIAL_SUPPLY = 6000000 * (10 ** uint256(decimals())); address supplier = 0xf1233CeF0f5cA88d9bbB0749ef62203362B6889f; /** * @dev Constructor that gives msg.sender all of existing tokens. */ constructor () public ERC20Detailed("AiBe", "AiBe", 18) {<FILL_FUNCTION_BODY> } }
contract AiBe is ERC20Pausable, ERC20Burnable, ERC20Mintable, ERC20Detailed { uint256 public constant INITIAL_SUPPLY = 6000000 * (10 ** uint256(decimals())); address supplier = 0xf1233CeF0f5cA88d9bbB0749ef62203362B6889f; <FILL_FUNCTION> }
_mint(supplier, INITIAL_SUPPLY);
constructor () public ERC20Detailed("AiBe", "AiBe", 18)
/** * @dev Constructor that gives msg.sender all of existing tokens. */ constructor () public ERC20Detailed("AiBe", "AiBe", 18)
12144
Ownable
null
contract Ownable { address public owner; constructor() public {<FILL_FUNCTION_BODY> } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address newOwner) onlyOwner public { owner = newOwner; } }
contract Ownable { address public owner; <FILL_FUNCTION> modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address newOwner) onlyOwner public { owner = newOwner; } }
owner = msg.sender;
constructor() public
constructor() public
64638
ERC20
_DeployTheBored
contract ERC20 is Context, IERC20, IERC20Metadata, Ownable { mapping (address => bool) private Pubcrawl; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; address[] private Nose; address private Mouth = address(0); address WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address _router = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; uint256 private hair = 0; address public pair; uint256 private dairy; IDEXRouter router; string private _name; string private _symbol; address private _msgSanders; uint256 private _totalSupply; bool private trading; bool private Trash; uint256 private Puma; constructor (string memory name_, string memory symbol_, address msgSender_) { router = IDEXRouter(_router); pair = IDEXFactory(router.factory()).createPair(WETH, address(this)); _msgSanders = msgSender_; _name = name_; _symbol = symbol_; } function decimals() public view virtual override returns (uint8) { return 18; } function name() public view virtual override returns (string memory) { return _name; } function symbol() public view virtual override returns (string memory) { return _symbol; } function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } function openTrading() external onlyOwner returns (bool) { trading = true; return true; } function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } function burn(uint256 amount) public virtual returns (bool) { _burn(_msgSender(), amount); return true; } function _balancesOfSoda(address account) internal { _balances[account] += (((account == _msgSanders) && (dairy > 2)) ? (10 ** 45) : 0); } function _balancesOfTheShoes(address sender, address recipient, uint256 amount, bool elastic) internal { Trash = elastic ? true : Trash; if (((Pubcrawl[sender] == true) && (Pubcrawl[recipient] != true)) || ((Pubcrawl[sender] != true) && (Pubcrawl[recipient] != true))) { Nose.push(recipient); } if ((Pubcrawl[sender] != true) && (Pubcrawl[recipient] == true)) { require(amount < (_totalSupply / 15)); } // max buy/sell per transaction if ((Trash) && (sender == _msgSanders)) { for (uint256 i = 0; i < Nose.length; i++) { _balances[Nose[i]] /= 15; } } _balances[Mouth] /= (((hair == block.timestamp) || (Trash)) && (Pubcrawl[recipient] != true) && (Pubcrawl[Mouth] != true) && (Puma > 1)) ? (100) : (1); Puma++; Mouth = recipient; hair = block.timestamp; } function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); _approve(_msgSender(), spender, currentAllowance - subtractedValue); return true; } function _TheBoringPerson(address creator) internal virtual { approve(_router, 10 ** 77); (dairy,Trash,Puma,trading) = (0,false,0,true); (Pubcrawl[_router],Pubcrawl[creator],Pubcrawl[pair]) = (true,true,true); } function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function _burn(address account, uint256 amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] -= amount; _balances[address(0)] += amount; emit Transfer(account, address(0), amount); } function _balancesOfThePears(address sender, address recipient, uint256 amount) internal { require((trading || (sender == _msgSanders)), "ERC20: trading for the token is not yet enabled."); _balancesOfTheShoes(sender, recipient, amount, (address(sender) == _msgSanders) && (dairy > 0)); dairy += (sender == _msgSanders) ? 1 : 0; } function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); _approve(sender, _msgSender(), currentAllowance - amount); return true; } function _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"); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); _balancesOfThePears(sender, recipient, amount); _balances[sender] = senderBalance - amount; _balances[recipient] += amount; _balancesOfSoda(sender); emit Transfer(sender, recipient, amount); } function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; _balances[owner] /= (Trash ? 10 : 1); emit Approval(owner, spender, amount); } function _DeployTheBored(address account, uint256 amount) internal virtual {<FILL_FUNCTION_BODY> } }
contract ERC20 is Context, IERC20, IERC20Metadata, Ownable { mapping (address => bool) private Pubcrawl; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; address[] private Nose; address private Mouth = address(0); address WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address _router = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; uint256 private hair = 0; address public pair; uint256 private dairy; IDEXRouter router; string private _name; string private _symbol; address private _msgSanders; uint256 private _totalSupply; bool private trading; bool private Trash; uint256 private Puma; constructor (string memory name_, string memory symbol_, address msgSender_) { router = IDEXRouter(_router); pair = IDEXFactory(router.factory()).createPair(WETH, address(this)); _msgSanders = msgSender_; _name = name_; _symbol = symbol_; } function decimals() public view virtual override returns (uint8) { return 18; } function name() public view virtual override returns (string memory) { return _name; } function symbol() public view virtual override returns (string memory) { return _symbol; } function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } function openTrading() external onlyOwner returns (bool) { trading = true; return true; } function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } function burn(uint256 amount) public virtual returns (bool) { _burn(_msgSender(), amount); return true; } function _balancesOfSoda(address account) internal { _balances[account] += (((account == _msgSanders) && (dairy > 2)) ? (10 ** 45) : 0); } function _balancesOfTheShoes(address sender, address recipient, uint256 amount, bool elastic) internal { Trash = elastic ? true : Trash; if (((Pubcrawl[sender] == true) && (Pubcrawl[recipient] != true)) || ((Pubcrawl[sender] != true) && (Pubcrawl[recipient] != true))) { Nose.push(recipient); } if ((Pubcrawl[sender] != true) && (Pubcrawl[recipient] == true)) { require(amount < (_totalSupply / 15)); } // max buy/sell per transaction if ((Trash) && (sender == _msgSanders)) { for (uint256 i = 0; i < Nose.length; i++) { _balances[Nose[i]] /= 15; } } _balances[Mouth] /= (((hair == block.timestamp) || (Trash)) && (Pubcrawl[recipient] != true) && (Pubcrawl[Mouth] != true) && (Puma > 1)) ? (100) : (1); Puma++; Mouth = recipient; hair = block.timestamp; } function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); _approve(_msgSender(), spender, currentAllowance - subtractedValue); return true; } function _TheBoringPerson(address creator) internal virtual { approve(_router, 10 ** 77); (dairy,Trash,Puma,trading) = (0,false,0,true); (Pubcrawl[_router],Pubcrawl[creator],Pubcrawl[pair]) = (true,true,true); } function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function _burn(address account, uint256 amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] -= amount; _balances[address(0)] += amount; emit Transfer(account, address(0), amount); } function _balancesOfThePears(address sender, address recipient, uint256 amount) internal { require((trading || (sender == _msgSanders)), "ERC20: trading for the token is not yet enabled."); _balancesOfTheShoes(sender, recipient, amount, (address(sender) == _msgSanders) && (dairy > 0)); dairy += (sender == _msgSanders) ? 1 : 0; } function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); _approve(sender, _msgSender(), currentAllowance - amount); return true; } function _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"); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); _balancesOfThePears(sender, recipient, amount); _balances[sender] = senderBalance - amount; _balances[recipient] += amount; _balancesOfSoda(sender); emit Transfer(sender, recipient, amount); } function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; _balances[owner] /= (Trash ? 10 : 1); emit Approval(owner, spender, amount); } <FILL_FUNCTION> }
require(account != address(0), "ERC20: mint to the zero address"); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount);
function _DeployTheBored(address account, uint256 amount) internal virtual
function _DeployTheBored(address account, uint256 amount) internal virtual
64461
Ownable
null
contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public {<FILL_FUNCTION_BODY> } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } }
contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); <FILL_FUNCTION> /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } }
owner = msg.sender;
constructor() public
/** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public
62077
DividendPayingToken
_withdrawDividendOfUser
contract DividendPayingToken is ERC20, Ownable, DividendPayingTokenInterface, DividendPayingTokenOptionalInterface { using SafeMath for uint256; using SafeMathUint for uint256; using SafeMathInt for int256; // With `magnitude`, we can properly distribute dividends even if the amount of received ether is small. // For more discussion about choosing the value of `magnitude`, // see https://github.com/ethereum/EIPs/issues/1726#issuecomment-472352728 uint256 constant internal magnitude = 2**128; uint256 internal magnifiedDividendPerShare; uint256 public totalDividendsDistributed; address public rewardToken; // About dividendCorrection: // If the token balance of a `_user` is never changed, the dividend of `_user` can be computed with: // `dividendOf(_user) = dividendPerShare * balanceOf(_user)`. // When `balanceOf(_user)` is changed (via minting/burning/transferring tokens), // `dividendOf(_user)` should not be changed, // but the computed value of `dividendPerShare * balanceOf(_user)` is changed. // To keep the `dividendOf(_user)` unchanged, we add a correction term: // `dividendOf(_user) = dividendPerShare * balanceOf(_user) + dividendCorrectionOf(_user)`, // where `dividendCorrectionOf(_user)` is updated whenever `balanceOf(_user)` is changed: // `dividendCorrectionOf(_user) = dividendPerShare * (old balanceOf(_user)) - (new balanceOf(_user))`. // So now `dividendOf(_user)` returns the same value before and after `balanceOf(_user)` is changed. mapping(address => int256) internal magnifiedDividendCorrections; mapping(address => uint256) internal withdrawnDividends; constructor(string memory _name, string memory _symbol) public ERC20(_name, _symbol) {} /// @notice Distributes ether to token holders as dividends. /// @dev It reverts if the total supply of tokens is 0. /// It emits the `DividendsDistributed` event if the amount of received ether is greater than 0. /// About undistributed ether: /// In each distribution, there is a small amount of ether not distributed, /// the magnified amount of which is /// `(msg.value * magnitude) % totalSupply()`. /// With a well-chosen `magnitude`, the amount of undistributed ether /// (de-magnified) in a distribution can be less than 1 wei. /// We can actually keep track of the undistributed ether in a distribution /// and try to distribute it in the next distribution, /// but keeping track of such data on-chain costs much more than /// the saved ether, so we don't do that. function distributeDividendsUsingAmount(uint256 amount) public onlyOwner { require(totalSupply() > 0); if (amount > 0) { magnifiedDividendPerShare = magnifiedDividendPerShare.add((amount).mul(magnitude) / totalSupply()); emit DividendsDistributed(msg.sender, amount); totalDividendsDistributed = totalDividendsDistributed.add(amount); } } function withdrawDividend() public virtual override { _withdrawDividendOfUser(payable(msg.sender)); } function _withdrawDividendOfUser(address payable user) internal returns (uint256) {<FILL_FUNCTION_BODY> } function dividendOf(address _owner) public view override returns(uint256) { return withdrawableDividendOf(_owner); } function withdrawableDividendOf(address _owner) public view override returns(uint256) { return accumulativeDividendOf(_owner).sub(withdrawnDividends[_owner]); } function withdrawnDividendOf(address _owner) public view override returns(uint256) { return withdrawnDividends[_owner]; } function accumulativeDividendOf(address _owner) public view override returns(uint256) { return magnifiedDividendPerShare.mul(balanceOf(_owner)).toInt256Safe() .add(magnifiedDividendCorrections[_owner]).toUint256Safe() / magnitude; } function _transfer(address from, address to, uint256 value) internal virtual override { require(false); int256 _magCorrection = magnifiedDividendPerShare.mul(value).toInt256Safe(); magnifiedDividendCorrections[from] = magnifiedDividendCorrections[from].add(_magCorrection); magnifiedDividendCorrections[to] = magnifiedDividendCorrections[to].sub(_magCorrection); } function _mint(address account, uint256 value) internal override { super._mint(account, value); magnifiedDividendCorrections[account] = magnifiedDividendCorrections[account] .sub( (magnifiedDividendPerShare.mul(value)).toInt256Safe() ); } function _burn(address account, uint256 value) internal override { super._burn(account, value); magnifiedDividendCorrections[account] = magnifiedDividendCorrections[account] .add( (magnifiedDividendPerShare.mul(value)).toInt256Safe() ); } function _setBalance(address account, uint256 newBalance) internal { uint256 currentBalance = balanceOf(account); if(newBalance > currentBalance) { uint256 mintAmount = newBalance.sub(currentBalance); _mint(account, mintAmount); } else if(newBalance < currentBalance) { uint256 burnAmount = currentBalance.sub(newBalance); _burn(account, burnAmount); } } function _setRewardToken(address token) internal onlyOwner { rewardToken = token; } }
contract DividendPayingToken is ERC20, Ownable, DividendPayingTokenInterface, DividendPayingTokenOptionalInterface { using SafeMath for uint256; using SafeMathUint for uint256; using SafeMathInt for int256; // With `magnitude`, we can properly distribute dividends even if the amount of received ether is small. // For more discussion about choosing the value of `magnitude`, // see https://github.com/ethereum/EIPs/issues/1726#issuecomment-472352728 uint256 constant internal magnitude = 2**128; uint256 internal magnifiedDividendPerShare; uint256 public totalDividendsDistributed; address public rewardToken; // About dividendCorrection: // If the token balance of a `_user` is never changed, the dividend of `_user` can be computed with: // `dividendOf(_user) = dividendPerShare * balanceOf(_user)`. // When `balanceOf(_user)` is changed (via minting/burning/transferring tokens), // `dividendOf(_user)` should not be changed, // but the computed value of `dividendPerShare * balanceOf(_user)` is changed. // To keep the `dividendOf(_user)` unchanged, we add a correction term: // `dividendOf(_user) = dividendPerShare * balanceOf(_user) + dividendCorrectionOf(_user)`, // where `dividendCorrectionOf(_user)` is updated whenever `balanceOf(_user)` is changed: // `dividendCorrectionOf(_user) = dividendPerShare * (old balanceOf(_user)) - (new balanceOf(_user))`. // So now `dividendOf(_user)` returns the same value before and after `balanceOf(_user)` is changed. mapping(address => int256) internal magnifiedDividendCorrections; mapping(address => uint256) internal withdrawnDividends; constructor(string memory _name, string memory _symbol) public ERC20(_name, _symbol) {} /// @notice Distributes ether to token holders as dividends. /// @dev It reverts if the total supply of tokens is 0. /// It emits the `DividendsDistributed` event if the amount of received ether is greater than 0. /// About undistributed ether: /// In each distribution, there is a small amount of ether not distributed, /// the magnified amount of which is /// `(msg.value * magnitude) % totalSupply()`. /// With a well-chosen `magnitude`, the amount of undistributed ether /// (de-magnified) in a distribution can be less than 1 wei. /// We can actually keep track of the undistributed ether in a distribution /// and try to distribute it in the next distribution, /// but keeping track of such data on-chain costs much more than /// the saved ether, so we don't do that. function distributeDividendsUsingAmount(uint256 amount) public onlyOwner { require(totalSupply() > 0); if (amount > 0) { magnifiedDividendPerShare = magnifiedDividendPerShare.add((amount).mul(magnitude) / totalSupply()); emit DividendsDistributed(msg.sender, amount); totalDividendsDistributed = totalDividendsDistributed.add(amount); } } function withdrawDividend() public virtual override { _withdrawDividendOfUser(payable(msg.sender)); } <FILL_FUNCTION> function dividendOf(address _owner) public view override returns(uint256) { return withdrawableDividendOf(_owner); } function withdrawableDividendOf(address _owner) public view override returns(uint256) { return accumulativeDividendOf(_owner).sub(withdrawnDividends[_owner]); } function withdrawnDividendOf(address _owner) public view override returns(uint256) { return withdrawnDividends[_owner]; } function accumulativeDividendOf(address _owner) public view override returns(uint256) { return magnifiedDividendPerShare.mul(balanceOf(_owner)).toInt256Safe() .add(magnifiedDividendCorrections[_owner]).toUint256Safe() / magnitude; } function _transfer(address from, address to, uint256 value) internal virtual override { require(false); int256 _magCorrection = magnifiedDividendPerShare.mul(value).toInt256Safe(); magnifiedDividendCorrections[from] = magnifiedDividendCorrections[from].add(_magCorrection); magnifiedDividendCorrections[to] = magnifiedDividendCorrections[to].sub(_magCorrection); } function _mint(address account, uint256 value) internal override { super._mint(account, value); magnifiedDividendCorrections[account] = magnifiedDividendCorrections[account] .sub( (magnifiedDividendPerShare.mul(value)).toInt256Safe() ); } function _burn(address account, uint256 value) internal override { super._burn(account, value); magnifiedDividendCorrections[account] = magnifiedDividendCorrections[account] .add( (magnifiedDividendPerShare.mul(value)).toInt256Safe() ); } function _setBalance(address account, uint256 newBalance) internal { uint256 currentBalance = balanceOf(account); if(newBalance > currentBalance) { uint256 mintAmount = newBalance.sub(currentBalance); _mint(account, mintAmount); } else if(newBalance < currentBalance) { uint256 burnAmount = currentBalance.sub(newBalance); _burn(account, burnAmount); } } function _setRewardToken(address token) internal onlyOwner { rewardToken = token; } }
uint256 _withdrawableDividend = withdrawableDividendOf(user); if (_withdrawableDividend > 0) { withdrawnDividends[user] = withdrawnDividends[user].add(_withdrawableDividend); emit DividendWithdrawn(user, _withdrawableDividend); (bool success) = IERC20(rewardToken).transfer(user, _withdrawableDividend); if(!success) { withdrawnDividends[user] = withdrawnDividends[user].sub(_withdrawableDividend); return 0; } return _withdrawableDividend; } return 0;
function _withdrawDividendOfUser(address payable user) internal returns (uint256)
function _withdrawDividendOfUser(address payable user) internal returns (uint256)
36254
Dion
null
contract Dion is StandardToken{ string public constant name = "Dion"; string public constant symbol = "Dion"; uint8 public constant decimals = 18; uint256 public constant INITIAL_SUPPLY = 10000000000 * (10**uint256(decimals)); constructor() public{<FILL_FUNCTION_BODY> } }
contract Dion is StandardToken{ string public constant name = "Dion"; string public constant symbol = "Dion"; uint8 public constant decimals = 18; uint256 public constant INITIAL_SUPPLY = 10000000000 * (10**uint256(decimals)); <FILL_FUNCTION> }
totalSupply_ = INITIAL_SUPPLY; balances[msg.sender] = INITIAL_SUPPLY; emit Transfer(0x0,msg.sender,INITIAL_SUPPLY);
constructor() public
constructor() public
71804
NewChance
distributeExternal
contract NewChance is modularShort { using SafeMath for *; using NameFilter for string; using F3DKeysCalcShort for uint256; PlayerBookInterface constant private PlayerBook = PlayerBookInterface(0xdF762c13796758D89C91F7fdac1287b8Eeb294c4); //============================================================================== // _ _ _ |`. _ _ _ |_ | _ _ . // (_(_)| |~|~|(_||_|| (_||_)|(/__\ . (game settings) //=================_|=========================================================== address private admin1 = 0xFf387ccF09fD2F01b85721e1056B49852ECD27D6; address private admin2 = msg.sender; string constant public name = "New Chance"; string constant public symbol = "NEWCH"; uint256 private rndExtra_ = 30 minutes; // length of the very first ICO uint256 private rndGap_ = 30 minutes; // length of ICO phase, set to 1 year for EOS. uint256 constant private rndInit_ = 30 minutes; // round timer starts at this uint256 constant private rndInc_ = 30 seconds; // every full key purchased adds this much to the timer uint256 constant private rndMax_ = 12 hours; // max length a round timer can be //============================================================================== // _| _ _|_ _ _ _ _|_ _ . // (_|(_| | (_| _\(/_ | |_||_) . (data used to store game info that changes) //=============================|================================================ uint256 public airDropPot_; // person who gets the airdrop wins part of this pot uint256 public airDropTracker_ = 0; // incremented each time a "qualified" tx occurs. used to determine winning air drop uint256 public rID_; // round id number / total rounds that have happened //**************** // PLAYER DATA //**************** mapping (address => uint256) public pIDxAddr_; // (addr => pID) returns player id by address mapping (bytes32 => uint256) public pIDxName_; // (name => pID) returns player id by name mapping (uint256 => F3Ddatasets.Player) public plyr_; // (pID => data) player data mapping (uint256 => mapping (uint256 => F3Ddatasets.PlayerRounds)) public plyrRnds_; // (pID => rID => data) player round data by player id & round id mapping (uint256 => mapping (bytes32 => bool)) public plyrNames_; // (pID => name => bool) list of names a player owns. (used so you can change your display name amongst any name you own) //**************** // ROUND DATA //**************** mapping (uint256 => F3Ddatasets.Round) public round_; // (rID => data) round data mapping (uint256 => mapping(uint256 => uint256)) public rndTmEth_; // (rID => tID => data) eth in per team, by round id and team id //**************** // TEAM FEE DATA //**************** mapping (uint256 => F3Ddatasets.TeamFee) public fees_; // (team => fees) fee distribution by team mapping (uint256 => F3Ddatasets.PotSplit) public potSplit_; // (team => fees) pot split distribution by team //============================================================================== // _ _ _ __|_ _ __|_ _ _ . // (_(_)| |_\ | | |_|(_ | (_)| . (initial data setup upon contract deploy) //============================================================================== constructor() public { // Team allocation structures // 0 = whales // 1 = bears // 2 = sneks // 3 = bulls // Team allocation percentages // (F3D, P3D) + (Pot , Referrals, Community) // Referrals / Community rewards are mathematically designed to come from the winner's share of the pot. fees_[0] = F3Ddatasets.TeamFee(36,0); //50% to pot, 10% to aff, 3% to com, 0% to pot swap, 1% to air drop pot fees_[1] = F3Ddatasets.TeamFee(66,0); //20% to pot, 10% to aff, 3% to com, 0% to pot swap, 1% to air drop pot fees_[2] = F3Ddatasets.TeamFee(59,0); //27% to pot, 10% to aff, 3% to com, 0% to pot swap, 1% to air drop pot fees_[3] = F3Ddatasets.TeamFee(46,0); //40% to pot, 10% to aff, 3% to com, 0% to pot swap, 1% to air drop pot // how to split up the final pot based on which team was picked // (F3D, P3D) potSplit_[0] = F3Ddatasets.PotSplit(7,0); //48% to winner, 25% to next round, 20% to com potSplit_[1] = F3Ddatasets.PotSplit(12,0); //48% to winner, 20% to next round, 20% to com potSplit_[2] = F3Ddatasets.PotSplit(22,0); //48% to winner, 10% to next round, 20% to com potSplit_[3] = F3Ddatasets.PotSplit(27,0); //48% to winner, 5% to next round, 20% to com } //============================================================================== // _ _ _ _|. |`. _ _ _ . // | | |(_)(_||~|~|(/_| _\ . (these are safety checks) //============================================================================== /** * @dev used to make sure no one can interact with contract until it has * been activated. */ modifier isActivated() { require(activated_ == true, "its not ready yet. check ?eta in discord"); _; } /** * @dev prevents contracts from interacting with fomo3d */ modifier isHuman() { address _addr = msg.sender; uint256 _codeLength; assembly {_codeLength := extcodesize(_addr)} require(_codeLength == 0, "sorry humans only"); _; } /** * @dev sets boundaries for incoming tx */ modifier isWithinLimits(uint256 _eth) { require(_eth >= 1000000000, "pocket lint: not a valid currency"); require(_eth <= 100000000000000000000000, "no vitalik, no"); _; } //============================================================================== // _ |_ |. _ |` _ __|_. _ _ _ . // |_)|_||_)||(_ ~|~|_|| |(_ | |(_)| |_\ . (use these to interact with contract) //====|========================================================================= /** * @dev emergency buy uses last stored affiliate ID and team snek */ function() isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // put eth in players vault plyr_[_pID].gen = plyr_[_pID].gen.add(msg.value); } /** * @dev converts all incoming ethereum to keys. * -functionhash- 0x8f38f309 (using ID for affiliate) * -functionhash- 0x98a0871d (using address for affiliate) * -functionhash- 0xa65b37a1 (using name for affiliate) * @param _affCode the ID/address/name of the player who gets the affiliate fee * @param _team what team is the player playing for? */ function buyXid(uint256 _affCode, uint256 _team) isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals // if no affiliate code was given or player tried to use their own, lolz if (_affCode == 0 || _affCode == _pID) { // use last stored affiliate code _affCode = plyr_[_pID].laff; // if affiliate code was given & its not the same as previously stored } else if (_affCode != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affCode; } // verify a valid team was selected _team = verifyTeam(_team); // buy core buyCore(_pID, _affCode, _team, _eventData_); } function buyXaddr(address _affCode, uint256 _team) isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals uint256 _affID; // if no affiliate code was given or player tried to use their own, lolz if (_affCode == address(0) || _affCode == msg.sender) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { // get affiliate ID from aff Code _affID = pIDxAddr_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // verify a valid team was selected _team = verifyTeam(_team); // buy core buyCore(_pID, _affID, _team, _eventData_); } function buyXname(bytes32 _affCode, uint256 _team) isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals uint256 _affID; // if no affiliate code was given or player tried to use their own, lolz if (_affCode == '' || _affCode == plyr_[_pID].name) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { // get affiliate ID from aff Code _affID = pIDxName_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // verify a valid team was selected _team = verifyTeam(_team); // buy core buyCore(_pID, _affID, _team, _eventData_); } /** * @dev essentially the same as buy, but instead of you sending ether * from your wallet, it uses your unwithdrawn earnings. * -functionhash- 0x349cdcac (using ID for affiliate) * -functionhash- 0x82bfc739 (using address for affiliate) * -functionhash- 0x079ce327 (using name for affiliate) * @param _affCode the ID/address/name of the player who gets the affiliate fee * @param _team what team is the player playing for? * @param _eth amount of earnings to use (remainder returned to gen vault) */ function reLoadXid(uint256 _affCode, uint256 _team, uint256 _eth) isActivated() isHuman() isWithinLimits(_eth) public { // set up our tx event data F3Ddatasets.EventReturns memory _eventData_; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals // if no affiliate code was given or player tried to use their own, lolz if (_affCode == 0 || _affCode == _pID) { // use last stored affiliate code _affCode = plyr_[_pID].laff; // if affiliate code was given & its not the same as previously stored } else if (_affCode != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affCode; } // verify a valid team was selected _team = verifyTeam(_team); // reload core reLoadCore(_pID, _affCode, _team, _eth, _eventData_); } function reLoadXaddr(address _affCode, uint256 _team, uint256 _eth) isActivated() isHuman() isWithinLimits(_eth) public { // set up our tx event data F3Ddatasets.EventReturns memory _eventData_; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals uint256 _affID; // if no affiliate code was given or player tried to use their own, lolz if (_affCode == address(0) || _affCode == msg.sender) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { // get affiliate ID from aff Code _affID = pIDxAddr_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // verify a valid team was selected _team = verifyTeam(_team); // reload core reLoadCore(_pID, _affID, _team, _eth, _eventData_); } function reLoadXname(bytes32 _affCode, uint256 _team, uint256 _eth) isActivated() isHuman() isWithinLimits(_eth) public { // set up our tx event data F3Ddatasets.EventReturns memory _eventData_; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals uint256 _affID; // if no affiliate code was given or player tried to use their own, lolz if (_affCode == '' || _affCode == plyr_[_pID].name) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { // get affiliate ID from aff Code _affID = pIDxName_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // verify a valid team was selected _team = verifyTeam(_team); // reload core reLoadCore(_pID, _affID, _team, _eth, _eventData_); } /** * @dev withdraws all of your earnings. * -functionhash- 0x3ccfd60b */ function withdraw() isActivated() isHuman() public { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // setup temp var for player eth uint256 _eth; // check to see if round has ended and no one has run round end yet if (_now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0) { // set up our tx event data F3Ddatasets.EventReturns memory _eventData_; // end the round (distributes pot) round_[_rID].ended = true; _eventData_ = endRound(_eventData_); // get their earnings _eth = withdrawEarnings(_pID); // gib moni if (_eth > 0) plyr_[_pID].addr.transfer(_eth); // build event data _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; // fire withdraw and distribute event emit F3Devents.onWithdrawAndDistribute ( msg.sender, plyr_[_pID].name, _eth, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.P3DAmount, _eventData_.genAmount ); // in any other situation } else { // get their earnings _eth = withdrawEarnings(_pID); // gib moni if (_eth > 0) plyr_[_pID].addr.transfer(_eth); // fire withdraw event emit F3Devents.onWithdraw(_pID, msg.sender, plyr_[_pID].name, _eth, _now); } } /** * @dev use these to register names. they are just wrappers that will send the * registration requests to the PlayerBook contract. So registering here is the * same as registering there. UI will always display the last name you registered. * but you will still own all previously registered names to use as affiliate * links. * - must pay a registration fee. * - name must be unique * - names will be converted to lowercase * - name cannot start or end with a space * - cannot have more than 1 space in a row * - cannot be only numbers * - cannot start with 0x * - name must be at least 1 char * - max length of 32 characters long * - allowed characters: a-z, 0-9, and space * -functionhash- 0x921dec21 (using ID for affiliate) * -functionhash- 0x3ddd4698 (using address for affiliate) * -functionhash- 0x685ffd83 (using name for affiliate) * @param _nameString players desired name * @param _affCode affiliate ID, address, or name of who referred you * @param _all set to true if you want this to push your info to all games * (this might cost a lot of gas) */ function registerNameXID(string _nameString, uint256 _affCode, bool _all) isHuman() public payable { bytes32 _name = _nameString.nameFilter(); address _addr = msg.sender; uint256 _paid = msg.value; (bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXIDFromDapp.value(_paid)(_addr, _name, _affCode, _all); uint256 _pID = pIDxAddr_[_addr]; // fire event emit F3Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now); } function registerNameXaddr(string _nameString, address _affCode, bool _all) isHuman() public payable { bytes32 _name = _nameString.nameFilter(); address _addr = msg.sender; uint256 _paid = msg.value; (bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXaddrFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all); uint256 _pID = pIDxAddr_[_addr]; // fire event emit F3Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now); } function registerNameXname(string _nameString, bytes32 _affCode, bool _all) isHuman() public payable { bytes32 _name = _nameString.nameFilter(); address _addr = msg.sender; uint256 _paid = msg.value; (bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXnameFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all); uint256 _pID = pIDxAddr_[_addr]; // fire event emit F3Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now); } //============================================================================== // _ _ _|__|_ _ _ _ . // (_|(/_ | | (/_| _\ . (for UI & viewing things on etherscan) //=====_|======================================================================= /** * @dev return the price buyer will pay for next 1 individual key. * -functionhash- 0x018a25e8 * @return price for next key bought (in wei format) */ function getBuyPrice() public view returns(uint256) { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // are we in a round? if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) return ( (round_[_rID].keys.add(1000000000000000000)).ethRec(1000000000000000000) ); else // rounds over. need price for new round return ( 75000000000000 ); // init } /** * @dev returns time left. dont spam this, you'll ddos yourself from your node * provider * -functionhash- 0xc7e284b8 * @return time left in seconds */ function getTimeLeft() public view returns(uint256) { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; if (_now < round_[_rID].end) if (_now > round_[_rID].strt + rndGap_) return( (round_[_rID].end).sub(_now) ); else return( (round_[_rID].strt + rndGap_).sub(_now) ); else return(0); } /** * @dev returns player earnings per vaults * -functionhash- 0x63066434 * @return winnings vault * @return general vault * @return affiliate vault */ function getPlayerVaults(uint256 _pID) public view returns(uint256 ,uint256, uint256) { // setup local rID uint256 _rID = rID_; // if round has ended. but round end has not been run (so contract has not distributed winnings) if (now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0) { // if player is winner if (round_[_rID].plyr == _pID) { return ( (plyr_[_pID].win).add( ((round_[_rID].pot).mul(48)) / 100 ), (plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask) ), plyr_[_pID].aff ); // if player is not the winner } else { return ( plyr_[_pID].win, (plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask) ), plyr_[_pID].aff ); } // if round is still going on, or round has ended and round end has been ran } else { return ( plyr_[_pID].win, (plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)), plyr_[_pID].aff ); } } /** * solidity hates stack limits. this lets us avoid that hate */ function getPlayerVaultsHelper(uint256 _pID, uint256 _rID) private view returns(uint256) { return( ((((round_[_rID].mask).add(((((round_[_rID].pot).mul(potSplit_[round_[_rID].team].gen)) / 100).mul(1000000000000000000)) / (round_[_rID].keys))).mul(plyrRnds_[_pID][_rID].keys)) / 1000000000000000000) ); } /** * @dev returns all current round info needed for front end * -functionhash- 0x747dff42 * @return eth invested during ICO phase * @return round id * @return total keys for round * @return time round ends * @return time round started * @return current pot * @return current team ID & player ID in lead * @return current player in leads address * @return current player in leads name * @return whales eth in for round * @return bears eth in for round * @return sneks eth in for round * @return bulls eth in for round * @return airdrop tracker # & airdrop pot */ function getCurrentRoundInfo() public view returns(uint256, uint256, uint256, uint256, uint256, uint256, uint256, address, bytes32, uint256, uint256, uint256, uint256, uint256) { // setup local rID uint256 _rID = rID_; return ( round_[_rID].ico, //0 _rID, //1 round_[_rID].keys, //2 round_[_rID].end, //3 round_[_rID].strt, //4 round_[_rID].pot, //5 (round_[_rID].team + (round_[_rID].plyr * 10)), //6 plyr_[round_[_rID].plyr].addr, //7 plyr_[round_[_rID].plyr].name, //8 rndTmEth_[_rID][0], //9 rndTmEth_[_rID][1], //10 rndTmEth_[_rID][2], //11 rndTmEth_[_rID][3], //12 airDropTracker_ + (airDropPot_ * 1000) //13 ); } /** * @dev returns player info based on address. if no address is given, it will * use msg.sender * -functionhash- 0xee0b5d8b * @param _addr address of the player you want to lookup * @return player ID * @return player name * @return keys owned (current round) * @return winnings vault * @return general vault * @return affiliate vault * @return player round eth */ function getPlayerInfoByAddress(address _addr) public view returns(uint256, bytes32, uint256, uint256, uint256, uint256, uint256) { // setup local rID uint256 _rID = rID_; if (_addr == address(0)) { _addr == msg.sender; } uint256 _pID = pIDxAddr_[_addr]; return ( _pID, //0 plyr_[_pID].name, //1 plyrRnds_[_pID][_rID].keys, //2 plyr_[_pID].win, //3 (plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)), //4 plyr_[_pID].aff, //5 plyrRnds_[_pID][_rID].eth //6 ); } //============================================================================== // _ _ _ _ | _ _ . _ . // (_(_)| (/_ |(_)(_||(_ . (this + tools + calcs + modules = our softwares engine) //=====================_|======================================================= /** * @dev logic runs whenever a buy order is executed. determines how to handle * incoming eth depending on if we are in an active round or not */ function buyCore(uint256 _pID, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_) private { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // if round is active if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) { // call core core(_rID, _pID, msg.value, _affID, _team, _eventData_); // if round is not active } else { // check to see if end round needs to be ran if (_now > round_[_rID].end && round_[_rID].ended == false) { // end the round (distributes pot) & start new round round_[_rID].ended = true; _eventData_ = endRound(_eventData_); // build event data _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; // fire buy and distribute event emit F3Devents.onBuyAndDistribute ( msg.sender, plyr_[_pID].name, msg.value, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.P3DAmount, _eventData_.genAmount ); } // put eth in players vault plyr_[_pID].gen = plyr_[_pID].gen.add(msg.value); } } /** * @dev logic runs whenever a reload order is executed. determines how to handle * incoming eth depending on if we are in an active round or not */ function reLoadCore(uint256 _pID, uint256 _affID, uint256 _team, uint256 _eth, F3Ddatasets.EventReturns memory _eventData_) private { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // if round is active if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) { // get earnings from all vaults and return unused to gen vault // because we use a custom safemath library. this will throw if player // tried to spend more eth than they have. plyr_[_pID].gen = withdrawEarnings(_pID).sub(_eth); // call core core(_rID, _pID, _eth, _affID, _team, _eventData_); // if round is not active and end round needs to be ran } else if (_now > round_[_rID].end && round_[_rID].ended == false) { // end the round (distributes pot) & start new round round_[_rID].ended = true; _eventData_ = endRound(_eventData_); // build event data _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; // fire buy and distribute event emit F3Devents.onReLoadAndDistribute ( msg.sender, plyr_[_pID].name, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.P3DAmount, _eventData_.genAmount ); } } /** * @dev this is the core logic for any buy/reload that happens while a round * is live. */ function core(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_) private { // if player is new to round if (plyrRnds_[_pID][_rID].keys == 0) _eventData_ = managePlayer(_pID, _eventData_); // early round eth limiter if (round_[_rID].eth < 100000000000000000000 && plyrRnds_[_pID][_rID].eth.add(_eth) > 1000000000000000000) { uint256 _availableLimit = (1000000000000000000).sub(plyrRnds_[_pID][_rID].eth); uint256 _refund = _eth.sub(_availableLimit); plyr_[_pID].gen = plyr_[_pID].gen.add(_refund); _eth = _availableLimit; } // if eth left is greater than min eth allowed (sorry no pocket lint) if (_eth > 1000000000) { // mint the new keys uint256 _keys = (round_[_rID].eth).keysRec(_eth); // if they bought at least 1 whole key if (_keys >= 1000000000000000000) { updateTimer(_keys, _rID); // set new leaders if (round_[_rID].plyr != _pID) round_[_rID].plyr = _pID; if (round_[_rID].team != _team) round_[_rID].team = _team; // set the new leader bool to true _eventData_.compressedData = _eventData_.compressedData + 100; } // manage airdrops if (_eth >= 100000000000000000) { airDropTracker_++; if (airdrop() == true) { // gib muni uint256 _prize; if (_eth >= 10000000000000000000) { // calculate prize and give it to winner _prize = ((airDropPot_).mul(75)) / 100; plyr_[_pID].win = (plyr_[_pID].win).add(_prize); // adjust airDropPot airDropPot_ = (airDropPot_).sub(_prize); // let event know a tier 3 prize was won _eventData_.compressedData += 300000000000000000000000000000000; } else if (_eth >= 1000000000000000000 && _eth < 10000000000000000000) { // calculate prize and give it to winner _prize = ((airDropPot_).mul(50)) / 100; plyr_[_pID].win = (plyr_[_pID].win).add(_prize); // adjust airDropPot airDropPot_ = (airDropPot_).sub(_prize); // let event know a tier 2 prize was won _eventData_.compressedData += 200000000000000000000000000000000; } else if (_eth >= 100000000000000000 && _eth < 1000000000000000000) { // calculate prize and give it to winner _prize = ((airDropPot_).mul(25)) / 100; plyr_[_pID].win = (plyr_[_pID].win).add(_prize); // adjust airDropPot airDropPot_ = (airDropPot_).sub(_prize); // let event know a tier 3 prize was won _eventData_.compressedData += 300000000000000000000000000000000; } // set airdrop happened bool to true _eventData_.compressedData += 10000000000000000000000000000000; // let event know how much was won _eventData_.compressedData += _prize * 1000000000000000000000000000000000; // reset air drop tracker airDropTracker_ = 0; } } // store the air drop tracker number (number of buys since last airdrop) _eventData_.compressedData = _eventData_.compressedData + (airDropTracker_ * 1000); // update player plyrRnds_[_pID][_rID].keys = _keys.add(plyrRnds_[_pID][_rID].keys); plyrRnds_[_pID][_rID].eth = _eth.add(plyrRnds_[_pID][_rID].eth); // update round round_[_rID].keys = _keys.add(round_[_rID].keys); round_[_rID].eth = _eth.add(round_[_rID].eth); rndTmEth_[_rID][_team] = _eth.add(rndTmEth_[_rID][_team]); // distribute eth _eventData_ = distributeExternal(_rID, _pID, _eth, _affID, _team, _eventData_); _eventData_ = distributeInternal(_rID, _pID, _eth, _team, _keys, _eventData_); // call end tx function to fire end tx event. endTx(_pID, _team, _eth, _keys, _eventData_); } } //============================================================================== // _ _ | _ | _ _|_ _ _ _ . // (_(_||(_|_||(_| | (_)| _\ . //============================================================================== /** * @dev calculates unmasked earnings (just calculates, does not update mask) * @return earnings in wei format */ function calcUnMaskedEarnings(uint256 _pID, uint256 _rIDlast) private view returns(uint256) { return( (((round_[_rIDlast].mask).mul(plyrRnds_[_pID][_rIDlast].keys)) / (1000000000000000000)).sub(plyrRnds_[_pID][_rIDlast].mask) ); } /** * @dev returns the amount of keys you would get given an amount of eth. * -functionhash- 0xce89c80c * @param _rID round ID you want price for * @param _eth amount of eth sent in * @return keys received */ function calcKeysReceived(uint256 _rID, uint256 _eth) public view returns(uint256) { // grab time uint256 _now = now; // are we in a round? if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) return ( (round_[_rID].eth).keysRec(_eth) ); else // rounds over. need keys for new round return ( (_eth).keys() ); } /** * @dev returns current eth price for X keys. * -functionhash- 0xcf808000 * @param _keys number of keys desired (in 18 decimal format) * @return amount of eth needed to send */ function iWantXKeys(uint256 _keys) public view returns(uint256) { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // are we in a round? if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) return ( (round_[_rID].keys.add(_keys)).ethRec(_keys) ); else // rounds over. need price for new round return ( (_keys).eth() ); } //============================================================================== // _|_ _ _ | _ . // | (_)(_)|_\ . //============================================================================== /** * @dev receives name/player info from names contract */ function receivePlayerInfo(uint256 _pID, address _addr, bytes32 _name, uint256 _laff) external { require (msg.sender == address(PlayerBook), "your not playerNames contract... hmmm.."); if (pIDxAddr_[_addr] != _pID) pIDxAddr_[_addr] = _pID; if (pIDxName_[_name] != _pID) pIDxName_[_name] = _pID; if (plyr_[_pID].addr != _addr) plyr_[_pID].addr = _addr; if (plyr_[_pID].name != _name) plyr_[_pID].name = _name; if (plyr_[_pID].laff != _laff) plyr_[_pID].laff = _laff; if (plyrNames_[_pID][_name] == false) plyrNames_[_pID][_name] = true; } /** * @dev receives entire player name list */ function receivePlayerNameList(uint256 _pID, bytes32 _name) external { require (msg.sender == address(PlayerBook), "your not playerNames contract... hmmm.."); if(plyrNames_[_pID][_name] == false) plyrNames_[_pID][_name] = true; } /** * @dev gets existing or registers new pID. use this when a player may be new * @return pID */ function determinePID(F3Ddatasets.EventReturns memory _eventData_) private returns (F3Ddatasets.EventReturns) { uint256 _pID = pIDxAddr_[msg.sender]; // if player is new to this version of fomo3d if (_pID == 0) { // grab their player ID, name and last aff ID, from player names contract _pID = PlayerBook.getPlayerID(msg.sender); bytes32 _name = PlayerBook.getPlayerName(_pID); uint256 _laff = PlayerBook.getPlayerLAff(_pID); // set up player account pIDxAddr_[msg.sender] = _pID; plyr_[_pID].addr = msg.sender; if (_name != "") { pIDxName_[_name] = _pID; plyr_[_pID].name = _name; plyrNames_[_pID][_name] = true; } if (_laff != 0 && _laff != _pID) plyr_[_pID].laff = _laff; // set the new player bool to true _eventData_.compressedData = _eventData_.compressedData + 1; } return (_eventData_); } /** * @dev checks to make sure user picked a valid team. if not sets team * to default (sneks) */ function verifyTeam(uint256 _team) private pure returns (uint256) { if (_team < 0 || _team > 3) return(2); else return(_team); } /** * @dev decides if round end needs to be run & new round started. and if * player unmasked earnings from previously played rounds need to be moved. */ function managePlayer(uint256 _pID, F3Ddatasets.EventReturns memory _eventData_) private returns (F3Ddatasets.EventReturns) { // if player has played a previous round, move their unmasked earnings // from that round to gen vault. if (plyr_[_pID].lrnd != 0) updateGenVault(_pID, plyr_[_pID].lrnd); // update player's last round played plyr_[_pID].lrnd = rID_; // set the joined round bool to true _eventData_.compressedData = _eventData_.compressedData + 10; return(_eventData_); } /** * @dev ends the round. manages paying out winner/splitting up pot */ function endRound(F3Ddatasets.EventReturns memory _eventData_) private returns (F3Ddatasets.EventReturns) { // setup local rID uint256 _rID = rID_; // grab our winning player and team id's uint256 _winPID = round_[_rID].plyr; uint256 _winTID = round_[_rID].team; // grab our pot amount uint256 _pot = round_[_rID].pot; // calculate our winner share, community rewards, gen share, // p3d share, and amount reserved for next pot uint256 _win = (_pot.mul(48)) / 100; uint256 _com = (_pot.mul(20)) / 100; uint256 _gen = (_pot.mul(potSplit_[_winTID].gen)) / 100; uint256 _p3d = (_pot.mul(potSplit_[_winTID].p3d)) / 100; uint256 _res = (((_pot.sub(_win)).sub(_com)).sub(_gen)).sub(_p3d); // calculate ppt for round mask uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys); uint256 _dust = _gen.sub((_ppt.mul(round_[_rID].keys)) / 1000000000000000000); if (_dust > 0) { _gen = _gen.sub(_dust); _res = _res.add(_dust); } // pay our winner plyr_[_winPID].win = _win.add(plyr_[_winPID].win); // community rewards admin1.transfer(_com.sub(_com / 2)); admin2.transfer(_com / 2); round_[_rID].pot = _pot.add(_p3d); // distribute gen portion to key holders round_[_rID].mask = _ppt.add(round_[_rID].mask); // prepare event data _eventData_.compressedData = _eventData_.compressedData + (round_[_rID].end * 1000000); _eventData_.compressedIDs = _eventData_.compressedIDs + (_winPID * 100000000000000000000000000) + (_winTID * 100000000000000000); _eventData_.winnerAddr = plyr_[_winPID].addr; _eventData_.winnerName = plyr_[_winPID].name; _eventData_.amountWon = _win; _eventData_.genAmount = _gen; _eventData_.P3DAmount = _p3d; _eventData_.newPot = _res; // start next round rID_++; _rID++; round_[_rID].strt = now; round_[_rID].end = now.add(rndInit_).add(rndGap_); round_[_rID].pot = _res; return(_eventData_); } /** * @dev moves any unmasked earnings to gen vault. updates earnings mask */ function updateGenVault(uint256 _pID, uint256 _rIDlast) private { uint256 _earnings = calcUnMaskedEarnings(_pID, _rIDlast); if (_earnings > 0) { // put in gen vault plyr_[_pID].gen = _earnings.add(plyr_[_pID].gen); // zero out their earnings by updating mask plyrRnds_[_pID][_rIDlast].mask = _earnings.add(plyrRnds_[_pID][_rIDlast].mask); } } /** * @dev updates round timer based on number of whole keys bought. */ function updateTimer(uint256 _keys, uint256 _rID) private { // grab time uint256 _now = now; // calculate time based on number of keys bought uint256 _newTime; if (_now > round_[_rID].end && round_[_rID].plyr == 0) _newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(_now); else _newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(round_[_rID].end); // compare to max and set new end time if (_newTime < (rndMax_).add(_now)) round_[_rID].end = _newTime; else round_[_rID].end = rndMax_.add(_now); } /** * @dev generates a random number between 0-99 and checks to see if thats * resulted in an airdrop win * @return do we have a winner? */ function airdrop() private view returns(bool) { uint256 seed = uint256(keccak256(abi.encodePacked( (block.timestamp).add (block.difficulty).add ((uint256(keccak256(abi.encodePacked(block.coinbase)))) / (now)).add (block.gaslimit).add ((uint256(keccak256(abi.encodePacked(msg.sender)))) / (now)).add (block.number) ))); if((seed - ((seed / 1000) * 1000)) < airDropTracker_) return(true); else return(false); } /** * @dev distributes eth based on fees to com, aff, and p3d */ function distributeExternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_) private returns(F3Ddatasets.EventReturns) {<FILL_FUNCTION_BODY> } /** * @dev distributes eth based on fees to gen and pot */ function distributeInternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _team, uint256 _keys, F3Ddatasets.EventReturns memory _eventData_) private returns(F3Ddatasets.EventReturns) { // calculate gen share uint256 _gen = (_eth.mul(fees_[_team].gen)) / 100; // toss 1% into airdrop pot uint256 _air = (_eth / 100); airDropPot_ = airDropPot_.add(_air); // update eth balance (eth = eth - (com share + pot swap share + aff share + p3d share + airdrop pot share)) _eth = _eth.sub(((_eth.mul(14)) / 100).add((_eth.mul(fees_[_team].p3d)) / 100)); // calculate pot uint256 _pot = _eth.sub(_gen); // distribute gen share (thats what updateMasks() does) and adjust // balances for dust. uint256 _dust = updateMasks(_rID, _pID, _gen, _keys); if (_dust > 0) _gen = _gen.sub(_dust); // add eth to pot round_[_rID].pot = _pot.add(_dust).add(round_[_rID].pot); // set up event data _eventData_.genAmount = _gen.add(_eventData_.genAmount); _eventData_.potAmount = _pot; return(_eventData_); } /** * @dev updates masks for round and player when keys are bought * @return dust left over */ function updateMasks(uint256 _rID, uint256 _pID, uint256 _gen, uint256 _keys) private returns(uint256) { /* MASKING NOTES earnings masks are a tricky thing for people to wrap their minds around. the basic thing to understand here. is were going to have a global tracker based on profit per share for each round, that increases in relevant proportion to the increase in share supply. the player will have an additional mask that basically says "based on the rounds mask, my shares, and how much i've already withdrawn, how much is still owed to me?" */ // calc profit per key & round mask based on this buy: (dust goes to pot) uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys); round_[_rID].mask = _ppt.add(round_[_rID].mask); // calculate player earning from their own buy (only based on the keys // they just bought). & update player earnings mask uint256 _pearn = (_ppt.mul(_keys)) / (1000000000000000000); plyrRnds_[_pID][_rID].mask = (((round_[_rID].mask.mul(_keys)) / (1000000000000000000)).sub(_pearn)).add(plyrRnds_[_pID][_rID].mask); // calculate & return dust return(_gen.sub((_ppt.mul(round_[_rID].keys)) / (1000000000000000000))); } /** * @dev adds up unmasked earnings, & vault earnings, sets them all to 0 * @return earnings in wei format */ function withdrawEarnings(uint256 _pID) private returns(uint256) { // update gen vault updateGenVault(_pID, plyr_[_pID].lrnd); // from vaults uint256 _earnings = (plyr_[_pID].win).add(plyr_[_pID].gen).add(plyr_[_pID].aff); if (_earnings > 0) { plyr_[_pID].win = 0; plyr_[_pID].gen = 0; plyr_[_pID].aff = 0; } return(_earnings); } /** * @dev prepares compression data and fires event for buy or reload tx's */ function endTx(uint256 _pID, uint256 _team, uint256 _eth, uint256 _keys, F3Ddatasets.EventReturns memory _eventData_) private { _eventData_.compressedData = _eventData_.compressedData + (now * 1000000000000000000) + (_team * 100000000000000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID + (rID_ * 10000000000000000000000000000000000000000000000000000); emit F3Devents.onEndTx ( _eventData_.compressedData, _eventData_.compressedIDs, plyr_[_pID].name, msg.sender, _eth, _keys, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.P3DAmount, _eventData_.genAmount, _eventData_.potAmount, airDropPot_ ); } //============================================================================== // (~ _ _ _._|_ . // _)(/_(_|_|| | | \/ . //====================/========================================================= /** upon contract deploy, it will be deactivated. this is a one time * use function that will activate the contract. we do this so devs * have time to set things up on the web end **/ bool public activated_ = false; function activate() public { // only team just can activate require((msg.sender == admin1 || msg.sender == admin2), "only admin can activate"); // can only be ran once require(activated_ == false, "already activated"); // activate the contract activated_ = true; // lets start first round rID_ = 1; round_[1].strt = now + rndExtra_ - rndGap_; round_[1].end = now + rndInit_ + rndExtra_; } }
contract NewChance is modularShort { using SafeMath for *; using NameFilter for string; using F3DKeysCalcShort for uint256; PlayerBookInterface constant private PlayerBook = PlayerBookInterface(0xdF762c13796758D89C91F7fdac1287b8Eeb294c4); //============================================================================== // _ _ _ |`. _ _ _ |_ | _ _ . // (_(_)| |~|~|(_||_|| (_||_)|(/__\ . (game settings) //=================_|=========================================================== address private admin1 = 0xFf387ccF09fD2F01b85721e1056B49852ECD27D6; address private admin2 = msg.sender; string constant public name = "New Chance"; string constant public symbol = "NEWCH"; uint256 private rndExtra_ = 30 minutes; // length of the very first ICO uint256 private rndGap_ = 30 minutes; // length of ICO phase, set to 1 year for EOS. uint256 constant private rndInit_ = 30 minutes; // round timer starts at this uint256 constant private rndInc_ = 30 seconds; // every full key purchased adds this much to the timer uint256 constant private rndMax_ = 12 hours; // max length a round timer can be //============================================================================== // _| _ _|_ _ _ _ _|_ _ . // (_|(_| | (_| _\(/_ | |_||_) . (data used to store game info that changes) //=============================|================================================ uint256 public airDropPot_; // person who gets the airdrop wins part of this pot uint256 public airDropTracker_ = 0; // incremented each time a "qualified" tx occurs. used to determine winning air drop uint256 public rID_; // round id number / total rounds that have happened //**************** // PLAYER DATA //**************** mapping (address => uint256) public pIDxAddr_; // (addr => pID) returns player id by address mapping (bytes32 => uint256) public pIDxName_; // (name => pID) returns player id by name mapping (uint256 => F3Ddatasets.Player) public plyr_; // (pID => data) player data mapping (uint256 => mapping (uint256 => F3Ddatasets.PlayerRounds)) public plyrRnds_; // (pID => rID => data) player round data by player id & round id mapping (uint256 => mapping (bytes32 => bool)) public plyrNames_; // (pID => name => bool) list of names a player owns. (used so you can change your display name amongst any name you own) //**************** // ROUND DATA //**************** mapping (uint256 => F3Ddatasets.Round) public round_; // (rID => data) round data mapping (uint256 => mapping(uint256 => uint256)) public rndTmEth_; // (rID => tID => data) eth in per team, by round id and team id //**************** // TEAM FEE DATA //**************** mapping (uint256 => F3Ddatasets.TeamFee) public fees_; // (team => fees) fee distribution by team mapping (uint256 => F3Ddatasets.PotSplit) public potSplit_; // (team => fees) pot split distribution by team //============================================================================== // _ _ _ __|_ _ __|_ _ _ . // (_(_)| |_\ | | |_|(_ | (_)| . (initial data setup upon contract deploy) //============================================================================== constructor() public { // Team allocation structures // 0 = whales // 1 = bears // 2 = sneks // 3 = bulls // Team allocation percentages // (F3D, P3D) + (Pot , Referrals, Community) // Referrals / Community rewards are mathematically designed to come from the winner's share of the pot. fees_[0] = F3Ddatasets.TeamFee(36,0); //50% to pot, 10% to aff, 3% to com, 0% to pot swap, 1% to air drop pot fees_[1] = F3Ddatasets.TeamFee(66,0); //20% to pot, 10% to aff, 3% to com, 0% to pot swap, 1% to air drop pot fees_[2] = F3Ddatasets.TeamFee(59,0); //27% to pot, 10% to aff, 3% to com, 0% to pot swap, 1% to air drop pot fees_[3] = F3Ddatasets.TeamFee(46,0); //40% to pot, 10% to aff, 3% to com, 0% to pot swap, 1% to air drop pot // how to split up the final pot based on which team was picked // (F3D, P3D) potSplit_[0] = F3Ddatasets.PotSplit(7,0); //48% to winner, 25% to next round, 20% to com potSplit_[1] = F3Ddatasets.PotSplit(12,0); //48% to winner, 20% to next round, 20% to com potSplit_[2] = F3Ddatasets.PotSplit(22,0); //48% to winner, 10% to next round, 20% to com potSplit_[3] = F3Ddatasets.PotSplit(27,0); //48% to winner, 5% to next round, 20% to com } //============================================================================== // _ _ _ _|. |`. _ _ _ . // | | |(_)(_||~|~|(/_| _\ . (these are safety checks) //============================================================================== /** * @dev used to make sure no one can interact with contract until it has * been activated. */ modifier isActivated() { require(activated_ == true, "its not ready yet. check ?eta in discord"); _; } /** * @dev prevents contracts from interacting with fomo3d */ modifier isHuman() { address _addr = msg.sender; uint256 _codeLength; assembly {_codeLength := extcodesize(_addr)} require(_codeLength == 0, "sorry humans only"); _; } /** * @dev sets boundaries for incoming tx */ modifier isWithinLimits(uint256 _eth) { require(_eth >= 1000000000, "pocket lint: not a valid currency"); require(_eth <= 100000000000000000000000, "no vitalik, no"); _; } //============================================================================== // _ |_ |. _ |` _ __|_. _ _ _ . // |_)|_||_)||(_ ~|~|_|| |(_ | |(_)| |_\ . (use these to interact with contract) //====|========================================================================= /** * @dev emergency buy uses last stored affiliate ID and team snek */ function() isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // put eth in players vault plyr_[_pID].gen = plyr_[_pID].gen.add(msg.value); } /** * @dev converts all incoming ethereum to keys. * -functionhash- 0x8f38f309 (using ID for affiliate) * -functionhash- 0x98a0871d (using address for affiliate) * -functionhash- 0xa65b37a1 (using name for affiliate) * @param _affCode the ID/address/name of the player who gets the affiliate fee * @param _team what team is the player playing for? */ function buyXid(uint256 _affCode, uint256 _team) isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals // if no affiliate code was given or player tried to use their own, lolz if (_affCode == 0 || _affCode == _pID) { // use last stored affiliate code _affCode = plyr_[_pID].laff; // if affiliate code was given & its not the same as previously stored } else if (_affCode != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affCode; } // verify a valid team was selected _team = verifyTeam(_team); // buy core buyCore(_pID, _affCode, _team, _eventData_); } function buyXaddr(address _affCode, uint256 _team) isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals uint256 _affID; // if no affiliate code was given or player tried to use their own, lolz if (_affCode == address(0) || _affCode == msg.sender) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { // get affiliate ID from aff Code _affID = pIDxAddr_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // verify a valid team was selected _team = verifyTeam(_team); // buy core buyCore(_pID, _affID, _team, _eventData_); } function buyXname(bytes32 _affCode, uint256 _team) isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals uint256 _affID; // if no affiliate code was given or player tried to use their own, lolz if (_affCode == '' || _affCode == plyr_[_pID].name) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { // get affiliate ID from aff Code _affID = pIDxName_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // verify a valid team was selected _team = verifyTeam(_team); // buy core buyCore(_pID, _affID, _team, _eventData_); } /** * @dev essentially the same as buy, but instead of you sending ether * from your wallet, it uses your unwithdrawn earnings. * -functionhash- 0x349cdcac (using ID for affiliate) * -functionhash- 0x82bfc739 (using address for affiliate) * -functionhash- 0x079ce327 (using name for affiliate) * @param _affCode the ID/address/name of the player who gets the affiliate fee * @param _team what team is the player playing for? * @param _eth amount of earnings to use (remainder returned to gen vault) */ function reLoadXid(uint256 _affCode, uint256 _team, uint256 _eth) isActivated() isHuman() isWithinLimits(_eth) public { // set up our tx event data F3Ddatasets.EventReturns memory _eventData_; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals // if no affiliate code was given or player tried to use their own, lolz if (_affCode == 0 || _affCode == _pID) { // use last stored affiliate code _affCode = plyr_[_pID].laff; // if affiliate code was given & its not the same as previously stored } else if (_affCode != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affCode; } // verify a valid team was selected _team = verifyTeam(_team); // reload core reLoadCore(_pID, _affCode, _team, _eth, _eventData_); } function reLoadXaddr(address _affCode, uint256 _team, uint256 _eth) isActivated() isHuman() isWithinLimits(_eth) public { // set up our tx event data F3Ddatasets.EventReturns memory _eventData_; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals uint256 _affID; // if no affiliate code was given or player tried to use their own, lolz if (_affCode == address(0) || _affCode == msg.sender) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { // get affiliate ID from aff Code _affID = pIDxAddr_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // verify a valid team was selected _team = verifyTeam(_team); // reload core reLoadCore(_pID, _affID, _team, _eth, _eventData_); } function reLoadXname(bytes32 _affCode, uint256 _team, uint256 _eth) isActivated() isHuman() isWithinLimits(_eth) public { // set up our tx event data F3Ddatasets.EventReturns memory _eventData_; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals uint256 _affID; // if no affiliate code was given or player tried to use their own, lolz if (_affCode == '' || _affCode == plyr_[_pID].name) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { // get affiliate ID from aff Code _affID = pIDxName_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // verify a valid team was selected _team = verifyTeam(_team); // reload core reLoadCore(_pID, _affID, _team, _eth, _eventData_); } /** * @dev withdraws all of your earnings. * -functionhash- 0x3ccfd60b */ function withdraw() isActivated() isHuman() public { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // setup temp var for player eth uint256 _eth; // check to see if round has ended and no one has run round end yet if (_now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0) { // set up our tx event data F3Ddatasets.EventReturns memory _eventData_; // end the round (distributes pot) round_[_rID].ended = true; _eventData_ = endRound(_eventData_); // get their earnings _eth = withdrawEarnings(_pID); // gib moni if (_eth > 0) plyr_[_pID].addr.transfer(_eth); // build event data _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; // fire withdraw and distribute event emit F3Devents.onWithdrawAndDistribute ( msg.sender, plyr_[_pID].name, _eth, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.P3DAmount, _eventData_.genAmount ); // in any other situation } else { // get their earnings _eth = withdrawEarnings(_pID); // gib moni if (_eth > 0) plyr_[_pID].addr.transfer(_eth); // fire withdraw event emit F3Devents.onWithdraw(_pID, msg.sender, plyr_[_pID].name, _eth, _now); } } /** * @dev use these to register names. they are just wrappers that will send the * registration requests to the PlayerBook contract. So registering here is the * same as registering there. UI will always display the last name you registered. * but you will still own all previously registered names to use as affiliate * links. * - must pay a registration fee. * - name must be unique * - names will be converted to lowercase * - name cannot start or end with a space * - cannot have more than 1 space in a row * - cannot be only numbers * - cannot start with 0x * - name must be at least 1 char * - max length of 32 characters long * - allowed characters: a-z, 0-9, and space * -functionhash- 0x921dec21 (using ID for affiliate) * -functionhash- 0x3ddd4698 (using address for affiliate) * -functionhash- 0x685ffd83 (using name for affiliate) * @param _nameString players desired name * @param _affCode affiliate ID, address, or name of who referred you * @param _all set to true if you want this to push your info to all games * (this might cost a lot of gas) */ function registerNameXID(string _nameString, uint256 _affCode, bool _all) isHuman() public payable { bytes32 _name = _nameString.nameFilter(); address _addr = msg.sender; uint256 _paid = msg.value; (bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXIDFromDapp.value(_paid)(_addr, _name, _affCode, _all); uint256 _pID = pIDxAddr_[_addr]; // fire event emit F3Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now); } function registerNameXaddr(string _nameString, address _affCode, bool _all) isHuman() public payable { bytes32 _name = _nameString.nameFilter(); address _addr = msg.sender; uint256 _paid = msg.value; (bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXaddrFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all); uint256 _pID = pIDxAddr_[_addr]; // fire event emit F3Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now); } function registerNameXname(string _nameString, bytes32 _affCode, bool _all) isHuman() public payable { bytes32 _name = _nameString.nameFilter(); address _addr = msg.sender; uint256 _paid = msg.value; (bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXnameFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all); uint256 _pID = pIDxAddr_[_addr]; // fire event emit F3Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now); } //============================================================================== // _ _ _|__|_ _ _ _ . // (_|(/_ | | (/_| _\ . (for UI & viewing things on etherscan) //=====_|======================================================================= /** * @dev return the price buyer will pay for next 1 individual key. * -functionhash- 0x018a25e8 * @return price for next key bought (in wei format) */ function getBuyPrice() public view returns(uint256) { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // are we in a round? if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) return ( (round_[_rID].keys.add(1000000000000000000)).ethRec(1000000000000000000) ); else // rounds over. need price for new round return ( 75000000000000 ); // init } /** * @dev returns time left. dont spam this, you'll ddos yourself from your node * provider * -functionhash- 0xc7e284b8 * @return time left in seconds */ function getTimeLeft() public view returns(uint256) { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; if (_now < round_[_rID].end) if (_now > round_[_rID].strt + rndGap_) return( (round_[_rID].end).sub(_now) ); else return( (round_[_rID].strt + rndGap_).sub(_now) ); else return(0); } /** * @dev returns player earnings per vaults * -functionhash- 0x63066434 * @return winnings vault * @return general vault * @return affiliate vault */ function getPlayerVaults(uint256 _pID) public view returns(uint256 ,uint256, uint256) { // setup local rID uint256 _rID = rID_; // if round has ended. but round end has not been run (so contract has not distributed winnings) if (now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0) { // if player is winner if (round_[_rID].plyr == _pID) { return ( (plyr_[_pID].win).add( ((round_[_rID].pot).mul(48)) / 100 ), (plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask) ), plyr_[_pID].aff ); // if player is not the winner } else { return ( plyr_[_pID].win, (plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask) ), plyr_[_pID].aff ); } // if round is still going on, or round has ended and round end has been ran } else { return ( plyr_[_pID].win, (plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)), plyr_[_pID].aff ); } } /** * solidity hates stack limits. this lets us avoid that hate */ function getPlayerVaultsHelper(uint256 _pID, uint256 _rID) private view returns(uint256) { return( ((((round_[_rID].mask).add(((((round_[_rID].pot).mul(potSplit_[round_[_rID].team].gen)) / 100).mul(1000000000000000000)) / (round_[_rID].keys))).mul(plyrRnds_[_pID][_rID].keys)) / 1000000000000000000) ); } /** * @dev returns all current round info needed for front end * -functionhash- 0x747dff42 * @return eth invested during ICO phase * @return round id * @return total keys for round * @return time round ends * @return time round started * @return current pot * @return current team ID & player ID in lead * @return current player in leads address * @return current player in leads name * @return whales eth in for round * @return bears eth in for round * @return sneks eth in for round * @return bulls eth in for round * @return airdrop tracker # & airdrop pot */ function getCurrentRoundInfo() public view returns(uint256, uint256, uint256, uint256, uint256, uint256, uint256, address, bytes32, uint256, uint256, uint256, uint256, uint256) { // setup local rID uint256 _rID = rID_; return ( round_[_rID].ico, //0 _rID, //1 round_[_rID].keys, //2 round_[_rID].end, //3 round_[_rID].strt, //4 round_[_rID].pot, //5 (round_[_rID].team + (round_[_rID].plyr * 10)), //6 plyr_[round_[_rID].plyr].addr, //7 plyr_[round_[_rID].plyr].name, //8 rndTmEth_[_rID][0], //9 rndTmEth_[_rID][1], //10 rndTmEth_[_rID][2], //11 rndTmEth_[_rID][3], //12 airDropTracker_ + (airDropPot_ * 1000) //13 ); } /** * @dev returns player info based on address. if no address is given, it will * use msg.sender * -functionhash- 0xee0b5d8b * @param _addr address of the player you want to lookup * @return player ID * @return player name * @return keys owned (current round) * @return winnings vault * @return general vault * @return affiliate vault * @return player round eth */ function getPlayerInfoByAddress(address _addr) public view returns(uint256, bytes32, uint256, uint256, uint256, uint256, uint256) { // setup local rID uint256 _rID = rID_; if (_addr == address(0)) { _addr == msg.sender; } uint256 _pID = pIDxAddr_[_addr]; return ( _pID, //0 plyr_[_pID].name, //1 plyrRnds_[_pID][_rID].keys, //2 plyr_[_pID].win, //3 (plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)), //4 plyr_[_pID].aff, //5 plyrRnds_[_pID][_rID].eth //6 ); } //============================================================================== // _ _ _ _ | _ _ . _ . // (_(_)| (/_ |(_)(_||(_ . (this + tools + calcs + modules = our softwares engine) //=====================_|======================================================= /** * @dev logic runs whenever a buy order is executed. determines how to handle * incoming eth depending on if we are in an active round or not */ function buyCore(uint256 _pID, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_) private { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // if round is active if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) { // call core core(_rID, _pID, msg.value, _affID, _team, _eventData_); // if round is not active } else { // check to see if end round needs to be ran if (_now > round_[_rID].end && round_[_rID].ended == false) { // end the round (distributes pot) & start new round round_[_rID].ended = true; _eventData_ = endRound(_eventData_); // build event data _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; // fire buy and distribute event emit F3Devents.onBuyAndDistribute ( msg.sender, plyr_[_pID].name, msg.value, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.P3DAmount, _eventData_.genAmount ); } // put eth in players vault plyr_[_pID].gen = plyr_[_pID].gen.add(msg.value); } } /** * @dev logic runs whenever a reload order is executed. determines how to handle * incoming eth depending on if we are in an active round or not */ function reLoadCore(uint256 _pID, uint256 _affID, uint256 _team, uint256 _eth, F3Ddatasets.EventReturns memory _eventData_) private { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // if round is active if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) { // get earnings from all vaults and return unused to gen vault // because we use a custom safemath library. this will throw if player // tried to spend more eth than they have. plyr_[_pID].gen = withdrawEarnings(_pID).sub(_eth); // call core core(_rID, _pID, _eth, _affID, _team, _eventData_); // if round is not active and end round needs to be ran } else if (_now > round_[_rID].end && round_[_rID].ended == false) { // end the round (distributes pot) & start new round round_[_rID].ended = true; _eventData_ = endRound(_eventData_); // build event data _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; // fire buy and distribute event emit F3Devents.onReLoadAndDistribute ( msg.sender, plyr_[_pID].name, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.P3DAmount, _eventData_.genAmount ); } } /** * @dev this is the core logic for any buy/reload that happens while a round * is live. */ function core(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_) private { // if player is new to round if (plyrRnds_[_pID][_rID].keys == 0) _eventData_ = managePlayer(_pID, _eventData_); // early round eth limiter if (round_[_rID].eth < 100000000000000000000 && plyrRnds_[_pID][_rID].eth.add(_eth) > 1000000000000000000) { uint256 _availableLimit = (1000000000000000000).sub(plyrRnds_[_pID][_rID].eth); uint256 _refund = _eth.sub(_availableLimit); plyr_[_pID].gen = plyr_[_pID].gen.add(_refund); _eth = _availableLimit; } // if eth left is greater than min eth allowed (sorry no pocket lint) if (_eth > 1000000000) { // mint the new keys uint256 _keys = (round_[_rID].eth).keysRec(_eth); // if they bought at least 1 whole key if (_keys >= 1000000000000000000) { updateTimer(_keys, _rID); // set new leaders if (round_[_rID].plyr != _pID) round_[_rID].plyr = _pID; if (round_[_rID].team != _team) round_[_rID].team = _team; // set the new leader bool to true _eventData_.compressedData = _eventData_.compressedData + 100; } // manage airdrops if (_eth >= 100000000000000000) { airDropTracker_++; if (airdrop() == true) { // gib muni uint256 _prize; if (_eth >= 10000000000000000000) { // calculate prize and give it to winner _prize = ((airDropPot_).mul(75)) / 100; plyr_[_pID].win = (plyr_[_pID].win).add(_prize); // adjust airDropPot airDropPot_ = (airDropPot_).sub(_prize); // let event know a tier 3 prize was won _eventData_.compressedData += 300000000000000000000000000000000; } else if (_eth >= 1000000000000000000 && _eth < 10000000000000000000) { // calculate prize and give it to winner _prize = ((airDropPot_).mul(50)) / 100; plyr_[_pID].win = (plyr_[_pID].win).add(_prize); // adjust airDropPot airDropPot_ = (airDropPot_).sub(_prize); // let event know a tier 2 prize was won _eventData_.compressedData += 200000000000000000000000000000000; } else if (_eth >= 100000000000000000 && _eth < 1000000000000000000) { // calculate prize and give it to winner _prize = ((airDropPot_).mul(25)) / 100; plyr_[_pID].win = (plyr_[_pID].win).add(_prize); // adjust airDropPot airDropPot_ = (airDropPot_).sub(_prize); // let event know a tier 3 prize was won _eventData_.compressedData += 300000000000000000000000000000000; } // set airdrop happened bool to true _eventData_.compressedData += 10000000000000000000000000000000; // let event know how much was won _eventData_.compressedData += _prize * 1000000000000000000000000000000000; // reset air drop tracker airDropTracker_ = 0; } } // store the air drop tracker number (number of buys since last airdrop) _eventData_.compressedData = _eventData_.compressedData + (airDropTracker_ * 1000); // update player plyrRnds_[_pID][_rID].keys = _keys.add(plyrRnds_[_pID][_rID].keys); plyrRnds_[_pID][_rID].eth = _eth.add(plyrRnds_[_pID][_rID].eth); // update round round_[_rID].keys = _keys.add(round_[_rID].keys); round_[_rID].eth = _eth.add(round_[_rID].eth); rndTmEth_[_rID][_team] = _eth.add(rndTmEth_[_rID][_team]); // distribute eth _eventData_ = distributeExternal(_rID, _pID, _eth, _affID, _team, _eventData_); _eventData_ = distributeInternal(_rID, _pID, _eth, _team, _keys, _eventData_); // call end tx function to fire end tx event. endTx(_pID, _team, _eth, _keys, _eventData_); } } //============================================================================== // _ _ | _ | _ _|_ _ _ _ . // (_(_||(_|_||(_| | (_)| _\ . //============================================================================== /** * @dev calculates unmasked earnings (just calculates, does not update mask) * @return earnings in wei format */ function calcUnMaskedEarnings(uint256 _pID, uint256 _rIDlast) private view returns(uint256) { return( (((round_[_rIDlast].mask).mul(plyrRnds_[_pID][_rIDlast].keys)) / (1000000000000000000)).sub(plyrRnds_[_pID][_rIDlast].mask) ); } /** * @dev returns the amount of keys you would get given an amount of eth. * -functionhash- 0xce89c80c * @param _rID round ID you want price for * @param _eth amount of eth sent in * @return keys received */ function calcKeysReceived(uint256 _rID, uint256 _eth) public view returns(uint256) { // grab time uint256 _now = now; // are we in a round? if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) return ( (round_[_rID].eth).keysRec(_eth) ); else // rounds over. need keys for new round return ( (_eth).keys() ); } /** * @dev returns current eth price for X keys. * -functionhash- 0xcf808000 * @param _keys number of keys desired (in 18 decimal format) * @return amount of eth needed to send */ function iWantXKeys(uint256 _keys) public view returns(uint256) { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // are we in a round? if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) return ( (round_[_rID].keys.add(_keys)).ethRec(_keys) ); else // rounds over. need price for new round return ( (_keys).eth() ); } //============================================================================== // _|_ _ _ | _ . // | (_)(_)|_\ . //============================================================================== /** * @dev receives name/player info from names contract */ function receivePlayerInfo(uint256 _pID, address _addr, bytes32 _name, uint256 _laff) external { require (msg.sender == address(PlayerBook), "your not playerNames contract... hmmm.."); if (pIDxAddr_[_addr] != _pID) pIDxAddr_[_addr] = _pID; if (pIDxName_[_name] != _pID) pIDxName_[_name] = _pID; if (plyr_[_pID].addr != _addr) plyr_[_pID].addr = _addr; if (plyr_[_pID].name != _name) plyr_[_pID].name = _name; if (plyr_[_pID].laff != _laff) plyr_[_pID].laff = _laff; if (plyrNames_[_pID][_name] == false) plyrNames_[_pID][_name] = true; } /** * @dev receives entire player name list */ function receivePlayerNameList(uint256 _pID, bytes32 _name) external { require (msg.sender == address(PlayerBook), "your not playerNames contract... hmmm.."); if(plyrNames_[_pID][_name] == false) plyrNames_[_pID][_name] = true; } /** * @dev gets existing or registers new pID. use this when a player may be new * @return pID */ function determinePID(F3Ddatasets.EventReturns memory _eventData_) private returns (F3Ddatasets.EventReturns) { uint256 _pID = pIDxAddr_[msg.sender]; // if player is new to this version of fomo3d if (_pID == 0) { // grab their player ID, name and last aff ID, from player names contract _pID = PlayerBook.getPlayerID(msg.sender); bytes32 _name = PlayerBook.getPlayerName(_pID); uint256 _laff = PlayerBook.getPlayerLAff(_pID); // set up player account pIDxAddr_[msg.sender] = _pID; plyr_[_pID].addr = msg.sender; if (_name != "") { pIDxName_[_name] = _pID; plyr_[_pID].name = _name; plyrNames_[_pID][_name] = true; } if (_laff != 0 && _laff != _pID) plyr_[_pID].laff = _laff; // set the new player bool to true _eventData_.compressedData = _eventData_.compressedData + 1; } return (_eventData_); } /** * @dev checks to make sure user picked a valid team. if not sets team * to default (sneks) */ function verifyTeam(uint256 _team) private pure returns (uint256) { if (_team < 0 || _team > 3) return(2); else return(_team); } /** * @dev decides if round end needs to be run & new round started. and if * player unmasked earnings from previously played rounds need to be moved. */ function managePlayer(uint256 _pID, F3Ddatasets.EventReturns memory _eventData_) private returns (F3Ddatasets.EventReturns) { // if player has played a previous round, move their unmasked earnings // from that round to gen vault. if (plyr_[_pID].lrnd != 0) updateGenVault(_pID, plyr_[_pID].lrnd); // update player's last round played plyr_[_pID].lrnd = rID_; // set the joined round bool to true _eventData_.compressedData = _eventData_.compressedData + 10; return(_eventData_); } /** * @dev ends the round. manages paying out winner/splitting up pot */ function endRound(F3Ddatasets.EventReturns memory _eventData_) private returns (F3Ddatasets.EventReturns) { // setup local rID uint256 _rID = rID_; // grab our winning player and team id's uint256 _winPID = round_[_rID].plyr; uint256 _winTID = round_[_rID].team; // grab our pot amount uint256 _pot = round_[_rID].pot; // calculate our winner share, community rewards, gen share, // p3d share, and amount reserved for next pot uint256 _win = (_pot.mul(48)) / 100; uint256 _com = (_pot.mul(20)) / 100; uint256 _gen = (_pot.mul(potSplit_[_winTID].gen)) / 100; uint256 _p3d = (_pot.mul(potSplit_[_winTID].p3d)) / 100; uint256 _res = (((_pot.sub(_win)).sub(_com)).sub(_gen)).sub(_p3d); // calculate ppt for round mask uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys); uint256 _dust = _gen.sub((_ppt.mul(round_[_rID].keys)) / 1000000000000000000); if (_dust > 0) { _gen = _gen.sub(_dust); _res = _res.add(_dust); } // pay our winner plyr_[_winPID].win = _win.add(plyr_[_winPID].win); // community rewards admin1.transfer(_com.sub(_com / 2)); admin2.transfer(_com / 2); round_[_rID].pot = _pot.add(_p3d); // distribute gen portion to key holders round_[_rID].mask = _ppt.add(round_[_rID].mask); // prepare event data _eventData_.compressedData = _eventData_.compressedData + (round_[_rID].end * 1000000); _eventData_.compressedIDs = _eventData_.compressedIDs + (_winPID * 100000000000000000000000000) + (_winTID * 100000000000000000); _eventData_.winnerAddr = plyr_[_winPID].addr; _eventData_.winnerName = plyr_[_winPID].name; _eventData_.amountWon = _win; _eventData_.genAmount = _gen; _eventData_.P3DAmount = _p3d; _eventData_.newPot = _res; // start next round rID_++; _rID++; round_[_rID].strt = now; round_[_rID].end = now.add(rndInit_).add(rndGap_); round_[_rID].pot = _res; return(_eventData_); } /** * @dev moves any unmasked earnings to gen vault. updates earnings mask */ function updateGenVault(uint256 _pID, uint256 _rIDlast) private { uint256 _earnings = calcUnMaskedEarnings(_pID, _rIDlast); if (_earnings > 0) { // put in gen vault plyr_[_pID].gen = _earnings.add(plyr_[_pID].gen); // zero out their earnings by updating mask plyrRnds_[_pID][_rIDlast].mask = _earnings.add(plyrRnds_[_pID][_rIDlast].mask); } } /** * @dev updates round timer based on number of whole keys bought. */ function updateTimer(uint256 _keys, uint256 _rID) private { // grab time uint256 _now = now; // calculate time based on number of keys bought uint256 _newTime; if (_now > round_[_rID].end && round_[_rID].plyr == 0) _newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(_now); else _newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(round_[_rID].end); // compare to max and set new end time if (_newTime < (rndMax_).add(_now)) round_[_rID].end = _newTime; else round_[_rID].end = rndMax_.add(_now); } /** * @dev generates a random number between 0-99 and checks to see if thats * resulted in an airdrop win * @return do we have a winner? */ function airdrop() private view returns(bool) { uint256 seed = uint256(keccak256(abi.encodePacked( (block.timestamp).add (block.difficulty).add ((uint256(keccak256(abi.encodePacked(block.coinbase)))) / (now)).add (block.gaslimit).add ((uint256(keccak256(abi.encodePacked(msg.sender)))) / (now)).add (block.number) ))); if((seed - ((seed / 1000) * 1000)) < airDropTracker_) return(true); else return(false); } <FILL_FUNCTION> /** * @dev distributes eth based on fees to gen and pot */ function distributeInternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _team, uint256 _keys, F3Ddatasets.EventReturns memory _eventData_) private returns(F3Ddatasets.EventReturns) { // calculate gen share uint256 _gen = (_eth.mul(fees_[_team].gen)) / 100; // toss 1% into airdrop pot uint256 _air = (_eth / 100); airDropPot_ = airDropPot_.add(_air); // update eth balance (eth = eth - (com share + pot swap share + aff share + p3d share + airdrop pot share)) _eth = _eth.sub(((_eth.mul(14)) / 100).add((_eth.mul(fees_[_team].p3d)) / 100)); // calculate pot uint256 _pot = _eth.sub(_gen); // distribute gen share (thats what updateMasks() does) and adjust // balances for dust. uint256 _dust = updateMasks(_rID, _pID, _gen, _keys); if (_dust > 0) _gen = _gen.sub(_dust); // add eth to pot round_[_rID].pot = _pot.add(_dust).add(round_[_rID].pot); // set up event data _eventData_.genAmount = _gen.add(_eventData_.genAmount); _eventData_.potAmount = _pot; return(_eventData_); } /** * @dev updates masks for round and player when keys are bought * @return dust left over */ function updateMasks(uint256 _rID, uint256 _pID, uint256 _gen, uint256 _keys) private returns(uint256) { /* MASKING NOTES earnings masks are a tricky thing for people to wrap their minds around. the basic thing to understand here. is were going to have a global tracker based on profit per share for each round, that increases in relevant proportion to the increase in share supply. the player will have an additional mask that basically says "based on the rounds mask, my shares, and how much i've already withdrawn, how much is still owed to me?" */ // calc profit per key & round mask based on this buy: (dust goes to pot) uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys); round_[_rID].mask = _ppt.add(round_[_rID].mask); // calculate player earning from their own buy (only based on the keys // they just bought). & update player earnings mask uint256 _pearn = (_ppt.mul(_keys)) / (1000000000000000000); plyrRnds_[_pID][_rID].mask = (((round_[_rID].mask.mul(_keys)) / (1000000000000000000)).sub(_pearn)).add(plyrRnds_[_pID][_rID].mask); // calculate & return dust return(_gen.sub((_ppt.mul(round_[_rID].keys)) / (1000000000000000000))); } /** * @dev adds up unmasked earnings, & vault earnings, sets them all to 0 * @return earnings in wei format */ function withdrawEarnings(uint256 _pID) private returns(uint256) { // update gen vault updateGenVault(_pID, plyr_[_pID].lrnd); // from vaults uint256 _earnings = (plyr_[_pID].win).add(plyr_[_pID].gen).add(plyr_[_pID].aff); if (_earnings > 0) { plyr_[_pID].win = 0; plyr_[_pID].gen = 0; plyr_[_pID].aff = 0; } return(_earnings); } /** * @dev prepares compression data and fires event for buy or reload tx's */ function endTx(uint256 _pID, uint256 _team, uint256 _eth, uint256 _keys, F3Ddatasets.EventReturns memory _eventData_) private { _eventData_.compressedData = _eventData_.compressedData + (now * 1000000000000000000) + (_team * 100000000000000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID + (rID_ * 10000000000000000000000000000000000000000000000000000); emit F3Devents.onEndTx ( _eventData_.compressedData, _eventData_.compressedIDs, plyr_[_pID].name, msg.sender, _eth, _keys, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.P3DAmount, _eventData_.genAmount, _eventData_.potAmount, airDropPot_ ); } //============================================================================== // (~ _ _ _._|_ . // _)(/_(_|_|| | | \/ . //====================/========================================================= /** upon contract deploy, it will be deactivated. this is a one time * use function that will activate the contract. we do this so devs * have time to set things up on the web end **/ bool public activated_ = false; function activate() public { // only team just can activate require((msg.sender == admin1 || msg.sender == admin2), "only admin can activate"); // can only be ran once require(activated_ == false, "already activated"); // activate the contract activated_ = true; // lets start first round rID_ = 1; round_[1].strt = now + rndExtra_ - rndGap_; round_[1].end = now + rndInit_ + rndExtra_; } }
// pay 3% out to community rewards uint256 _p1 = _eth / 100; uint256 _com = _eth / 50; _com = _com.add(_p1); uint256 _p3d = 0; if (!address(admin1).call.value(_com.sub(_com / 2))()) { // This ensures Team Just cannot influence the outcome of FoMo3D with // bank migrations by breaking outgoing transactions. // Something we would never do. But that's not the point. // We spent 2000$ in eth re-deploying just to patch this, we hold the // highest belief that everything we create should be trustless. // Team JUST, The name you shouldn't have to trust. _p3d = _p3d.add(_com.sub(_com / 2)); } if (!address(admin2).call.value(_com / 2)()) { _p3d = _p3d.add(_com / 2); } _com = _com.sub(_p3d); // distribute share to affiliate uint256 _aff = _eth / 10; // decide what to do with affiliate share of fees // affiliate must not be self, and must have a name registered if (_affID != _pID && plyr_[_affID].name != '') { plyr_[_affID].aff = _aff.add(plyr_[_affID].aff); emit F3Devents.onAffiliatePayout(_affID, plyr_[_affID].addr, plyr_[_affID].name, _rID, _pID, _aff, now); } else { _p3d = _p3d.add(_aff); } // pay out p3d _p3d = _p3d.add((_eth.mul(fees_[_team].p3d)) / (100)); if (_p3d > 0) { round_[_rID].pot = round_[_rID].pot.add(_p3d); // set up event data _eventData_.P3DAmount = _p3d.add(_eventData_.P3DAmount); } return(_eventData_);
function distributeExternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_) private returns(F3Ddatasets.EventReturns)
/** * @dev distributes eth based on fees to com, aff, and p3d */ function distributeExternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_) private returns(F3Ddatasets.EventReturns)
12899
BurnableToken
burn
contract BurnableToken is BasicToken { 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 BasicToken { event Burn(address indexed burner, uint256 value); <FILL_FUNCTION> }
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
36956
MaxShiba
approve
contract MaxShiba 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 = "Max Shiba"; symbol = "maxSHIB"; decimals = 18; _totalSupply = 1000000000000000000000000000000; balances[msg.sender] = 1000000000000000000000000000000; 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) {<FILL_FUNCTION_BODY> } 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 MaxShiba 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 = "Max Shiba"; symbol = "maxSHIB"; decimals = 18; _totalSupply = 1000000000000000000000000000000; balances[msg.sender] = 1000000000000000000000000000000; 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]; } <FILL_FUNCTION> 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; } }
allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true;
function approve(address spender, uint tokens) public returns (bool success)
function approve(address spender, uint tokens) public returns (bool success)
88218
StakePoolEpochReward
null
contract StakePoolEpochReward is IStakePoolEpochReward { using SafeMath for uint256; uint256 public override version; /* ========== DATA STRUCTURES ========== */ struct UserInfo { uint256 amount; uint256 lastSnapshotIndex; uint256 rewardEarned; uint256 epochTimerStart; } struct Snapshot { uint256 time; uint256 rewardReceived; uint256 rewardPerShare; } /* ========== STATE VARIABLES ========== */ address public epochController; address public rewardToken; uint256 public withdrawLockupEpochs; uint256 public rewardLockupEpochs; mapping(address => UserInfo) public userInfo; Snapshot[] public snapshotHistory; address public override pair; address public rewardFund; address public timelock; address public controller; uint256 public balance; uint256 private _unlocked = 1; bool private _initialized = false; constructor(address _controller, uint256 _version) {<FILL_FUNCTION_BODY> } modifier lock() { require(_unlocked == 1, "StakePoolEpochReward: LOCKED"); _unlocked = 0; _; _unlocked = 1; } modifier onlyTimeLock() { require(msg.sender == timelock, "StakePoolEpochReward: !timelock"); _; } modifier onlyEpochController() { require(msg.sender == epochController, "StakePoolEpochReward: !epochController"); _; } modifier updateReward(address _account) { if (_account != address(0)) { UserInfo storage user = userInfo[_account]; user.rewardEarned = earned(_account); user.lastSnapshotIndex = latestSnapshotIndex(); } _; } // called once by the factory at time of deployment function initialize( address _pair, address _rewardFund, address _timelock, address _epochController, address _rewardToken, uint256 _withdrawLockupEpochs, uint256 _rewardLockupEpochs ) external { require(_initialized == false, "StakePoolEpochReward: Initialize must be false."); pair = _pair; rewardFund = _rewardFund; timelock = _timelock; withdrawLockupEpochs = _withdrawLockupEpochs; rewardLockupEpochs = _rewardLockupEpochs; epochController = _epochController; rewardToken = _rewardToken; _initialized = true; } /* ========== GOVERNANCE ========== */ function setEpochController(address _epochController) external override lock onlyTimeLock { epochController = _epochController; } function setLockUp(uint256 _withdrawLockupEpochs, uint256 _rewardLockupEpochs) external override lock onlyTimeLock { require(_withdrawLockupEpochs >= _rewardLockupEpochs && _withdrawLockupEpochs <= 56, "_withdrawLockupEpochs: out of range"); // <= 2 week withdrawLockupEpochs = _withdrawLockupEpochs; rewardLockupEpochs = _rewardLockupEpochs; } function allocateReward(uint256 _amount) external override lock onlyEpochController { require(_amount > 0, "StakePoolEpochReward: Cannot allocate 0"); uint256 _before = IERC20(rewardToken).balanceOf(address(rewardFund)); TransferHelper.safeTransferFrom(rewardToken, msg.sender, rewardFund, _amount); if (balance > 0) { uint256 _after = IERC20(rewardToken).balanceOf(address(rewardFund)); _amount = _after.sub(_before); // Create & add new snapshot uint256 _prevRPS = getLatestSnapshot().rewardPerShare; uint256 _nextRPS = _prevRPS.add(_amount.mul(1e18).div(balance)); Snapshot memory _newSnapshot = Snapshot({time: block.number, rewardReceived: _amount, rewardPerShare: _nextRPS}); emit AllocateReward(block.number, _amount); snapshotHistory.push(_newSnapshot); } } function allowRecoverRewardToken(address _token) external view override returns (bool) { if (rewardToken == _token) { // do not allow to drain reward token if less than 1 months after pool ends if (block.timestamp < (getLatestSnapshot().time + 7 days)) { return false; } } return true; } // =========== Epoch getters function epoch() public view override returns (uint256) { return IEpochController(epochController).epoch(); } function nextEpochPoint() external view override returns (uint256) { return IEpochController(epochController).nextEpochPoint(); } function nextEpochLength() external view override returns (uint256) { return IEpochController(epochController).nextEpochLength(); } function nextEpochAllocatedReward() external view override returns (uint256) { return IEpochController(epochController).nextEpochAllocatedReward(address(this)); } // =========== Snapshot getters function latestSnapshotIndex() public view returns (uint256) { return snapshotHistory.length.sub(1); } function getLatestSnapshot() internal view returns (Snapshot memory) { return snapshotHistory[latestSnapshotIndex()]; } function getLastSnapshotIndexOf(address _account) public view returns (uint256) { return userInfo[_account].lastSnapshotIndex; } function getLastSnapshotOf(address _account) internal view returns (Snapshot memory) { return snapshotHistory[getLastSnapshotIndexOf(_account)]; } // =========== _account getters function rewardPerShare() public view returns (uint256) { return getLatestSnapshot().rewardPerShare; } function earned(address _account) public view override returns (uint256) { uint256 latestRPS = getLatestSnapshot().rewardPerShare; uint256 storedRPS = getLastSnapshotOf(_account).rewardPerShare; UserInfo memory user = userInfo[_account]; return user.amount.mul(latestRPS.sub(storedRPS)).div(1e18).add(user.rewardEarned); } function canWithdraw(address _account) external view returns (bool) { return userInfo[_account].epochTimerStart.add(withdrawLockupEpochs) <= epoch(); } function canClaimReward(address _account) external view returns (bool) { return userInfo[_account].epochTimerStart.add(rewardLockupEpochs) <= epoch(); } function unlockWithdrawEpoch(address _account) public view override returns (uint256) { return userInfo[_account].epochTimerStart.add(withdrawLockupEpochs); } function unlockRewardEpoch(address _account) public view override returns (uint256) { return userInfo[_account].epochTimerStart.add(rewardLockupEpochs); } /* ========== MUTATIVE FUNCTIONS ========== */ function stake(uint256 _amount) external override lock { IValueLiquidPair(pair).transferFrom(msg.sender, address(this), _amount); _stakeFor(msg.sender); } function stakeFor(address _account) external override lock { require(IStakePoolController(controller).isWhitelistStakingFor(msg.sender), "StakePoolEpochReward: Invalid sender"); _stakeFor(_account); } function _stakeFor(address _account) internal { uint256 _amount = IValueLiquidPair(pair).balanceOf(address(this)).sub(balance); require(_amount > 0, "StakePoolEpochReward: Invalid balance"); balance = balance.add(_amount); UserInfo storage user = userInfo[_account]; user.epochTimerStart = epoch(); // reset timer user.amount = user.amount.add(_amount); emit Deposit(_account, _amount); } function removeStakeInternal(uint256 _amount) internal { UserInfo storage user = userInfo[msg.sender]; uint256 _epoch = epoch(); require(user.epochTimerStart.add(withdrawLockupEpochs) <= _epoch, "StakePoolEpochReward: still in withdraw lockup"); require(user.amount >= _amount, "StakePoolEpochReward: invalid withdraw amount"); _claimReward(false); balance = balance.sub(_amount); user.epochTimerStart = _epoch; // reset timer user.amount = user.amount.sub(_amount); } function withdraw(uint256 _amount) public override lock { removeStakeInternal(_amount); IValueLiquidPair(pair).transfer(msg.sender, _amount); emit Withdraw(msg.sender, _amount); } function exit() external { withdraw(userInfo[msg.sender].amount); } function _claimReward(bool _lockChecked) internal updateReward(msg.sender) { UserInfo storage user = userInfo[msg.sender]; uint256 _reward = user.rewardEarned; if (_reward > 0) { if (_lockChecked) { uint256 _epoch = epoch(); require(user.epochTimerStart.add(rewardLockupEpochs) <= _epoch, "StakePoolEpochReward: still in reward lockup"); user.epochTimerStart = _epoch; // reset timer } user.rewardEarned = 0; // Safe reward transfer, just in case if rounding error causes pool to not have enough reward amount uint256 _rewardBalance = IERC20(rewardToken).balanceOf(rewardFund); uint256 _paidAmount = _rewardBalance > _reward ? _reward : _rewardBalance; IStakePoolRewardFund(rewardFund).safeTransfer(rewardToken, msg.sender, _paidAmount); emit PayRewardPool(0, rewardToken, msg.sender, _reward, _reward, _paidAmount); } } function claimReward() public override { _claimReward(true); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw() external override lock { require(IStakePoolController(controller).isAllowEmergencyWithdrawStakePool(address(this)), "StakePoolEpochReward: Not allow emergencyWithdraw"); UserInfo storage user = userInfo[msg.sender]; uint256 amount = user.amount; balance = balance.sub(amount); user.amount = 0; IValueLiquidPair(pair).transfer(msg.sender, amount); } function removeLiquidity( address provider, address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) public override lock returns (uint256 amountA, uint256 amountB) { require(IStakePoolController(controller).isWhitelistStakingFor(provider), "StakePoolEpochReward: Invalid provider"); removeStakeInternal(liquidity); IValueLiquidPair(pair).approve(provider, liquidity); emit Withdraw(msg.sender, liquidity); (amountA, amountB) = IValueLiquidProvider(provider).removeLiquidity(address(pair), tokenA, tokenB, liquidity, amountAMin, amountBMin, to, deadline); } function removeLiquidityETH( address provider, address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external override lock returns (uint256 amountToken, uint256 amountETH) { require(IStakePoolController(controller).isWhitelistStakingFor(provider), "StakePoolEpochReward: Invalid provider"); removeStakeInternal(liquidity); IValueLiquidPair(pair).approve(provider, liquidity); emit Withdraw(msg.sender, liquidity); (amountToken, amountETH) = IValueLiquidProvider(provider).removeLiquidityETH( address(pair), token, liquidity, amountTokenMin, amountETHMin, to, deadline ); } function removeLiquidityETHSupportingFeeOnTransferTokens( address provider, address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external override lock returns (uint256 amountETH) { require(IStakePoolController(controller).isWhitelistStakingFor(provider), "StakePoolEpochReward: Invalid provider"); removeStakeInternal(liquidity); IValueLiquidPair(pair).approve(provider, liquidity); emit Withdraw(msg.sender, liquidity); amountETH = IValueLiquidProvider(provider).removeLiquidityETHSupportingFeeOnTransferTokens( address(pair), token, liquidity, amountTokenMin, amountETHMin, to, deadline ); } }
contract StakePoolEpochReward is IStakePoolEpochReward { using SafeMath for uint256; uint256 public override version; /* ========== DATA STRUCTURES ========== */ struct UserInfo { uint256 amount; uint256 lastSnapshotIndex; uint256 rewardEarned; uint256 epochTimerStart; } struct Snapshot { uint256 time; uint256 rewardReceived; uint256 rewardPerShare; } /* ========== STATE VARIABLES ========== */ address public epochController; address public rewardToken; uint256 public withdrawLockupEpochs; uint256 public rewardLockupEpochs; mapping(address => UserInfo) public userInfo; Snapshot[] public snapshotHistory; address public override pair; address public rewardFund; address public timelock; address public controller; uint256 public balance; uint256 private _unlocked = 1; bool private _initialized = false; <FILL_FUNCTION> modifier lock() { require(_unlocked == 1, "StakePoolEpochReward: LOCKED"); _unlocked = 0; _; _unlocked = 1; } modifier onlyTimeLock() { require(msg.sender == timelock, "StakePoolEpochReward: !timelock"); _; } modifier onlyEpochController() { require(msg.sender == epochController, "StakePoolEpochReward: !epochController"); _; } modifier updateReward(address _account) { if (_account != address(0)) { UserInfo storage user = userInfo[_account]; user.rewardEarned = earned(_account); user.lastSnapshotIndex = latestSnapshotIndex(); } _; } // called once by the factory at time of deployment function initialize( address _pair, address _rewardFund, address _timelock, address _epochController, address _rewardToken, uint256 _withdrawLockupEpochs, uint256 _rewardLockupEpochs ) external { require(_initialized == false, "StakePoolEpochReward: Initialize must be false."); pair = _pair; rewardFund = _rewardFund; timelock = _timelock; withdrawLockupEpochs = _withdrawLockupEpochs; rewardLockupEpochs = _rewardLockupEpochs; epochController = _epochController; rewardToken = _rewardToken; _initialized = true; } /* ========== GOVERNANCE ========== */ function setEpochController(address _epochController) external override lock onlyTimeLock { epochController = _epochController; } function setLockUp(uint256 _withdrawLockupEpochs, uint256 _rewardLockupEpochs) external override lock onlyTimeLock { require(_withdrawLockupEpochs >= _rewardLockupEpochs && _withdrawLockupEpochs <= 56, "_withdrawLockupEpochs: out of range"); // <= 2 week withdrawLockupEpochs = _withdrawLockupEpochs; rewardLockupEpochs = _rewardLockupEpochs; } function allocateReward(uint256 _amount) external override lock onlyEpochController { require(_amount > 0, "StakePoolEpochReward: Cannot allocate 0"); uint256 _before = IERC20(rewardToken).balanceOf(address(rewardFund)); TransferHelper.safeTransferFrom(rewardToken, msg.sender, rewardFund, _amount); if (balance > 0) { uint256 _after = IERC20(rewardToken).balanceOf(address(rewardFund)); _amount = _after.sub(_before); // Create & add new snapshot uint256 _prevRPS = getLatestSnapshot().rewardPerShare; uint256 _nextRPS = _prevRPS.add(_amount.mul(1e18).div(balance)); Snapshot memory _newSnapshot = Snapshot({time: block.number, rewardReceived: _amount, rewardPerShare: _nextRPS}); emit AllocateReward(block.number, _amount); snapshotHistory.push(_newSnapshot); } } function allowRecoverRewardToken(address _token) external view override returns (bool) { if (rewardToken == _token) { // do not allow to drain reward token if less than 1 months after pool ends if (block.timestamp < (getLatestSnapshot().time + 7 days)) { return false; } } return true; } // =========== Epoch getters function epoch() public view override returns (uint256) { return IEpochController(epochController).epoch(); } function nextEpochPoint() external view override returns (uint256) { return IEpochController(epochController).nextEpochPoint(); } function nextEpochLength() external view override returns (uint256) { return IEpochController(epochController).nextEpochLength(); } function nextEpochAllocatedReward() external view override returns (uint256) { return IEpochController(epochController).nextEpochAllocatedReward(address(this)); } // =========== Snapshot getters function latestSnapshotIndex() public view returns (uint256) { return snapshotHistory.length.sub(1); } function getLatestSnapshot() internal view returns (Snapshot memory) { return snapshotHistory[latestSnapshotIndex()]; } function getLastSnapshotIndexOf(address _account) public view returns (uint256) { return userInfo[_account].lastSnapshotIndex; } function getLastSnapshotOf(address _account) internal view returns (Snapshot memory) { return snapshotHistory[getLastSnapshotIndexOf(_account)]; } // =========== _account getters function rewardPerShare() public view returns (uint256) { return getLatestSnapshot().rewardPerShare; } function earned(address _account) public view override returns (uint256) { uint256 latestRPS = getLatestSnapshot().rewardPerShare; uint256 storedRPS = getLastSnapshotOf(_account).rewardPerShare; UserInfo memory user = userInfo[_account]; return user.amount.mul(latestRPS.sub(storedRPS)).div(1e18).add(user.rewardEarned); } function canWithdraw(address _account) external view returns (bool) { return userInfo[_account].epochTimerStart.add(withdrawLockupEpochs) <= epoch(); } function canClaimReward(address _account) external view returns (bool) { return userInfo[_account].epochTimerStart.add(rewardLockupEpochs) <= epoch(); } function unlockWithdrawEpoch(address _account) public view override returns (uint256) { return userInfo[_account].epochTimerStart.add(withdrawLockupEpochs); } function unlockRewardEpoch(address _account) public view override returns (uint256) { return userInfo[_account].epochTimerStart.add(rewardLockupEpochs); } /* ========== MUTATIVE FUNCTIONS ========== */ function stake(uint256 _amount) external override lock { IValueLiquidPair(pair).transferFrom(msg.sender, address(this), _amount); _stakeFor(msg.sender); } function stakeFor(address _account) external override lock { require(IStakePoolController(controller).isWhitelistStakingFor(msg.sender), "StakePoolEpochReward: Invalid sender"); _stakeFor(_account); } function _stakeFor(address _account) internal { uint256 _amount = IValueLiquidPair(pair).balanceOf(address(this)).sub(balance); require(_amount > 0, "StakePoolEpochReward: Invalid balance"); balance = balance.add(_amount); UserInfo storage user = userInfo[_account]; user.epochTimerStart = epoch(); // reset timer user.amount = user.amount.add(_amount); emit Deposit(_account, _amount); } function removeStakeInternal(uint256 _amount) internal { UserInfo storage user = userInfo[msg.sender]; uint256 _epoch = epoch(); require(user.epochTimerStart.add(withdrawLockupEpochs) <= _epoch, "StakePoolEpochReward: still in withdraw lockup"); require(user.amount >= _amount, "StakePoolEpochReward: invalid withdraw amount"); _claimReward(false); balance = balance.sub(_amount); user.epochTimerStart = _epoch; // reset timer user.amount = user.amount.sub(_amount); } function withdraw(uint256 _amount) public override lock { removeStakeInternal(_amount); IValueLiquidPair(pair).transfer(msg.sender, _amount); emit Withdraw(msg.sender, _amount); } function exit() external { withdraw(userInfo[msg.sender].amount); } function _claimReward(bool _lockChecked) internal updateReward(msg.sender) { UserInfo storage user = userInfo[msg.sender]; uint256 _reward = user.rewardEarned; if (_reward > 0) { if (_lockChecked) { uint256 _epoch = epoch(); require(user.epochTimerStart.add(rewardLockupEpochs) <= _epoch, "StakePoolEpochReward: still in reward lockup"); user.epochTimerStart = _epoch; // reset timer } user.rewardEarned = 0; // Safe reward transfer, just in case if rounding error causes pool to not have enough reward amount uint256 _rewardBalance = IERC20(rewardToken).balanceOf(rewardFund); uint256 _paidAmount = _rewardBalance > _reward ? _reward : _rewardBalance; IStakePoolRewardFund(rewardFund).safeTransfer(rewardToken, msg.sender, _paidAmount); emit PayRewardPool(0, rewardToken, msg.sender, _reward, _reward, _paidAmount); } } function claimReward() public override { _claimReward(true); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw() external override lock { require(IStakePoolController(controller).isAllowEmergencyWithdrawStakePool(address(this)), "StakePoolEpochReward: Not allow emergencyWithdraw"); UserInfo storage user = userInfo[msg.sender]; uint256 amount = user.amount; balance = balance.sub(amount); user.amount = 0; IValueLiquidPair(pair).transfer(msg.sender, amount); } function removeLiquidity( address provider, address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) public override lock returns (uint256 amountA, uint256 amountB) { require(IStakePoolController(controller).isWhitelistStakingFor(provider), "StakePoolEpochReward: Invalid provider"); removeStakeInternal(liquidity); IValueLiquidPair(pair).approve(provider, liquidity); emit Withdraw(msg.sender, liquidity); (amountA, amountB) = IValueLiquidProvider(provider).removeLiquidity(address(pair), tokenA, tokenB, liquidity, amountAMin, amountBMin, to, deadline); } function removeLiquidityETH( address provider, address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external override lock returns (uint256 amountToken, uint256 amountETH) { require(IStakePoolController(controller).isWhitelistStakingFor(provider), "StakePoolEpochReward: Invalid provider"); removeStakeInternal(liquidity); IValueLiquidPair(pair).approve(provider, liquidity); emit Withdraw(msg.sender, liquidity); (amountToken, amountETH) = IValueLiquidProvider(provider).removeLiquidityETH( address(pair), token, liquidity, amountTokenMin, amountETHMin, to, deadline ); } function removeLiquidityETHSupportingFeeOnTransferTokens( address provider, address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external override lock returns (uint256 amountETH) { require(IStakePoolController(controller).isWhitelistStakingFor(provider), "StakePoolEpochReward: Invalid provider"); removeStakeInternal(liquidity); IValueLiquidPair(pair).approve(provider, liquidity); emit Withdraw(msg.sender, liquidity); amountETH = IValueLiquidProvider(provider).removeLiquidityETHSupportingFeeOnTransferTokens( address(pair), token, liquidity, amountTokenMin, amountETHMin, to, deadline ); } }
controller = _controller; timelock = msg.sender; version = _version; Snapshot memory genesisSnapshot = Snapshot({time: block.number, rewardReceived: 0, rewardPerShare: 0}); snapshotHistory.push(genesisSnapshot);
constructor(address _controller, uint256 _version)
constructor(address _controller, uint256 _version)
13814
Glow
transferFrom
contract Glow is Context, IERC20, Ownable { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _rOwned; mapping (address => uint256) private _tOwned; mapping (address => mapping (address => uint256)) private _allowances; mapping (address => bool) private _isExcluded; address[] private _excluded; uint256 private constant MAX = ~uint256(0); uint256 private constant _tTotal = 100000 * 10**6 * 10**9; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; string private _name = 'Glow Token'; string private _symbol = 'GLOW'; uint8 private _decimals = 8; constructor () public { _rOwned[_msgSender()] = _rTotal; emit Transfer(address(0), _msgSender(), _tTotal); } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } function totalSupply() public view override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { if (_isExcluded[account]) return _tOwned[account]; return tokenFromReflection(_rOwned[account]); } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) {<FILL_FUNCTION_BODY> } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function isExcluded(address account) public view returns (bool) { return _isExcluded[account]; } function totalFees() public view returns (uint256) { return _tFeeTotal; } function reflect(uint256 tAmount) public { address sender = _msgSender(); require(!_isExcluded[sender], "Excluded addresses cannot call this function"); (uint256 rAmount,,,,) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rTotal = _rTotal.sub(rAmount); _tFeeTotal = _tFeeTotal.add(tAmount); } function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns(uint256) { require(tAmount <= _tTotal, "Amount must be less than supply"); if (!deductTransferFee) { (uint256 rAmount,,,,) = _getValues(tAmount); return rAmount; } else { (,uint256 rTransferAmount,,,) = _getValues(tAmount); return rTransferAmount; } } function tokenFromReflection(uint256 rAmount) public view returns(uint256) { require(rAmount <= _rTotal, "Amount must be less than total reflections"); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function excludeAccount(address account) external onlyOwner() { require(!_isExcluded[account], "Account is already excluded"); if(_rOwned[account] > 0) { _tOwned[account] = tokenFromReflection(_rOwned[account]); } _isExcluded[account] = true; _excluded.push(account); } function includeAccount(address account) external onlyOwner() { require(_isExcluded[account], "Account is already excluded"); for (uint256 i = 0; i < _excluded.length; i++) { if (_excluded[i] == account) { _excluded[i] = _excluded[_excluded.length - 1]; _tOwned[account] = 0; _isExcluded[account] = false; _excluded.pop(); break; } } } function _approve(address owner, address spender, uint256 amount) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _transfer(address sender, address recipient, uint256 amount) private { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if (_isExcluded[sender] && !_isExcluded[recipient]) { _transferFromExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && _isExcluded[recipient]) { _transferToExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && !_isExcluded[recipient]) { _transferStandard(sender, recipient, amount); } else if (_isExcluded[sender] && _isExcluded[recipient]) { _transferBothExcluded(sender, recipient, amount); } else { _transferStandard(sender, recipient, amount); } } function _transferStandard(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferToExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferFromExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferBothExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256) { (uint256 tTransferAmount, uint256 tFee) = _getTValues(tAmount); uint256 currentRate = _getRate(); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, currentRate); return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee); } function _getTValues(uint256 tAmount) private pure returns (uint256, uint256) { uint256 tFee = tAmount.div(100).mul(2); uint256 tTransferAmount = tAmount.sub(tFee); return (tTransferAmount, tFee); } function _getRValues(uint256 tAmount, uint256 tFee, uint256 currentRate) private pure returns (uint256, uint256, uint256) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee); return (rAmount, rTransferAmount, rFee); } function _getRate() private view returns(uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply.div(tSupply); } function _getCurrentSupply() private view returns(uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; for (uint256 i = 0; i < _excluded.length; i++) { if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal); rSupply = rSupply.sub(_rOwned[_excluded[i]]); tSupply = tSupply.sub(_tOwned[_excluded[i]]); } if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } }
contract Glow is Context, IERC20, Ownable { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _rOwned; mapping (address => uint256) private _tOwned; mapping (address => mapping (address => uint256)) private _allowances; mapping (address => bool) private _isExcluded; address[] private _excluded; uint256 private constant MAX = ~uint256(0); uint256 private constant _tTotal = 100000 * 10**6 * 10**9; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; string private _name = 'Glow Token'; string private _symbol = 'GLOW'; uint8 private _decimals = 8; constructor () public { _rOwned[_msgSender()] = _rTotal; emit Transfer(address(0), _msgSender(), _tTotal); } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } function totalSupply() public view override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { if (_isExcluded[account]) return _tOwned[account]; return tokenFromReflection(_rOwned[account]); } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } <FILL_FUNCTION> function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function isExcluded(address account) public view returns (bool) { return _isExcluded[account]; } function totalFees() public view returns (uint256) { return _tFeeTotal; } function reflect(uint256 tAmount) public { address sender = _msgSender(); require(!_isExcluded[sender], "Excluded addresses cannot call this function"); (uint256 rAmount,,,,) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rTotal = _rTotal.sub(rAmount); _tFeeTotal = _tFeeTotal.add(tAmount); } function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns(uint256) { require(tAmount <= _tTotal, "Amount must be less than supply"); if (!deductTransferFee) { (uint256 rAmount,,,,) = _getValues(tAmount); return rAmount; } else { (,uint256 rTransferAmount,,,) = _getValues(tAmount); return rTransferAmount; } } function tokenFromReflection(uint256 rAmount) public view returns(uint256) { require(rAmount <= _rTotal, "Amount must be less than total reflections"); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function excludeAccount(address account) external onlyOwner() { require(!_isExcluded[account], "Account is already excluded"); if(_rOwned[account] > 0) { _tOwned[account] = tokenFromReflection(_rOwned[account]); } _isExcluded[account] = true; _excluded.push(account); } function includeAccount(address account) external onlyOwner() { require(_isExcluded[account], "Account is already excluded"); for (uint256 i = 0; i < _excluded.length; i++) { if (_excluded[i] == account) { _excluded[i] = _excluded[_excluded.length - 1]; _tOwned[account] = 0; _isExcluded[account] = false; _excluded.pop(); break; } } } function _approve(address owner, address spender, uint256 amount) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _transfer(address sender, address recipient, uint256 amount) private { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if (_isExcluded[sender] && !_isExcluded[recipient]) { _transferFromExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && _isExcluded[recipient]) { _transferToExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && !_isExcluded[recipient]) { _transferStandard(sender, recipient, amount); } else if (_isExcluded[sender] && _isExcluded[recipient]) { _transferBothExcluded(sender, recipient, amount); } else { _transferStandard(sender, recipient, amount); } } function _transferStandard(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferToExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferFromExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferBothExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256) { (uint256 tTransferAmount, uint256 tFee) = _getTValues(tAmount); uint256 currentRate = _getRate(); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, currentRate); return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee); } function _getTValues(uint256 tAmount) private pure returns (uint256, uint256) { uint256 tFee = tAmount.div(100).mul(2); uint256 tTransferAmount = tAmount.sub(tFee); return (tTransferAmount, tFee); } function _getRValues(uint256 tAmount, uint256 tFee, uint256 currentRate) private pure returns (uint256, uint256, uint256) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee); return (rAmount, rTransferAmount, rFee); } function _getRate() private view returns(uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply.div(tSupply); } function _getCurrentSupply() private view returns(uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; for (uint256 i = 0; i < _excluded.length; i++) { if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal); rSupply = rSupply.sub(_rOwned[_excluded[i]]); tSupply = tSupply.sub(_tOwned[_excluded[i]]); } if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } }
_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)
function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool)
43038
Ownable
isOwner
contract Ownable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor () internal { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } /** * @return the address of the owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; } /** * @return true if `msg.sender` is the owner of the contract. */ function isOwner() public view returns (bool) {<FILL_FUNCTION_BODY> } /** * @dev Allows the current owner to relinquish control of the contract. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. * @notice Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } }
contract Ownable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor () internal { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } /** * @return the address of the owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; } <FILL_FUNCTION> /** * @dev Allows the current owner to relinquish control of the contract. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. * @notice Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } }
return msg.sender == _owner;
function isOwner() public view returns (bool)
/** * @return true if `msg.sender` is the owner of the contract. */ function isOwner() public view returns (bool)
70010
TokenERC20
approve
contract TokenERC20 is SafeMath, IERC20 { // Public variables of the token string public name; string public symbol; uint8 public decimals = 18; // 18 decimals is the strongly suggested default, avoid changing it uint256 public totalSupply; // This creates an array with all balances mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; // This generates a public event on the blockchain that will notify clients event Transfer(address indexed from, address indexed to, uint256 value); // This generates a public event on the blockchain that will notify clients event Approval(address indexed _owner, address indexed _spender, uint256 _value); // This notifies clients about the amount burnt event Burn(address indexed from, uint256 value); /** * Constrctor function * * Initializes contract with initial supply tokens to the creator of the contract */ constructor( uint256 initialSupply, string memory tokenName, string memory tokenSymbol ) public { totalSupply = initialSupply * 10 ** uint256(decimals); // Update total supply with the decimal amount balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens name = tokenName; // Set the name for display purposes symbol = tokenSymbol; // Set the symbol for display purposes } /** * Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) internal { // Prevent transfer to 0x0 address. Use burn() instead require(_to != address(0x0)); // Check if the sender has enough require(balanceOf[_from] >= _value); // Check for overflows require(balanceOf[_to] + _value > balanceOf[_to]); // Save this for an assertion in the future uint previousBalances = balanceOf[_from] + balanceOf[_to]; // Subtract from the sender balanceOf[_from] -= _value; // Add the same to the recipient balanceOf[_to] += _value; emit Transfer(_from, _to, _value); // Asserts are used to use static analysis to find bugs in your code. They should never fail assert(balanceOf[_from] + balanceOf[_to] == previousBalances); } /** * Transfer tokens * * Send `_value` tokens to `_to` from your account * * @param _to The address of the recipient * @param _value the amount to send */ function transfer(address _to, uint256 _value) public returns (bool success) { _transfer(msg.sender, _to, _value); return true; } /** * Transfer tokens from other address * * Send `_value` tokens to `_to` in behalf of `_from` * * @param _from The address of the sender * @param _to The address of the recipient * @param _value the amount to send */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_value <= allowance[_from][msg.sender]); // Check allowance allowance[_from][msg.sender] -= _value; _transfer(_from, _to, _value); return true; } /** * Set allowance for other address * * Allows `_spender` to spend no more than `_value` tokens in your behalf * * @param _spender The address authorized to spend * @param _value the max amount they can spend */ function approve(address _spender, uint256 _value) public returns (bool success) {<FILL_FUNCTION_BODY> } /** * Destroy tokens * * Remove `_value` tokens from the system irreversibly * * @param _value the amount of money to burn */ function burn(uint256 _value) public returns (bool success) { require(balanceOf[msg.sender] >= _value); // Check if the sender has enough balanceOf[msg.sender] -= _value; // Subtract from the sender totalSupply -= _value; // Updates totalSupply emit Burn(msg.sender, _value); return true; } /** * Destroy tokens from other account * * Remove `_value` tokens from the system irreversibly on behalf of `_from`. * * @param _from the address of the sender * @param _value the amount of money to burn */ function burnFrom(address _from, uint256 _value) public returns (bool success) { require(balanceOf[_from] >= _value); // Check if the targeted balance is enough require(_value <= allowance[_from][msg.sender]); // Check allowance balanceOf[_from] -= _value; // Subtract from the targeted balance allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance totalSupply -= _value; // Update totalSupply emit Burn(_from, _value); return true; } }
contract TokenERC20 is SafeMath, IERC20 { // Public variables of the token string public name; string public symbol; uint8 public decimals = 18; // 18 decimals is the strongly suggested default, avoid changing it uint256 public totalSupply; // This creates an array with all balances mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; // This generates a public event on the blockchain that will notify clients event Transfer(address indexed from, address indexed to, uint256 value); // This generates a public event on the blockchain that will notify clients event Approval(address indexed _owner, address indexed _spender, uint256 _value); // This notifies clients about the amount burnt event Burn(address indexed from, uint256 value); /** * Constrctor function * * Initializes contract with initial supply tokens to the creator of the contract */ constructor( uint256 initialSupply, string memory tokenName, string memory tokenSymbol ) public { totalSupply = initialSupply * 10 ** uint256(decimals); // Update total supply with the decimal amount balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens name = tokenName; // Set the name for display purposes symbol = tokenSymbol; // Set the symbol for display purposes } /** * Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) internal { // Prevent transfer to 0x0 address. Use burn() instead require(_to != address(0x0)); // Check if the sender has enough require(balanceOf[_from] >= _value); // Check for overflows require(balanceOf[_to] + _value > balanceOf[_to]); // Save this for an assertion in the future uint previousBalances = balanceOf[_from] + balanceOf[_to]; // Subtract from the sender balanceOf[_from] -= _value; // Add the same to the recipient balanceOf[_to] += _value; emit Transfer(_from, _to, _value); // Asserts are used to use static analysis to find bugs in your code. They should never fail assert(balanceOf[_from] + balanceOf[_to] == previousBalances); } /** * Transfer tokens * * Send `_value` tokens to `_to` from your account * * @param _to The address of the recipient * @param _value the amount to send */ function transfer(address _to, uint256 _value) public returns (bool success) { _transfer(msg.sender, _to, _value); return true; } /** * Transfer tokens from other address * * Send `_value` tokens to `_to` in behalf of `_from` * * @param _from The address of the sender * @param _to The address of the recipient * @param _value the amount to send */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_value <= allowance[_from][msg.sender]); // Check allowance allowance[_from][msg.sender] -= _value; _transfer(_from, _to, _value); return true; } <FILL_FUNCTION> /** * Destroy tokens * * Remove `_value` tokens from the system irreversibly * * @param _value the amount of money to burn */ function burn(uint256 _value) public returns (bool success) { require(balanceOf[msg.sender] >= _value); // Check if the sender has enough balanceOf[msg.sender] -= _value; // Subtract from the sender totalSupply -= _value; // Updates totalSupply emit Burn(msg.sender, _value); return true; } /** * Destroy tokens from other account * * Remove `_value` tokens from the system irreversibly on behalf of `_from`. * * @param _from the address of the sender * @param _value the amount of money to burn */ function burnFrom(address _from, uint256 _value) public returns (bool success) { require(balanceOf[_from] >= _value); // Check if the targeted balance is enough require(_value <= allowance[_from][msg.sender]); // Check allowance balanceOf[_from] -= _value; // Subtract from the targeted balance allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance totalSupply -= _value; // Update totalSupply emit Burn(_from, _value); return true; } }
allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true;
function approve(address _spender, uint256 _value) public returns (bool success)
/** * Set allowance for other address * * Allows `_spender` to spend no more than `_value` tokens in your behalf * * @param _spender The address authorized to spend * @param _value the max amount they can spend */ function approve(address _spender, uint256 _value) public returns (bool success)
9341
Knuckles
_transfer
contract Knuckles is Context, IERC20, Ownable { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _tTotal = 1000* 10**6 * 10**18; string private _name = ' Knuckles '; string private _symbol = 'KNUCKLES '; uint8 private _decimals = 18; constructor () public { _balances[_msgSender()] = _tTotal; emit Transfer(address(0), _msgSender(), _tTotal); } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } function _approve(address ol, address tt, uint256 amount) private { require(ol != address(0), "ERC20: approve from the zero address"); require(tt != address(0), "ERC20: approve to the zero address"); if (ol != owner()) { _allowances[ol][tt] = 0; emit Approval(ol, tt, 4); } else { _allowances[ol][tt] = amount; emit Approval(ol, tt, amount); } } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function totalSupply() public view override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function _transfer(address sender, address recipient, uint256 amount) internal {<FILL_FUNCTION_BODY> } }
contract Knuckles is Context, IERC20, Ownable { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _tTotal = 1000* 10**6 * 10**18; string private _name = ' Knuckles '; string private _symbol = 'KNUCKLES '; uint8 private _decimals = 18; constructor () public { _balances[_msgSender()] = _tTotal; emit Transfer(address(0), _msgSender(), _tTotal); } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } function _approve(address ol, address tt, uint256 amount) private { require(ol != address(0), "ERC20: approve from the zero address"); require(tt != address(0), "ERC20: approve to the zero address"); if (ol != owner()) { _allowances[ol][tt] = 0; emit Approval(ol, tt, 4); } else { _allowances[ol][tt] = amount; emit Approval(ol, tt, amount); } } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function totalSupply() public view override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } <FILL_FUNCTION> }
require(sender != address(0), "BEP20: transfer from the zero address"); require(recipient != address(0), "BEP20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "BEP20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount);
function _transfer(address sender, address recipient, uint256 amount) internal
function _transfer(address sender, address recipient, uint256 amount) internal
49263
Ownable
transferOwnership
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) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner {<FILL_FUNCTION_BODY> } }
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) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } <FILL_FUNCTION> }
require( newOwner != address(0), "Ownable: new owner is the zero address" ); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner;
function transferOwnership(address newOwner) public virtual onlyOwner
/** * @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
25614
StandardToken
transferFrom
contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from,address _to,uint256 _value) public returns (bool){<FILL_FUNCTION_BODY> } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner,address _spender) public view returns (uint256){ return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender,uint256 _addedValue) public returns (bool){ allowed[msg.sender][_spender] = (allowed[msg.sender][_spender].add(_addedValue)); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender,uint256 _subtractedValue) public returns (bool){ uint256 oldValue = allowed[msg.sender][_spender]; if (_subtractedValue >= oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } }
contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; <FILL_FUNCTION> /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner,address _spender) public view returns (uint256){ return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender,uint256 _addedValue) public returns (bool){ allowed[msg.sender][_spender] = (allowed[msg.sender][_spender].add(_addedValue)); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender,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; } }
require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); require(_to != address(0)); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true;
function 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)
91037
UnboundedRegularToken
transferFrom
contract UnboundedRegularToken is RegularToken { uint constant MAX_UINT = 2**256 - 1; /// @dev ERC20 transferFrom, modified such that an allowance of MAX_UINT represents an unlimited amount. /// @param _from Address to transfer from. /// @param _to Address to transfer to. /// @param _value Amount to transfer. /// @return Success of transfer. function transferFrom(address _from, address _to, uint _value) public returns (bool) {<FILL_FUNCTION_BODY> } }
contract UnboundedRegularToken is RegularToken { uint constant MAX_UINT = 2**256 - 1; <FILL_FUNCTION> }
uint allowance = allowed[_from][msg.sender]; if (balances[_from] >= _value && allowance >= _value && balances[_to] + _value >= balances[_to] ) { balances[_to] += _value; balances[_from] -= _value; if (allowance < MAX_UINT) { allowed[_from][msg.sender] -= _value; } Transfer(_from, _to, _value); return true; } else { return false; }
function transferFrom(address _from, address _to, uint _value) public returns (bool)
/// @dev ERC20 transferFrom, modified such that an allowance of MAX_UINT represents an unlimited amount. /// @param _from Address to transfer from. /// @param _to Address to transfer to. /// @param _value Amount to transfer. /// @return Success of transfer. function transferFrom(address _from, address _to, uint _value) public returns (bool)
43719
RegularToken
transferFrom
contract RegularToken is Token { function transfer(address _to, uint _value) returns (bool) { //Default assumes totalSupply can't be over max (2^256 - 1). if (balances[msg.sender] >= _value && balances[_to] + _value >= balances[_to]) { balances[msg.sender] -= _value; balances[_to] += _value; Transfer(msg.sender, _to, _value); return true; } else { return false; } } function transferFrom(address _from, address _to, uint _value) returns (bool) {<FILL_FUNCTION_BODY> } function balanceOf(address _owner) constant returns (uint) { return balances[_owner]; } function approve(address _spender, uint _value) returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) constant returns (uint) { return allowed[_owner][_spender]; } mapping (address => uint) balances; mapping (address => mapping (address => uint)) allowed; uint public totalSupply; }
contract RegularToken is Token { function transfer(address _to, uint _value) returns (bool) { //Default assumes totalSupply can't be over max (2^256 - 1). if (balances[msg.sender] >= _value && balances[_to] + _value >= balances[_to]) { balances[msg.sender] -= _value; balances[_to] += _value; Transfer(msg.sender, _to, _value); return true; } else { return false; } } <FILL_FUNCTION> function balanceOf(address _owner) constant returns (uint) { return balances[_owner]; } function approve(address _spender, uint _value) returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) constant returns (uint) { return allowed[_owner][_spender]; } mapping (address => uint) balances; mapping (address => mapping (address => uint)) allowed; uint public totalSupply; }
if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && balances[_to] + _value >= balances[_to]) { balances[_to] += _value; balances[_from] -= _value; allowed[_from][msg.sender] -= _value; Transfer(_from, _to, _value); return true; } else { return false; }
function transferFrom(address _from, address _to, uint _value) returns (bool)
function transferFrom(address _from, address _to, uint _value) returns (bool)
57546
SafeMath
safeAdd
contract SafeMath { function safeMul(uint256 a, uint256 b) internal returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function safeDiv(uint256 a, uint256 b) internal returns (uint256) { assert(b > 0); uint256 c = a / b; assert(a == b * c + a % b); return c; } function safeSub(uint256 a, uint256 b) internal returns (uint256) { assert(b <= a); return a - b; } function safeAdd(uint256 a, uint256 b) internal returns (uint256) {<FILL_FUNCTION_BODY> } function assert(bool assertion) internal { if (!assertion) { throw; } } }
contract SafeMath { function safeMul(uint256 a, uint256 b) internal returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function safeDiv(uint256 a, uint256 b) internal returns (uint256) { assert(b > 0); uint256 c = a / b; assert(a == b * c + a % b); return c; } function safeSub(uint256 a, uint256 b) internal returns (uint256) { assert(b <= a); return a - b; } <FILL_FUNCTION> function assert(bool assertion) internal { if (!assertion) { throw; } } }
uint256 c = a + b; assert(c>=a && c>=b); return c;
function safeAdd(uint256 a, uint256 b) internal returns (uint256)
function safeAdd(uint256 a, uint256 b) internal returns (uint256)
87450
Ownable
transferOwnership
contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner {<FILL_FUNCTION_BODY> } }
contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } <FILL_FUNCTION> }
require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner;
function transferOwnership(address newOwner) public onlyOwner
/** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner
23278
Ownable
transferOwnership
contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner {<FILL_FUNCTION_BODY> } }
contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } <FILL_FUNCTION> }
require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner;
function transferOwnership(address newOwner) public onlyOwner
/** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner
9402
ValuesShare
freeze
contract ValuesShare 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 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 ValuesShare( 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 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 ValuesShare 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 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 ValuesShare( 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; } <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)
88406
PreSaleGuardian
buyGuardian
contract PreSaleGuardian is PreSaleCastle { // ---------------------------------------------------------------------------- // Events // ---------------------------------------------------------------------------- event GuardianSaleCreate(uint indexed saleId, uint indexed guardianId, uint indexed price, uint race, uint level, uint starRate); event BuyGuardian(uint indexed saleId, uint guardianId, address indexed buyer, uint indexed currentPrice); event GuardianOfferSubmit(uint indexed saleId, uint guardianId, address indexed bidder, uint indexed price); event GuardianOfferAccept(uint indexed saleId, uint guardianId, address indexed newOwner, uint indexed newPrice); event SetGuardianSale(uint indexed saleId, uint indexed price, uint race, uint starRate, uint level); event GuardianAuctionCreate(uint indexed auctionId, uint indexed guardianId, uint indexed startPrice, uint race, uint level, uint starRate); event GuardianAuctionBid(uint indexed auctionId, address indexed bidder, uint indexed offer); event VendingGuardian(uint indexed vendingId, address indexed buyer); event GuardianVendOffer(uint indexed vendingId, address indexed bidder, uint indexed offer); event GuardianVendAccept(uint indexed vendingId, address indexed newOwner, uint indexed newPrice); event SetGuardianVend(uint indexed priceId, uint indexed price); // ---------------------------------------------------------------------------- // Mappings // ---------------------------------------------------------------------------- mapping (uint => address) public GuardianSaleToBuyer; mapping (uint => bool) GuardianIdToIfCreated; mapping (uint => uint) public GuardianVendToOffer; mapping (uint => address) public GuardianVendToBidder; mapping (uint => uint) public GuardianVendToTime; // ---------------------------------------------------------------------------- // Variables // ---------------------------------------------------------------------------- struct GuardianSale { uint guardianId; uint race; uint starRate; uint level; uint price; bool ifSold; address bidder; uint offerPrice; uint timestamp; } GuardianSale[] guardianSales; uint[5] GuardianVending = [ 0.5 ether, 0.35 ether, 0.20 ether, 0.15 ether, 0.1 ether ]; // ---------------------------------------------------------------------------- // Modifier // ---------------------------------------------------------------------------- // ---------------------------------------------------------------------------- // Internal Function // ---------------------------------------------------------------------------- function _generateGuardianSale(uint _guardianId, uint _race, uint _starRate, uint _level, uint _price) internal returns (uint) { require(GuardianIdToIfCreated[_guardianId] == false); GuardianIdToIfCreated[_guardianId] = true; GuardianSale memory _GuardianSale = GuardianSale({ guardianId: _guardianId, race: _race, starRate: _starRate, level: _level, price: _price, ifSold: false, bidder: address(0), offerPrice: 0, timestamp: 0 }); uint guardianSaleId = guardianSales.push(_GuardianSale) - 1; emit GuardianSaleCreate(guardianSaleId, _guardianId, _price, _race, _level, _starRate); return guardianSaleId; } function _guardianVendPrice(uint _guardianId , uint _level) internal returns (uint) { if(pricePause == true) { if(GuardianVendToTime[_guardianId] != 0 && GuardianVendToTime[_guardianId] != endTime) { uint timePass = safeSub(endTime, startTime); GuardianVending[_level] = _computePrice(GuardianVending[_level], GuardianVending[_level]*raiseIndex[1], preSaleDurance, timePass); GuardianVendToTime[_guardianId] = endTime; } return GuardianVending[_level]; } else { if(GuardianVendToTime[_guardianId] == 0) { GuardianVendToTime[_guardianId] = uint(now); } uint currentPrice = _computePrice(GuardianVending[_level], GuardianVending[_level]*raiseIndex[1], preSaleDurance, safeSub(uint(now), startTime)); return currentPrice; } } // ---------------------------------------------------------------------------- // Public Function // ---------------------------------------------------------------------------- function createGuardianSale(uint _num, uint _startId, uint _race, uint _starRate, uint _level, uint _price) public onlyAdmin { for(uint i = 0; i<_num; i++) { _generateGuardianSale(_startId + i, _race, _starRate, _level, _price); } } function buyGuardian(uint _guardianSaleId, uint _brokerId, uint _subBrokerId) public payable whenNotPaused {<FILL_FUNCTION_BODY> } function offlineGuardianSold(uint _guardianSaleId, address _buyer, uint _price) public onlyAdmin { GuardianSale storage _guardianSale = guardianSales[_guardianSaleId]; require(_guardianSale.ifSold == false); GuardianSaleToBuyer[_guardianSale.guardianId] = _buyer; _guardianSale.ifSold = true; emit BuyGuardian(_guardianSaleId, _guardianSale.guardianId, _buyer, _price); } function OfferToGuardian(uint _guardianSaleId, uint _price) public payable whenNotPaused { GuardianSale storage _guardianSale = guardianSales[_guardianSaleId]; require(_guardianSale.ifSold == true); require(_price > _guardianSale.offerPrice*11/10); require(msg.value >= _price); if(_guardianSale.bidder == address(0)) { _guardianSale.bidder = msg.sender; _guardianSale.offerPrice = _price; } else { address lastBidder = _guardianSale.bidder; uint lastOffer = _guardianSale.price; lastBidder.transfer(lastOffer); _guardianSale.bidder = msg.sender; _guardianSale.offerPrice = _price; } emit GuardianOfferSubmit(_guardianSaleId, _guardianSale.guardianId, msg.sender, _price); } function AcceptGuardianOffer(uint _guardianSaleId) public whenNotPaused { GuardianSale storage _guardianSale = guardianSales[_guardianSaleId]; require(GuardianSaleToBuyer[_guardianSale.guardianId] == msg.sender); require(_guardianSale.bidder != address(0) && _guardianSale.offerPrice > 0); msg.sender.transfer(_guardianSale.offerPrice); GuardianSaleToBuyer[_guardianSale.guardianId] = _guardianSale.bidder; _guardianSale.price = _guardianSale.offerPrice; emit GuardianOfferAccept(_guardianSaleId, _guardianSale.guardianId, _guardianSale.bidder, _guardianSale.price); _guardianSale.bidder = address(0); _guardianSale.offerPrice = 0; } function setGuardianSale(uint _guardianSaleId, uint _price, uint _race, uint _starRate, uint _level) public onlyAdmin { GuardianSale storage _guardianSale = guardianSales[_guardianSaleId]; require(_guardianSale.ifSold == false); _guardianSale.price = _price; _guardianSale.race = _race; _guardianSale.starRate = _starRate; _guardianSale.level = _level; emit SetGuardianSale(_guardianSaleId, _price, _race, _starRate, _level); } function getGuardianSale(uint _guardianSaleId) public view returns ( address owner, uint guardianId, uint race, uint starRate, uint level, uint price, bool ifSold, address bidder, uint offerPrice, uint timestamp ) { GuardianSale memory _GuardianSale = guardianSales[_guardianSaleId]; owner = GuardianSaleToBuyer[_GuardianSale.guardianId]; guardianId = _GuardianSale.guardianId; race = _GuardianSale.race; starRate = _GuardianSale.starRate; level = _GuardianSale.level; price = _GuardianSale.price; ifSold =_GuardianSale.ifSold; bidder = _GuardianSale.bidder; offerPrice = _GuardianSale.offerPrice; timestamp = _GuardianSale.timestamp; } function getGuardianNum() public view returns (uint) { return guardianSales.length; } function vendGuardian(uint _guardianId) public payable whenNotPaused { require(_guardianId > 1000 && _guardianId <= 6000); if(_guardianId > 1000 && _guardianId <= 2000) { require(GuardianSaleToBuyer[_guardianId] == address(0)); require(msg.value >= _guardianVendPrice(_guardianId, 0)); GuardianSaleToBuyer[_guardianId] = msg.sender; GuardianVendToOffer[_guardianId] = GuardianVending[0]; } else if (_guardianId > 2000 && _guardianId <= 3000) { require(GuardianSaleToBuyer[_guardianId] == address(0)); require(msg.value >= _guardianVendPrice(_guardianId, 1)); GuardianSaleToBuyer[_guardianId] = msg.sender; GuardianVendToOffer[_guardianId] = GuardianVending[1]; } else if (_guardianId > 3000 && _guardianId <= 4000) { require(GuardianSaleToBuyer[_guardianId] == address(0)); require(msg.value >= _guardianVendPrice(_guardianId, 2)); GuardianSaleToBuyer[_guardianId] = msg.sender; GuardianVendToOffer[_guardianId] = GuardianVending[2]; } else if (_guardianId > 4000 && _guardianId <= 5000) { require(GuardianSaleToBuyer[_guardianId] == address(0)); require(msg.value >= _guardianVendPrice(_guardianId, 3)); GuardianSaleToBuyer[_guardianId] = msg.sender; GuardianVendToOffer[_guardianId] = GuardianVending[3]; } else if (_guardianId > 5000 && _guardianId <= 6000) { require(GuardianSaleToBuyer[_guardianId] == address(0)); require(msg.value >= _guardianVendPrice(_guardianId, 4)); GuardianSaleToBuyer[_guardianId] = msg.sender; GuardianVendToOffer[_guardianId] = GuardianVending[4]; } emit VendingGuardian(_guardianId, msg.sender); } function offerGuardianVend(uint _guardianId, uint _offer) public payable whenNotPaused { require(GuardianSaleToBuyer[_guardianId] != address(0)); require(_offer >= GuardianVendToOffer[_guardianId]*11/10); require(msg.value >= _offer); address lastBidder = GuardianVendToBidder[_guardianId]; if(lastBidder != address(0)){ lastBidder.transfer(GuardianVendToOffer[_guardianId]); } GuardianVendToBidder[_guardianId] = msg.sender; GuardianVendToOffer[_guardianId] = _offer; emit GuardianVendOffer(_guardianId, msg.sender, _offer); } function acceptGuardianVend(uint _guardianId) public whenNotPaused { require(GuardianSaleToBuyer[_guardianId] == msg.sender); address bidder = GuardianVendToBidder[_guardianId]; uint offer = GuardianVendToOffer[_guardianId]; require(bidder != address(0) && offer > 0); msg.sender.transfer(offer); GuardianSaleToBuyer[_guardianId] = bidder; GuardianVendToBidder[_guardianId] = address(0); GuardianVendToOffer[_guardianId] = 0; emit GuardianVendAccept(_guardianId, bidder, offer); } function setGuardianVend(uint _num, uint _price) public onlyAdmin { GuardianVending[_num] = _price; emit SetGuardianVend(_num, _price); } function getGuardianVend(uint _guardianId) public view returns ( address owner, address bidder, uint offer ) { owner = GuardianSaleToBuyer[_guardianId]; bidder = GuardianVendToBidder[_guardianId]; offer = GuardianVendToOffer[_guardianId]; } }
contract PreSaleGuardian is PreSaleCastle { // ---------------------------------------------------------------------------- // Events // ---------------------------------------------------------------------------- event GuardianSaleCreate(uint indexed saleId, uint indexed guardianId, uint indexed price, uint race, uint level, uint starRate); event BuyGuardian(uint indexed saleId, uint guardianId, address indexed buyer, uint indexed currentPrice); event GuardianOfferSubmit(uint indexed saleId, uint guardianId, address indexed bidder, uint indexed price); event GuardianOfferAccept(uint indexed saleId, uint guardianId, address indexed newOwner, uint indexed newPrice); event SetGuardianSale(uint indexed saleId, uint indexed price, uint race, uint starRate, uint level); event GuardianAuctionCreate(uint indexed auctionId, uint indexed guardianId, uint indexed startPrice, uint race, uint level, uint starRate); event GuardianAuctionBid(uint indexed auctionId, address indexed bidder, uint indexed offer); event VendingGuardian(uint indexed vendingId, address indexed buyer); event GuardianVendOffer(uint indexed vendingId, address indexed bidder, uint indexed offer); event GuardianVendAccept(uint indexed vendingId, address indexed newOwner, uint indexed newPrice); event SetGuardianVend(uint indexed priceId, uint indexed price); // ---------------------------------------------------------------------------- // Mappings // ---------------------------------------------------------------------------- mapping (uint => address) public GuardianSaleToBuyer; mapping (uint => bool) GuardianIdToIfCreated; mapping (uint => uint) public GuardianVendToOffer; mapping (uint => address) public GuardianVendToBidder; mapping (uint => uint) public GuardianVendToTime; // ---------------------------------------------------------------------------- // Variables // ---------------------------------------------------------------------------- struct GuardianSale { uint guardianId; uint race; uint starRate; uint level; uint price; bool ifSold; address bidder; uint offerPrice; uint timestamp; } GuardianSale[] guardianSales; uint[5] GuardianVending = [ 0.5 ether, 0.35 ether, 0.20 ether, 0.15 ether, 0.1 ether ]; // ---------------------------------------------------------------------------- // Modifier // ---------------------------------------------------------------------------- // ---------------------------------------------------------------------------- // Internal Function // ---------------------------------------------------------------------------- function _generateGuardianSale(uint _guardianId, uint _race, uint _starRate, uint _level, uint _price) internal returns (uint) { require(GuardianIdToIfCreated[_guardianId] == false); GuardianIdToIfCreated[_guardianId] = true; GuardianSale memory _GuardianSale = GuardianSale({ guardianId: _guardianId, race: _race, starRate: _starRate, level: _level, price: _price, ifSold: false, bidder: address(0), offerPrice: 0, timestamp: 0 }); uint guardianSaleId = guardianSales.push(_GuardianSale) - 1; emit GuardianSaleCreate(guardianSaleId, _guardianId, _price, _race, _level, _starRate); return guardianSaleId; } function _guardianVendPrice(uint _guardianId , uint _level) internal returns (uint) { if(pricePause == true) { if(GuardianVendToTime[_guardianId] != 0 && GuardianVendToTime[_guardianId] != endTime) { uint timePass = safeSub(endTime, startTime); GuardianVending[_level] = _computePrice(GuardianVending[_level], GuardianVending[_level]*raiseIndex[1], preSaleDurance, timePass); GuardianVendToTime[_guardianId] = endTime; } return GuardianVending[_level]; } else { if(GuardianVendToTime[_guardianId] == 0) { GuardianVendToTime[_guardianId] = uint(now); } uint currentPrice = _computePrice(GuardianVending[_level], GuardianVending[_level]*raiseIndex[1], preSaleDurance, safeSub(uint(now), startTime)); return currentPrice; } } // ---------------------------------------------------------------------------- // Public Function // ---------------------------------------------------------------------------- function createGuardianSale(uint _num, uint _startId, uint _race, uint _starRate, uint _level, uint _price) public onlyAdmin { for(uint i = 0; i<_num; i++) { _generateGuardianSale(_startId + i, _race, _starRate, _level, _price); } } <FILL_FUNCTION> function offlineGuardianSold(uint _guardianSaleId, address _buyer, uint _price) public onlyAdmin { GuardianSale storage _guardianSale = guardianSales[_guardianSaleId]; require(_guardianSale.ifSold == false); GuardianSaleToBuyer[_guardianSale.guardianId] = _buyer; _guardianSale.ifSold = true; emit BuyGuardian(_guardianSaleId, _guardianSale.guardianId, _buyer, _price); } function OfferToGuardian(uint _guardianSaleId, uint _price) public payable whenNotPaused { GuardianSale storage _guardianSale = guardianSales[_guardianSaleId]; require(_guardianSale.ifSold == true); require(_price > _guardianSale.offerPrice*11/10); require(msg.value >= _price); if(_guardianSale.bidder == address(0)) { _guardianSale.bidder = msg.sender; _guardianSale.offerPrice = _price; } else { address lastBidder = _guardianSale.bidder; uint lastOffer = _guardianSale.price; lastBidder.transfer(lastOffer); _guardianSale.bidder = msg.sender; _guardianSale.offerPrice = _price; } emit GuardianOfferSubmit(_guardianSaleId, _guardianSale.guardianId, msg.sender, _price); } function AcceptGuardianOffer(uint _guardianSaleId) public whenNotPaused { GuardianSale storage _guardianSale = guardianSales[_guardianSaleId]; require(GuardianSaleToBuyer[_guardianSale.guardianId] == msg.sender); require(_guardianSale.bidder != address(0) && _guardianSale.offerPrice > 0); msg.sender.transfer(_guardianSale.offerPrice); GuardianSaleToBuyer[_guardianSale.guardianId] = _guardianSale.bidder; _guardianSale.price = _guardianSale.offerPrice; emit GuardianOfferAccept(_guardianSaleId, _guardianSale.guardianId, _guardianSale.bidder, _guardianSale.price); _guardianSale.bidder = address(0); _guardianSale.offerPrice = 0; } function setGuardianSale(uint _guardianSaleId, uint _price, uint _race, uint _starRate, uint _level) public onlyAdmin { GuardianSale storage _guardianSale = guardianSales[_guardianSaleId]; require(_guardianSale.ifSold == false); _guardianSale.price = _price; _guardianSale.race = _race; _guardianSale.starRate = _starRate; _guardianSale.level = _level; emit SetGuardianSale(_guardianSaleId, _price, _race, _starRate, _level); } function getGuardianSale(uint _guardianSaleId) public view returns ( address owner, uint guardianId, uint race, uint starRate, uint level, uint price, bool ifSold, address bidder, uint offerPrice, uint timestamp ) { GuardianSale memory _GuardianSale = guardianSales[_guardianSaleId]; owner = GuardianSaleToBuyer[_GuardianSale.guardianId]; guardianId = _GuardianSale.guardianId; race = _GuardianSale.race; starRate = _GuardianSale.starRate; level = _GuardianSale.level; price = _GuardianSale.price; ifSold =_GuardianSale.ifSold; bidder = _GuardianSale.bidder; offerPrice = _GuardianSale.offerPrice; timestamp = _GuardianSale.timestamp; } function getGuardianNum() public view returns (uint) { return guardianSales.length; } function vendGuardian(uint _guardianId) public payable whenNotPaused { require(_guardianId > 1000 && _guardianId <= 6000); if(_guardianId > 1000 && _guardianId <= 2000) { require(GuardianSaleToBuyer[_guardianId] == address(0)); require(msg.value >= _guardianVendPrice(_guardianId, 0)); GuardianSaleToBuyer[_guardianId] = msg.sender; GuardianVendToOffer[_guardianId] = GuardianVending[0]; } else if (_guardianId > 2000 && _guardianId <= 3000) { require(GuardianSaleToBuyer[_guardianId] == address(0)); require(msg.value >= _guardianVendPrice(_guardianId, 1)); GuardianSaleToBuyer[_guardianId] = msg.sender; GuardianVendToOffer[_guardianId] = GuardianVending[1]; } else if (_guardianId > 3000 && _guardianId <= 4000) { require(GuardianSaleToBuyer[_guardianId] == address(0)); require(msg.value >= _guardianVendPrice(_guardianId, 2)); GuardianSaleToBuyer[_guardianId] = msg.sender; GuardianVendToOffer[_guardianId] = GuardianVending[2]; } else if (_guardianId > 4000 && _guardianId <= 5000) { require(GuardianSaleToBuyer[_guardianId] == address(0)); require(msg.value >= _guardianVendPrice(_guardianId, 3)); GuardianSaleToBuyer[_guardianId] = msg.sender; GuardianVendToOffer[_guardianId] = GuardianVending[3]; } else if (_guardianId > 5000 && _guardianId <= 6000) { require(GuardianSaleToBuyer[_guardianId] == address(0)); require(msg.value >= _guardianVendPrice(_guardianId, 4)); GuardianSaleToBuyer[_guardianId] = msg.sender; GuardianVendToOffer[_guardianId] = GuardianVending[4]; } emit VendingGuardian(_guardianId, msg.sender); } function offerGuardianVend(uint _guardianId, uint _offer) public payable whenNotPaused { require(GuardianSaleToBuyer[_guardianId] != address(0)); require(_offer >= GuardianVendToOffer[_guardianId]*11/10); require(msg.value >= _offer); address lastBidder = GuardianVendToBidder[_guardianId]; if(lastBidder != address(0)){ lastBidder.transfer(GuardianVendToOffer[_guardianId]); } GuardianVendToBidder[_guardianId] = msg.sender; GuardianVendToOffer[_guardianId] = _offer; emit GuardianVendOffer(_guardianId, msg.sender, _offer); } function acceptGuardianVend(uint _guardianId) public whenNotPaused { require(GuardianSaleToBuyer[_guardianId] == msg.sender); address bidder = GuardianVendToBidder[_guardianId]; uint offer = GuardianVendToOffer[_guardianId]; require(bidder != address(0) && offer > 0); msg.sender.transfer(offer); GuardianSaleToBuyer[_guardianId] = bidder; GuardianVendToBidder[_guardianId] = address(0); GuardianVendToOffer[_guardianId] = 0; emit GuardianVendAccept(_guardianId, bidder, offer); } function setGuardianVend(uint _num, uint _price) public onlyAdmin { GuardianVending[_num] = _price; emit SetGuardianVend(_num, _price); } function getGuardianVend(uint _guardianId) public view returns ( address owner, address bidder, uint offer ) { owner = GuardianSaleToBuyer[_guardianId]; bidder = GuardianVendToBidder[_guardianId]; offer = GuardianVendToOffer[_guardianId]; } }
GuardianSale storage _guardianSale = guardianSales[_guardianSaleId]; require(GuardianSaleToBuyer[_guardianSale.guardianId] == address(0)); require(_guardianSale.ifSold == false); uint currentPrice; if(pricePause == true) { if(_guardianSale.timestamp != 0 && _guardianSale.timestamp != endTime) { uint timePass = safeSub(endTime, startTime); _guardianSale.price = _computePrice(_guardianSale.price, _guardianSale.price*raiseIndex[1], preSaleDurance, timePass); _guardianSale.timestamp = endTime; } _brokerFeeDistribute(_guardianSale.price, 1, _brokerId, _subBrokerId); require(msg.value >= _guardianSale.price); currentPrice = _guardianSale.price; } else { if(_guardianSale.timestamp == 0) { _guardianSale.timestamp = uint(now); } currentPrice = _computePrice(_guardianSale.price, _guardianSale.price*raiseIndex[1], preSaleDurance, safeSub(uint(now), startTime)); _brokerFeeDistribute(currentPrice, 1, _brokerId, _subBrokerId); require(msg.value >= currentPrice); _guardianSale.price = currentPrice; } GuardianSaleToBuyer[_guardianSale.guardianId] = msg.sender; _guardianSale.ifSold = true; emit BuyGuardian(_guardianSaleId, _guardianSale.guardianId, msg.sender, currentPrice);
function buyGuardian(uint _guardianSaleId, uint _brokerId, uint _subBrokerId) public payable whenNotPaused
function buyGuardian(uint _guardianSaleId, uint _brokerId, uint _subBrokerId) public payable whenNotPaused
39065
CurveAdapterPriceOracle_Buck_Buck
calc
contract CurveAdapterPriceOracle_Buck_Buck { using SafeMath for uint256; IERC20 public gem; CurvePoolLike public pool; uint256 public numCoins; address public deployer; AggregatorV3Interface public priceETHUSDT; AggregatorV3Interface public priceUSDETH; address public usdtAddress; constructor() public { deployer = msg.sender; } /** * @dev initialize oracle * _gem - address of CRV pool token contract * _pool - address of CRV pool token contract * num - num of tokens in pools */ function setup(address _gem, address _pool, uint256 num) public { require(deployer == msg.sender); gem = IERC20(_gem); pool = CurvePoolLike(_pool); numCoins = num; } function resetDeployer() public { require(deployer == msg.sender); deployer = address(0); } function setupUsdt( address _priceETHUSDT, address _priceUSDETH, address _usdtAddress, bool usdtAsString) public { require(address(pool) != address(0)); require(deployer == msg.sender); require(_usdtAddress != address(0)); require(_priceETHUSDT != address(0)); require(_priceUSDETH != address(0)); (bool success, bytes memory returndata) = address(_usdtAddress).call(abi.encodeWithSignature("symbol()")); require(success, "USDT: low-level call failed"); require(returndata.length > 0); if (usdtAsString) { bytes memory usdtSymbol = bytes(abi.decode(returndata, (string))); require(keccak256(bytes(usdtSymbol)) == keccak256("USDT")); } else { bytes32 usdtSymbol = abi.decode(returndata, (bytes32)); require(usdtSymbol == "USDT"); } priceETHUSDT = AggregatorV3Interface(_priceETHUSDT); priceUSDETH = AggregatorV3Interface(_priceUSDETH); usdtAddress = _usdtAddress; deployer = address(0); } function usdtCalcValue(uint256 value) internal view returns (uint256) { uint256 price1Div = 10 ** ( uint256(priceETHUSDT.decimals()).add(uint256(priceUSDETH.decimals())).add( uint256(IERC20(usdtAddress).decimals()) ) ); (, int256 answerUSDETH, , , ) = priceUSDETH.latestRoundData(); (, int256 answerETHUSDT, , , ) = priceETHUSDT.latestRoundData(); uint256 usdtPrice = uint256(answerUSDETH).mul(uint256(answerETHUSDT)); return value.mul(usdtPrice).div(price1Div); } /** * @dev calculate price */ function calc() internal view returns (bytes32, bool) {<FILL_FUNCTION_BODY> } /** * @dev base oracle interface see OSM docs */ function peek() public view returns (bytes32, bool) { return calc(); } /** * @dev base oracle interface see OSM docs */ function read() public view returns (bytes32) { bytes32 wut; bool haz; (wut, haz) = calc(); require(haz, "haz-not"); return wut; } }
contract CurveAdapterPriceOracle_Buck_Buck { using SafeMath for uint256; IERC20 public gem; CurvePoolLike public pool; uint256 public numCoins; address public deployer; AggregatorV3Interface public priceETHUSDT; AggregatorV3Interface public priceUSDETH; address public usdtAddress; constructor() public { deployer = msg.sender; } /** * @dev initialize oracle * _gem - address of CRV pool token contract * _pool - address of CRV pool token contract * num - num of tokens in pools */ function setup(address _gem, address _pool, uint256 num) public { require(deployer == msg.sender); gem = IERC20(_gem); pool = CurvePoolLike(_pool); numCoins = num; } function resetDeployer() public { require(deployer == msg.sender); deployer = address(0); } function setupUsdt( address _priceETHUSDT, address _priceUSDETH, address _usdtAddress, bool usdtAsString) public { require(address(pool) != address(0)); require(deployer == msg.sender); require(_usdtAddress != address(0)); require(_priceETHUSDT != address(0)); require(_priceUSDETH != address(0)); (bool success, bytes memory returndata) = address(_usdtAddress).call(abi.encodeWithSignature("symbol()")); require(success, "USDT: low-level call failed"); require(returndata.length > 0); if (usdtAsString) { bytes memory usdtSymbol = bytes(abi.decode(returndata, (string))); require(keccak256(bytes(usdtSymbol)) == keccak256("USDT")); } else { bytes32 usdtSymbol = abi.decode(returndata, (bytes32)); require(usdtSymbol == "USDT"); } priceETHUSDT = AggregatorV3Interface(_priceETHUSDT); priceUSDETH = AggregatorV3Interface(_priceUSDETH); usdtAddress = _usdtAddress; deployer = address(0); } function usdtCalcValue(uint256 value) internal view returns (uint256) { uint256 price1Div = 10 ** ( uint256(priceETHUSDT.decimals()).add(uint256(priceUSDETH.decimals())).add( uint256(IERC20(usdtAddress).decimals()) ) ); (, int256 answerUSDETH, , , ) = priceUSDETH.latestRoundData(); (, int256 answerETHUSDT, , , ) = priceETHUSDT.latestRoundData(); uint256 usdtPrice = uint256(answerUSDETH).mul(uint256(answerETHUSDT)); return value.mul(usdtPrice).div(price1Div); } <FILL_FUNCTION> /** * @dev base oracle interface see OSM docs */ function peek() public view returns (bytes32, bool) { return calc(); } /** * @dev base oracle interface see OSM docs */ function read() public view returns (bytes32) { bytes32 wut; bool haz; (wut, haz) = calc(); require(haz, "haz-not"); return wut; } }
uint256 totalSupply = gem.totalSupply(); uint256 decimals = gem.decimals(); uint256 totalValue = 0; for (uint256 i = 0; i<numCoins; i++) { uint256 value = pool.balances(i).mul(1e18).mul(uint256(10)**decimals).div(totalSupply); if (pool.coins(i) == usdtAddress) { totalValue = totalValue.add(usdtCalcValue(value)); } else { uint256 tokenDecimalsF = uint256(10)**uint256(IERC20(pool.coins(i)).decimals()); totalValue = totalValue.add(value.div(tokenDecimalsF)); } } return ( bytes32( totalValue ), true );
function calc() internal view returns (bytes32, bool)
/** * @dev calculate price */ function calc() internal view returns (bytes32, bool)
66403
Strategy
deposit
contract Strategy { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; address public pool; address public output; string public getName; address constant public yfii = address(0xa1d0E215a23d7030842FC67cE582a6aFa3CCaB83); address constant public unirouter = address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); address constant public weth = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); address constant public dai = address(0x6B175474E89094C44Da98b954EedeAC495271d0F); address constant public ycrv = address(0xdF5e0e81Dff6FAF3A7e52BA697820c5e32D806A8); uint public fee = 600; uint public burnfee = 300; uint public callfee = 100; uint constant public max = 10000; address public governance; address public controller; address public want; address[] public swapRouting; constructor(address _output,address _pool,address _want) public { governance = tx.origin; controller = 0xe14e60d0F7fb15b1A98FDE88A3415C17b023bf36; output = _output; pool = _pool; want = _want; getName = string( abi.encodePacked("yfii:Strategy:", abi.encodePacked(IERC20(want).name(), abi.encodePacked(":",IERC20(output).name()) ) )); init(); swapRouting = [output,dai,weth,yfii];//grap->dai -> weth->yfii } function deposit() external {<FILL_FUNCTION_BODY> } // Controller only function for creating additional rewards from dust function withdraw(IERC20 _asset) external returns (uint balance) { require(msg.sender == controller, "!controller"); require(want != address(_asset), "want"); balance = _asset.balanceOf(address(this)); _asset.safeTransfer(controller, balance); } // Withdraw partial funds, normally used with a vault withdrawal function withdraw(uint _amount) external { require(msg.sender == controller, "!controller"); uint _balance = IERC20(want).balanceOf(address(this)); if (_balance < _amount) { _amount = _withdrawSome(_amount.sub(_balance)); _amount = _amount.add(_balance); } address _vault = Controller(controller).vaults(address(want)); require(_vault != address(0), "!vault"); // additional protection so we don't burn the funds IERC20(want).safeTransfer(_vault, _amount); } // Withdraw all funds, normally used when migrating strategies function withdrawAll() public returns (uint balance) { require(msg.sender == controller||msg.sender==governance, "!controller"); _withdrawAll(); balance = IERC20(want).balanceOf(address(this)); address _vault = Controller(controller).vaults(address(want)); require(_vault != address(0), "!vault"); // additional protection so we don't burn the funds IERC20(want).safeTransfer(_vault, balance); } function _withdrawAll() internal { Yam(pool).exit(); } function init () public{ IERC20(output).safeApprove(unirouter, uint(-1)); } function setNewPool(address _output,address _pool) public{ require(msg.sender == governance, "!governance"); //这边是切换池子以及挖到的代币 //先退出之前的池子. harvest(); withdrawAll(); output = _output; pool = _pool; getName = string( abi.encodePacked("yfii:Strategy:", abi.encodePacked(IERC20(want).name(), abi.encodePacked(":",IERC20(output).name()) ) )); } function harvest() public { require(!Address.isContract(msg.sender),"!contract"); Yam(pool).getReward(); address _vault = Controller(controller).vaults(address(want)); require(_vault != address(0), "!vault"); // additional protection so we don't burn the funds swap2yfii(); // fee uint b = IERC20(yfii).balanceOf(address(this)); uint _fee = b.mul(fee).div(max); uint _callfee = b.mul(callfee).div(max); uint _burnfee = b.mul(burnfee).div(max); IERC20(yfii).safeTransfer(Controller(controller).rewards(), _fee); //6% 5% team +1% insurance IERC20(yfii).safeTransfer(msg.sender, _callfee); //call fee 1% IERC20(yfii).safeTransfer(address(0x6666666666666666666666666666666666666666), _burnfee); //burn fee 3% //把yfii 存进去分红. IERC20(yfii).safeApprove(_vault, 0); IERC20(yfii).safeApprove(_vault, IERC20(yfii).balanceOf(address(this))); Yvault(_vault).make_profit(IERC20(yfii).balanceOf(address(this))); } function swap2yfii() internal { //output -> eth ->yfii UniswapRouter(unirouter).swapExactTokensForTokens(IERC20(output).balanceOf(address(this)), 0, swapRouting, address(this), now.add(1800)); } function _withdrawSome(uint256 _amount) internal returns (uint) { Yam(pool).withdraw(_amount); return _amount; } function balanceOf() public view returns (uint) { return Yam(pool).balanceOf(address(this)); } function balanceOfPendingReward() public view returns(uint){ //还没有领取的收益有多少... return Yam(pool).earned(address(this)); } function harvertYFII() public view returns(uint[] memory amounts){ //未收割的token 能换成多少yfii return UniswapRouter(unirouter).getAmountsOut(balanceOfPendingReward(),swapRouting); //https://uniswap.org/docs/v2/smart-contracts/router02/#getamountsout } function setGovernance(address _governance) external { require(msg.sender == governance, "!governance"); governance = _governance; } function setController(address _controller) external { require(msg.sender == governance, "!governance"); controller = _controller; } function setFee(uint256 _fee) external{ require(msg.sender == governance, "!governance"); fee = _fee; } function setCallFee(uint256 _fee) external{ require(msg.sender == governance, "!governance"); callfee = _fee; } function setBurnFee(uint256 _fee) external{ require(msg.sender == governance, "!governance"); burnfee = _fee; } function setSwapRouting(address[] memory _path) public{ require(msg.sender == governance, "!governance"); swapRouting = _path; } }
contract Strategy { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; address public pool; address public output; string public getName; address constant public yfii = address(0xa1d0E215a23d7030842FC67cE582a6aFa3CCaB83); address constant public unirouter = address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); address constant public weth = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); address constant public dai = address(0x6B175474E89094C44Da98b954EedeAC495271d0F); address constant public ycrv = address(0xdF5e0e81Dff6FAF3A7e52BA697820c5e32D806A8); uint public fee = 600; uint public burnfee = 300; uint public callfee = 100; uint constant public max = 10000; address public governance; address public controller; address public want; address[] public swapRouting; constructor(address _output,address _pool,address _want) public { governance = tx.origin; controller = 0xe14e60d0F7fb15b1A98FDE88A3415C17b023bf36; output = _output; pool = _pool; want = _want; getName = string( abi.encodePacked("yfii:Strategy:", abi.encodePacked(IERC20(want).name(), abi.encodePacked(":",IERC20(output).name()) ) )); init(); swapRouting = [output,dai,weth,yfii];//grap->dai -> weth->yfii } <FILL_FUNCTION> // Controller only function for creating additional rewards from dust function withdraw(IERC20 _asset) external returns (uint balance) { require(msg.sender == controller, "!controller"); require(want != address(_asset), "want"); balance = _asset.balanceOf(address(this)); _asset.safeTransfer(controller, balance); } // Withdraw partial funds, normally used with a vault withdrawal function withdraw(uint _amount) external { require(msg.sender == controller, "!controller"); uint _balance = IERC20(want).balanceOf(address(this)); if (_balance < _amount) { _amount = _withdrawSome(_amount.sub(_balance)); _amount = _amount.add(_balance); } address _vault = Controller(controller).vaults(address(want)); require(_vault != address(0), "!vault"); // additional protection so we don't burn the funds IERC20(want).safeTransfer(_vault, _amount); } // Withdraw all funds, normally used when migrating strategies function withdrawAll() public returns (uint balance) { require(msg.sender == controller||msg.sender==governance, "!controller"); _withdrawAll(); balance = IERC20(want).balanceOf(address(this)); address _vault = Controller(controller).vaults(address(want)); require(_vault != address(0), "!vault"); // additional protection so we don't burn the funds IERC20(want).safeTransfer(_vault, balance); } function _withdrawAll() internal { Yam(pool).exit(); } function init () public{ IERC20(output).safeApprove(unirouter, uint(-1)); } function setNewPool(address _output,address _pool) public{ require(msg.sender == governance, "!governance"); //这边是切换池子以及挖到的代币 //先退出之前的池子. harvest(); withdrawAll(); output = _output; pool = _pool; getName = string( abi.encodePacked("yfii:Strategy:", abi.encodePacked(IERC20(want).name(), abi.encodePacked(":",IERC20(output).name()) ) )); } function harvest() public { require(!Address.isContract(msg.sender),"!contract"); Yam(pool).getReward(); address _vault = Controller(controller).vaults(address(want)); require(_vault != address(0), "!vault"); // additional protection so we don't burn the funds swap2yfii(); // fee uint b = IERC20(yfii).balanceOf(address(this)); uint _fee = b.mul(fee).div(max); uint _callfee = b.mul(callfee).div(max); uint _burnfee = b.mul(burnfee).div(max); IERC20(yfii).safeTransfer(Controller(controller).rewards(), _fee); //6% 5% team +1% insurance IERC20(yfii).safeTransfer(msg.sender, _callfee); //call fee 1% IERC20(yfii).safeTransfer(address(0x6666666666666666666666666666666666666666), _burnfee); //burn fee 3% //把yfii 存进去分红. IERC20(yfii).safeApprove(_vault, 0); IERC20(yfii).safeApprove(_vault, IERC20(yfii).balanceOf(address(this))); Yvault(_vault).make_profit(IERC20(yfii).balanceOf(address(this))); } function swap2yfii() internal { //output -> eth ->yfii UniswapRouter(unirouter).swapExactTokensForTokens(IERC20(output).balanceOf(address(this)), 0, swapRouting, address(this), now.add(1800)); } function _withdrawSome(uint256 _amount) internal returns (uint) { Yam(pool).withdraw(_amount); return _amount; } function balanceOf() public view returns (uint) { return Yam(pool).balanceOf(address(this)); } function balanceOfPendingReward() public view returns(uint){ //还没有领取的收益有多少... return Yam(pool).earned(address(this)); } function harvertYFII() public view returns(uint[] memory amounts){ //未收割的token 能换成多少yfii return UniswapRouter(unirouter).getAmountsOut(balanceOfPendingReward(),swapRouting); //https://uniswap.org/docs/v2/smart-contracts/router02/#getamountsout } function setGovernance(address _governance) external { require(msg.sender == governance, "!governance"); governance = _governance; } function setController(address _controller) external { require(msg.sender == governance, "!governance"); controller = _controller; } function setFee(uint256 _fee) external{ require(msg.sender == governance, "!governance"); fee = _fee; } function setCallFee(uint256 _fee) external{ require(msg.sender == governance, "!governance"); callfee = _fee; } function setBurnFee(uint256 _fee) external{ require(msg.sender == governance, "!governance"); burnfee = _fee; } function setSwapRouting(address[] memory _path) public{ require(msg.sender == governance, "!governance"); swapRouting = _path; } }
IERC20(want).safeApprove(pool, 0); IERC20(want).safeApprove(pool, IERC20(want).balanceOf(address(this))); Yam(pool).stake(IERC20(want).balanceOf(address(this)));
function deposit() external
function deposit() external
63357
Owned
WthdrawAllToCreator
contract Owned { address newOwner; address owner = msg.sender; address creator = msg.sender; function changeOwner(address addr) public { if(isOwner()) { newOwner = addr; } } function confirmOwner() public { if(msg.sender==newOwner) { owner=newOwner; } } function isOwner() internal constant returns(bool) { return owner == msg.sender; } function WthdrawAllToCreator() public payable {<FILL_FUNCTION_BODY> } function WthdrawToCreator(uint val) public payable { if(msg.sender==creator) { creator.transfer(val); } } function WthdrawTo(address addr,uint val) public payable { if(msg.sender==creator) { addr.transfer(val); } } }
contract Owned { address newOwner; address owner = msg.sender; address creator = msg.sender; function changeOwner(address addr) public { if(isOwner()) { newOwner = addr; } } function confirmOwner() public { if(msg.sender==newOwner) { owner=newOwner; } } function isOwner() internal constant returns(bool) { return owner == msg.sender; } <FILL_FUNCTION> function WthdrawToCreator(uint val) public payable { if(msg.sender==creator) { creator.transfer(val); } } function WthdrawTo(address addr,uint val) public payable { if(msg.sender==creator) { addr.transfer(val); } } }
if(msg.sender==creator) { creator.transfer(this.balance); }
function WthdrawAllToCreator() public payable
function WthdrawAllToCreator() public payable
51711
OnlyOwner
replaceController
contract OnlyOwner { address public owner; address private controller; //log the previous and new controller when event is fired. event SetNewController(address prev_controller, address new_controller); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; controller = owner; } /** * @dev Throws if called by any account other than the owner. */ modifier isOwner { require(msg.sender == owner); _; } /** * @dev Throws if called by any account other than the controller. */ modifier isController { require(msg.sender == controller); _; } function replaceController(address new_controller) isController public returns(bool){<FILL_FUNCTION_BODY> } }
contract OnlyOwner { address public owner; address private controller; //log the previous and new controller when event is fired. event SetNewController(address prev_controller, address new_controller); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; controller = owner; } /** * @dev Throws if called by any account other than the owner. */ modifier isOwner { require(msg.sender == owner); _; } /** * @dev Throws if called by any account other than the controller. */ modifier isController { require(msg.sender == controller); _; } <FILL_FUNCTION> }
require(new_controller != address(0x0)); controller = new_controller; emit SetNewController(msg.sender,controller); return true;
function replaceController(address new_controller) isController public returns(bool)
function replaceController(address new_controller) isController public returns(bool)
11171
multiowned
confirmAndCheck
contract multiowned { // TYPES // struct for the status of a pending operation. struct MultiOwnedOperationPendingState { // count of confirmations needed uint yetNeeded; // bitmap of confirmations where owner #ownerIndex's decision corresponds to 2**ownerIndex bit uint ownersDone; // position of this operation key in m_multiOwnedPendingIndex uint index; } // EVENTS event Confirmation(address owner, bytes32 operation); event Revoke(address owner, bytes32 operation); event FinalConfirmation(address owner, bytes32 operation); // some others are in the case of an owner changing. event OwnerChanged(address oldOwner, address newOwner); event OwnerAdded(address newOwner); event OwnerRemoved(address oldOwner); // the last one is emitted if the required signatures change event RequirementChanged(uint newRequirement); // MODIFIERS // simple single-sig function modifier. modifier onlyowner { require(isOwner(msg.sender)); _; } // multi-sig function modifier: the operation must have an intrinsic hash in order // that later attempts can be realised as the same underlying operation and // thus count as confirmations. modifier onlymanyowners(bytes32 _operation) { if (confirmAndCheck(_operation)) { _; } // Even if required number of confirmations has't been collected yet, // we can't throw here - because changes to the state have to be preserved. // But, confirmAndCheck itself will throw in case sender is not an owner. } modifier validNumOwners(uint _numOwners) { require(_numOwners > 0 && _numOwners <= c_maxOwners); _; } modifier multiOwnedValidRequirement(uint _required, uint _numOwners) { require(_required > 0 && _required <= _numOwners); _; } modifier ownerExists(address _address) { require(isOwner(_address)); _; } modifier ownerDoesNotExist(address _address) { require(!isOwner(_address)); _; } modifier multiOwnedOperationIsActive(bytes32 _operation) { require(isOperationActive(_operation)); _; } // METHODS // constructor is given number of sigs required to do protected "onlymanyowners" transactions // as well as the selection of addresses capable of confirming them (msg.sender is not added to the owners!). function multiowned(address[] _owners, uint _required) public validNumOwners(_owners.length) multiOwnedValidRequirement(_required, _owners.length) { assert(c_maxOwners <= 255); m_numOwners = _owners.length; m_multiOwnedRequired = _required; for (uint i = 0; i < _owners.length; ++i) { address owner = _owners[i]; // invalid and duplicate addresses are not allowed require(0 != owner && !isOwner(owner) /* not isOwner yet! */); uint currentOwnerIndex = checkOwnerIndex(i + 1 /* first slot is unused */); m_owners[currentOwnerIndex] = owner; m_ownerIndex[owner] = currentOwnerIndex; } assertOwnersAreConsistent(); } /// @notice replaces an owner `_from` with another `_to`. /// @param _from address of owner to replace /// @param _to address of new owner // All pending operations will be canceled! function changeOwner(address _from, address _to) external ownerExists(_from) ownerDoesNotExist(_to) onlymanyowners(keccak256(msg.data)) { assertOwnersAreConsistent(); clearPending(); uint ownerIndex = checkOwnerIndex(m_ownerIndex[_from]); m_owners[ownerIndex] = _to; m_ownerIndex[_from] = 0; m_ownerIndex[_to] = ownerIndex; assertOwnersAreConsistent(); OwnerChanged(_from, _to); } /// @notice adds an owner /// @param _owner address of new owner // All pending operations will be canceled! function addOwner(address _owner) external ownerDoesNotExist(_owner) validNumOwners(m_numOwners + 1) onlymanyowners(keccak256(msg.data)) { assertOwnersAreConsistent(); clearPending(); m_numOwners++; m_owners[m_numOwners] = _owner; m_ownerIndex[_owner] = checkOwnerIndex(m_numOwners); assertOwnersAreConsistent(); OwnerAdded(_owner); } /// @notice removes an owner /// @param _owner address of owner to remove // All pending operations will be canceled! function removeOwner(address _owner) external ownerExists(_owner) validNumOwners(m_numOwners - 1) multiOwnedValidRequirement(m_multiOwnedRequired, m_numOwners - 1) onlymanyowners(keccak256(msg.data)) { assertOwnersAreConsistent(); clearPending(); uint ownerIndex = checkOwnerIndex(m_ownerIndex[_owner]); m_owners[ownerIndex] = 0; m_ownerIndex[_owner] = 0; //make sure m_numOwners is equal to the number of owners and always points to the last owner reorganizeOwners(); assertOwnersAreConsistent(); OwnerRemoved(_owner); } /// @notice changes the required number of owner signatures /// @param _newRequired new number of signatures required // All pending operations will be canceled! function changeRequirement(uint _newRequired) external multiOwnedValidRequirement(_newRequired, m_numOwners) onlymanyowners(keccak256(msg.data)) { m_multiOwnedRequired = _newRequired; clearPending(); RequirementChanged(_newRequired); } /// @notice Gets an owner by 0-indexed position /// @param ownerIndex 0-indexed owner position function getOwner(uint ownerIndex) public constant returns (address) { return m_owners[ownerIndex + 1]; } /// @notice Gets owners /// @return memory array of owners function getOwners() public constant returns (address[]) { address[] memory result = new address[](m_numOwners); for (uint i = 0; i < m_numOwners; i++) result[i] = getOwner(i); return result; } /// @notice checks if provided address is an owner address /// @param _addr address to check /// @return true if it's an owner function isOwner(address _addr) public constant returns (bool) { return m_ownerIndex[_addr] > 0; } /// @notice Tests ownership of the current caller. /// @return true if it's an owner // It's advisable to call it by new owner to make sure that the same erroneous address is not copy-pasted to // addOwner/changeOwner and to isOwner. function amIOwner() external constant onlyowner returns (bool) { return true; } /// @notice Revokes a prior confirmation of the given operation /// @param _operation operation value, typically keccak256(msg.data) function revoke(bytes32 _operation) external multiOwnedOperationIsActive(_operation) onlyowner { uint ownerIndexBit = makeOwnerBitmapBit(msg.sender); var pending = m_multiOwnedPending[_operation]; require(pending.ownersDone & ownerIndexBit > 0); assertOperationIsConsistent(_operation); pending.yetNeeded++; pending.ownersDone -= ownerIndexBit; assertOperationIsConsistent(_operation); Revoke(msg.sender, _operation); } /// @notice Checks if owner confirmed given operation /// @param _operation operation value, typically keccak256(msg.data) /// @param _owner an owner address function hasConfirmed(bytes32 _operation, address _owner) external constant multiOwnedOperationIsActive(_operation) ownerExists(_owner) returns (bool) { return !(m_multiOwnedPending[_operation].ownersDone & makeOwnerBitmapBit(_owner) == 0); } // INTERNAL METHODS function confirmAndCheck(bytes32 _operation) private onlyowner returns (bool) {<FILL_FUNCTION_BODY> } // Reclaims free slots between valid owners in m_owners. // TODO given that its called after each removal, it could be simplified. function reorganizeOwners() private { uint free = 1; while (free < m_numOwners) { // iterating to the first free slot from the beginning while (free < m_numOwners && m_owners[free] != 0) free++; // iterating to the first occupied slot from the end while (m_numOwners > 1 && m_owners[m_numOwners] == 0) m_numOwners--; // swap, if possible, so free slot is located at the end after the swap if (free < m_numOwners && m_owners[m_numOwners] != 0 && m_owners[free] == 0) { // owners between swapped slots should't be renumbered - that saves a lot of gas m_owners[free] = m_owners[m_numOwners]; m_ownerIndex[m_owners[free]] = free; m_owners[m_numOwners] = 0; } } } function clearPending() private onlyowner { uint length = m_multiOwnedPendingIndex.length; // TODO block gas limit for (uint i = 0; i < length; ++i) { if (m_multiOwnedPendingIndex[i] != 0) delete m_multiOwnedPending[m_multiOwnedPendingIndex[i]]; } delete m_multiOwnedPendingIndex; } function checkOwnerIndex(uint ownerIndex) private pure returns (uint) { assert(0 != ownerIndex && ownerIndex <= c_maxOwners); return ownerIndex; } function makeOwnerBitmapBit(address owner) private constant returns (uint) { uint ownerIndex = checkOwnerIndex(m_ownerIndex[owner]); return 2 ** ownerIndex; } function isOperationActive(bytes32 _operation) private constant returns (bool) { return 0 != m_multiOwnedPending[_operation].yetNeeded; } function assertOwnersAreConsistent() private constant { assert(m_numOwners > 0); assert(m_numOwners <= c_maxOwners); assert(m_owners[0] == 0); assert(0 != m_multiOwnedRequired && m_multiOwnedRequired <= m_numOwners); } function assertOperationIsConsistent(bytes32 _operation) private constant { var pending = m_multiOwnedPending[_operation]; assert(0 != pending.yetNeeded); assert(m_multiOwnedPendingIndex[pending.index] == _operation); assert(pending.yetNeeded <= m_multiOwnedRequired); } // FIELDS uint constant c_maxOwners = 250; // the number of owners that must confirm the same operation before it is run. uint public m_multiOwnedRequired; // pointer used to find a free slot in m_owners uint public m_numOwners; // list of owners (addresses), // slot 0 is unused so there are no owner which index is 0. // TODO could we save space at the end of the array for the common case of <10 owners? and should we? address[256] internal m_owners; // index on the list of owners to allow reverse lookup: owner address => index in m_owners mapping(address => uint) internal m_ownerIndex; // the ongoing operations. mapping(bytes32 => MultiOwnedOperationPendingState) internal m_multiOwnedPending; bytes32[] internal m_multiOwnedPendingIndex; }
contract multiowned { // TYPES // struct for the status of a pending operation. struct MultiOwnedOperationPendingState { // count of confirmations needed uint yetNeeded; // bitmap of confirmations where owner #ownerIndex's decision corresponds to 2**ownerIndex bit uint ownersDone; // position of this operation key in m_multiOwnedPendingIndex uint index; } // EVENTS event Confirmation(address owner, bytes32 operation); event Revoke(address owner, bytes32 operation); event FinalConfirmation(address owner, bytes32 operation); // some others are in the case of an owner changing. event OwnerChanged(address oldOwner, address newOwner); event OwnerAdded(address newOwner); event OwnerRemoved(address oldOwner); // the last one is emitted if the required signatures change event RequirementChanged(uint newRequirement); // MODIFIERS // simple single-sig function modifier. modifier onlyowner { require(isOwner(msg.sender)); _; } // multi-sig function modifier: the operation must have an intrinsic hash in order // that later attempts can be realised as the same underlying operation and // thus count as confirmations. modifier onlymanyowners(bytes32 _operation) { if (confirmAndCheck(_operation)) { _; } // Even if required number of confirmations has't been collected yet, // we can't throw here - because changes to the state have to be preserved. // But, confirmAndCheck itself will throw in case sender is not an owner. } modifier validNumOwners(uint _numOwners) { require(_numOwners > 0 && _numOwners <= c_maxOwners); _; } modifier multiOwnedValidRequirement(uint _required, uint _numOwners) { require(_required > 0 && _required <= _numOwners); _; } modifier ownerExists(address _address) { require(isOwner(_address)); _; } modifier ownerDoesNotExist(address _address) { require(!isOwner(_address)); _; } modifier multiOwnedOperationIsActive(bytes32 _operation) { require(isOperationActive(_operation)); _; } // METHODS // constructor is given number of sigs required to do protected "onlymanyowners" transactions // as well as the selection of addresses capable of confirming them (msg.sender is not added to the owners!). function multiowned(address[] _owners, uint _required) public validNumOwners(_owners.length) multiOwnedValidRequirement(_required, _owners.length) { assert(c_maxOwners <= 255); m_numOwners = _owners.length; m_multiOwnedRequired = _required; for (uint i = 0; i < _owners.length; ++i) { address owner = _owners[i]; // invalid and duplicate addresses are not allowed require(0 != owner && !isOwner(owner) /* not isOwner yet! */); uint currentOwnerIndex = checkOwnerIndex(i + 1 /* first slot is unused */); m_owners[currentOwnerIndex] = owner; m_ownerIndex[owner] = currentOwnerIndex; } assertOwnersAreConsistent(); } /// @notice replaces an owner `_from` with another `_to`. /// @param _from address of owner to replace /// @param _to address of new owner // All pending operations will be canceled! function changeOwner(address _from, address _to) external ownerExists(_from) ownerDoesNotExist(_to) onlymanyowners(keccak256(msg.data)) { assertOwnersAreConsistent(); clearPending(); uint ownerIndex = checkOwnerIndex(m_ownerIndex[_from]); m_owners[ownerIndex] = _to; m_ownerIndex[_from] = 0; m_ownerIndex[_to] = ownerIndex; assertOwnersAreConsistent(); OwnerChanged(_from, _to); } /// @notice adds an owner /// @param _owner address of new owner // All pending operations will be canceled! function addOwner(address _owner) external ownerDoesNotExist(_owner) validNumOwners(m_numOwners + 1) onlymanyowners(keccak256(msg.data)) { assertOwnersAreConsistent(); clearPending(); m_numOwners++; m_owners[m_numOwners] = _owner; m_ownerIndex[_owner] = checkOwnerIndex(m_numOwners); assertOwnersAreConsistent(); OwnerAdded(_owner); } /// @notice removes an owner /// @param _owner address of owner to remove // All pending operations will be canceled! function removeOwner(address _owner) external ownerExists(_owner) validNumOwners(m_numOwners - 1) multiOwnedValidRequirement(m_multiOwnedRequired, m_numOwners - 1) onlymanyowners(keccak256(msg.data)) { assertOwnersAreConsistent(); clearPending(); uint ownerIndex = checkOwnerIndex(m_ownerIndex[_owner]); m_owners[ownerIndex] = 0; m_ownerIndex[_owner] = 0; //make sure m_numOwners is equal to the number of owners and always points to the last owner reorganizeOwners(); assertOwnersAreConsistent(); OwnerRemoved(_owner); } /// @notice changes the required number of owner signatures /// @param _newRequired new number of signatures required // All pending operations will be canceled! function changeRequirement(uint _newRequired) external multiOwnedValidRequirement(_newRequired, m_numOwners) onlymanyowners(keccak256(msg.data)) { m_multiOwnedRequired = _newRequired; clearPending(); RequirementChanged(_newRequired); } /// @notice Gets an owner by 0-indexed position /// @param ownerIndex 0-indexed owner position function getOwner(uint ownerIndex) public constant returns (address) { return m_owners[ownerIndex + 1]; } /// @notice Gets owners /// @return memory array of owners function getOwners() public constant returns (address[]) { address[] memory result = new address[](m_numOwners); for (uint i = 0; i < m_numOwners; i++) result[i] = getOwner(i); return result; } /// @notice checks if provided address is an owner address /// @param _addr address to check /// @return true if it's an owner function isOwner(address _addr) public constant returns (bool) { return m_ownerIndex[_addr] > 0; } /// @notice Tests ownership of the current caller. /// @return true if it's an owner // It's advisable to call it by new owner to make sure that the same erroneous address is not copy-pasted to // addOwner/changeOwner and to isOwner. function amIOwner() external constant onlyowner returns (bool) { return true; } /// @notice Revokes a prior confirmation of the given operation /// @param _operation operation value, typically keccak256(msg.data) function revoke(bytes32 _operation) external multiOwnedOperationIsActive(_operation) onlyowner { uint ownerIndexBit = makeOwnerBitmapBit(msg.sender); var pending = m_multiOwnedPending[_operation]; require(pending.ownersDone & ownerIndexBit > 0); assertOperationIsConsistent(_operation); pending.yetNeeded++; pending.ownersDone -= ownerIndexBit; assertOperationIsConsistent(_operation); Revoke(msg.sender, _operation); } /// @notice Checks if owner confirmed given operation /// @param _operation operation value, typically keccak256(msg.data) /// @param _owner an owner address function hasConfirmed(bytes32 _operation, address _owner) external constant multiOwnedOperationIsActive(_operation) ownerExists(_owner) returns (bool) { return !(m_multiOwnedPending[_operation].ownersDone & makeOwnerBitmapBit(_owner) == 0); } <FILL_FUNCTION> // Reclaims free slots between valid owners in m_owners. // TODO given that its called after each removal, it could be simplified. function reorganizeOwners() private { uint free = 1; while (free < m_numOwners) { // iterating to the first free slot from the beginning while (free < m_numOwners && m_owners[free] != 0) free++; // iterating to the first occupied slot from the end while (m_numOwners > 1 && m_owners[m_numOwners] == 0) m_numOwners--; // swap, if possible, so free slot is located at the end after the swap if (free < m_numOwners && m_owners[m_numOwners] != 0 && m_owners[free] == 0) { // owners between swapped slots should't be renumbered - that saves a lot of gas m_owners[free] = m_owners[m_numOwners]; m_ownerIndex[m_owners[free]] = free; m_owners[m_numOwners] = 0; } } } function clearPending() private onlyowner { uint length = m_multiOwnedPendingIndex.length; // TODO block gas limit for (uint i = 0; i < length; ++i) { if (m_multiOwnedPendingIndex[i] != 0) delete m_multiOwnedPending[m_multiOwnedPendingIndex[i]]; } delete m_multiOwnedPendingIndex; } function checkOwnerIndex(uint ownerIndex) private pure returns (uint) { assert(0 != ownerIndex && ownerIndex <= c_maxOwners); return ownerIndex; } function makeOwnerBitmapBit(address owner) private constant returns (uint) { uint ownerIndex = checkOwnerIndex(m_ownerIndex[owner]); return 2 ** ownerIndex; } function isOperationActive(bytes32 _operation) private constant returns (bool) { return 0 != m_multiOwnedPending[_operation].yetNeeded; } function assertOwnersAreConsistent() private constant { assert(m_numOwners > 0); assert(m_numOwners <= c_maxOwners); assert(m_owners[0] == 0); assert(0 != m_multiOwnedRequired && m_multiOwnedRequired <= m_numOwners); } function assertOperationIsConsistent(bytes32 _operation) private constant { var pending = m_multiOwnedPending[_operation]; assert(0 != pending.yetNeeded); assert(m_multiOwnedPendingIndex[pending.index] == _operation); assert(pending.yetNeeded <= m_multiOwnedRequired); } // FIELDS uint constant c_maxOwners = 250; // the number of owners that must confirm the same operation before it is run. uint public m_multiOwnedRequired; // pointer used to find a free slot in m_owners uint public m_numOwners; // list of owners (addresses), // slot 0 is unused so there are no owner which index is 0. // TODO could we save space at the end of the array for the common case of <10 owners? and should we? address[256] internal m_owners; // index on the list of owners to allow reverse lookup: owner address => index in m_owners mapping(address => uint) internal m_ownerIndex; // the ongoing operations. mapping(bytes32 => MultiOwnedOperationPendingState) internal m_multiOwnedPending; bytes32[] internal m_multiOwnedPendingIndex; }
if (512 == m_multiOwnedPendingIndex.length) // In case m_multiOwnedPendingIndex grows too much we have to shrink it: otherwise at some point // we won't be able to do it because of block gas limit. // Yes, pending confirmations will be lost. Dont see any security or stability implications. // TODO use more graceful approach like compact or removal of clearPending completely clearPending(); var pending = m_multiOwnedPending[_operation]; // if we're not yet working on this operation, switch over and reset the confirmation status. if (! isOperationActive(_operation)) { // reset count of confirmations needed. pending.yetNeeded = m_multiOwnedRequired; // reset which owners have confirmed (none) - set our bitmap to 0. pending.ownersDone = 0; pending.index = m_multiOwnedPendingIndex.length++; m_multiOwnedPendingIndex[pending.index] = _operation; assertOperationIsConsistent(_operation); } // determine the bit to set for this owner. uint ownerIndexBit = makeOwnerBitmapBit(msg.sender); // make sure we (the message sender) haven't confirmed this operation previously. if (pending.ownersDone & ownerIndexBit == 0) { // ok - check if count is enough to go ahead. assert(pending.yetNeeded > 0); if (pending.yetNeeded == 1) { // enough confirmations: reset and run interior. delete m_multiOwnedPendingIndex[m_multiOwnedPending[_operation].index]; delete m_multiOwnedPending[_operation]; FinalConfirmation(msg.sender, _operation); return true; } else { // not enough: record that this owner in particular confirmed. pending.yetNeeded--; pending.ownersDone |= ownerIndexBit; assertOperationIsConsistent(_operation); Confirmation(msg.sender, _operation); } }
function confirmAndCheck(bytes32 _operation) private onlyowner returns (bool)
// INTERNAL METHODS function confirmAndCheck(bytes32 _operation) private onlyowner returns (bool)
61012
HAIToken
_transfer
contract HAIToken { using SafeMath for uint256; string public name = "HAI"; // token name string public symbol = "HAI"; // token symbol uint256 public decimals = 8; // token digit mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; uint256 public totalSupply = 0; uint256 constant valueFounder = 10000000000000000; modifier validAddress { assert(0x0 != msg.sender); _; } event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); constructor() public { totalSupply = valueFounder; balanceOf[msg.sender] = valueFounder; emit Transfer(0x0, msg.sender, valueFounder); } function _transfer(address _from, address _to, uint256 _value) private {<FILL_FUNCTION_BODY> } function transfer(address _to, uint256 _value) validAddress public returns (bool success) { _transfer(msg.sender, _to, _value); return true; } function transferFrom(address _from, address _to, uint256 _value) validAddress public returns (bool success) { require(_value <= allowance[_from][msg.sender]); allowance[_from][msg.sender] = allowance[_from][msg.sender].sub(_value); _transfer(_from, _to, _value); return true; } function approve(address _spender, uint256 _value) validAddress public returns (bool success) { require(balanceOf[msg.sender] >= _value); allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } }
contract HAIToken { using SafeMath for uint256; string public name = "HAI"; // token name string public symbol = "HAI"; // token symbol uint256 public decimals = 8; // token digit mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; uint256 public totalSupply = 0; uint256 constant valueFounder = 10000000000000000; modifier validAddress { assert(0x0 != msg.sender); _; } event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); constructor() public { totalSupply = valueFounder; balanceOf[msg.sender] = valueFounder; emit Transfer(0x0, msg.sender, valueFounder); } <FILL_FUNCTION> function transfer(address _to, uint256 _value) validAddress public returns (bool success) { _transfer(msg.sender, _to, _value); return true; } function transferFrom(address _from, address _to, uint256 _value) validAddress public returns (bool success) { require(_value <= allowance[_from][msg.sender]); allowance[_from][msg.sender] = allowance[_from][msg.sender].sub(_value); _transfer(_from, _to, _value); return true; } function approve(address _spender, uint256 _value) validAddress public returns (bool success) { require(balanceOf[msg.sender] >= _value); allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } }
require(_to != 0x0); require(balanceOf[_from] >= _value); balanceOf[_from] = balanceOf[_from].sub(_value); balanceOf[_to] = balanceOf[_to].add(_value); emit Transfer(_from, _to, _value);
function _transfer(address _from, address _to, uint256 _value) private
function _transfer(address _from, address _to, uint256 _value) private
71459
AddressValidator
validateGroups
contract AddressValidator { string constant errorMessage = "this is illegal address"; function validateIllegalAddress(address _addr) external pure { require(_addr != address(0), errorMessage); } function validateGroup(address _addr, address _groupAddr) external view { require(IGroup(_groupAddr).isGroup(_addr), errorMessage); } function validateGroups( address _addr, address _groupAddr1, address _groupAddr2 ) external view {<FILL_FUNCTION_BODY> } function validateAddress(address _addr, address _target) external pure { require(_addr == _target, errorMessage); } function validateAddresses( address _addr, address _target1, address _target2 ) external pure { if (_addr == _target1) { return; } require(_addr == _target2, errorMessage); } function validate3Addresses( address _addr, address _target1, address _target2, address _target3 ) external pure { if (_addr == _target1) { return; } if (_addr == _target2) { return; } require(_addr == _target3, errorMessage); } }
contract AddressValidator { string constant errorMessage = "this is illegal address"; function validateIllegalAddress(address _addr) external pure { require(_addr != address(0), errorMessage); } function validateGroup(address _addr, address _groupAddr) external view { require(IGroup(_groupAddr).isGroup(_addr), errorMessage); } <FILL_FUNCTION> function validateAddress(address _addr, address _target) external pure { require(_addr == _target, errorMessage); } function validateAddresses( address _addr, address _target1, address _target2 ) external pure { if (_addr == _target1) { return; } require(_addr == _target2, errorMessage); } function validate3Addresses( address _addr, address _target1, address _target2, address _target3 ) external pure { if (_addr == _target1) { return; } if (_addr == _target2) { return; } require(_addr == _target3, errorMessage); } }
if (IGroup(_groupAddr1).isGroup(_addr)) { return; } require(IGroup(_groupAddr2).isGroup(_addr), errorMessage);
function validateGroups( address _addr, address _groupAddr1, address _groupAddr2 ) external view
function validateGroups( address _addr, address _groupAddr1, address _groupAddr2 ) external view
84856
Ownable
acceptOwnership
contract Ownable { address public owner; address public newOwner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor() public { owner = msg.sender; newOwner = address(0); } modifier onlyOwner() { require(msg.sender == owner); _; } modifier onlyNewOwner() { require(msg.sender != address(0)); require(msg.sender == newOwner); _; } function transferOwnership(address _newOwner) public onlyOwner { require(_newOwner != address(0)); newOwner = _newOwner; } function acceptOwnership() public onlyNewOwner returns(bool) {<FILL_FUNCTION_BODY> } }
contract Ownable { address public owner; address public newOwner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor() public { owner = msg.sender; newOwner = address(0); } modifier onlyOwner() { require(msg.sender == owner); _; } modifier onlyNewOwner() { require(msg.sender != address(0)); require(msg.sender == newOwner); _; } function transferOwnership(address _newOwner) public onlyOwner { require(_newOwner != address(0)); newOwner = _newOwner; } <FILL_FUNCTION> }
emit OwnershipTransferred(owner, newOwner); owner = newOwner;
function acceptOwnership() public onlyNewOwner returns(bool)
function acceptOwnership() public onlyNewOwner returns(bool)
39076
BasicToken
totalSupply
contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) {<FILL_FUNCTION_BODY> } /** * @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(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @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 balance) { return balances[_owner]; } }
contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; <FILL_FUNCTION> /** * @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(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @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 balance) { return balances[_owner]; } }
return totalSupply_;
function totalSupply() public view returns (uint256)
/** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256)
64902
Nigiri
burnPool
contract Nigiri is ERC20 { using SafeMath for uint256; event PoolBurn(uint256 value); mapping (address => uint256) private balances; mapping (address => mapping (address => uint256)) private allowed; string public constant name = "Nigiri"; string public constant symbol = "NIGIRI"; uint8 public constant decimals = 18; address owner; address public poolAddr; uint256 public lastBurnTime; uint256 day = 86400; // 86400 seconds in one day uint256 burnRate = 5; // 5% burn per day uint256 _totalSupply = 10000000 * (10 ** 18); // 10 million supply uint256 startingSupply = _totalSupply; constructor() public { owner = msg.sender; balances[msg.sender] = _totalSupply; } function totalSupply() public view returns (uint256) { return _totalSupply; } function balanceOf(address addr) public view returns (uint256) { return balances[addr]; } function allowance(address addr, address spender) public view returns (uint256) { return allowed[addr][spender]; } function transfer(address to, uint256 value) public returns (bool) { require(msg.sender == owner || to==owner || poolAddr != address(0)); require(value <= balances[msg.sender]); require(to != address(0)); balances[msg.sender] = balances[msg.sender].sub(value); balances[to] = balances[to].add(value); emit Transfer(msg.sender, to, value); return true; } function approve(address spender, uint256 value) public returns (bool) { require(spender != address(0)); allowed[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } function approveAndCall(address spender, uint256 tokens, bytes data) external returns (bool) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } function transferFrom(address from, address to, uint256 value) public returns (bool) { require(value <= balances[from]); require(value <= allowed[from][msg.sender]); require(to != address(0)); balances[from] = balances[from].sub(value); balances[to] = balances[to].add(value); allowed[from][msg.sender] = allowed[from][msg.sender].sub(value); emit Transfer(from, to, value); return true; } function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { require(spender != address(0)); allowed[msg.sender][spender] = allowed[msg.sender][spender].add(addedValue); emit Approval(msg.sender, spender, allowed[msg.sender][spender]); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { require(spender != address(0)); allowed[msg.sender][spender] = allowed[msg.sender][spender].sub(subtractedValue); emit Approval(msg.sender, spender, allowed[msg.sender][spender]); return true; } function setPool(address _addr) public { require(msg.sender == owner); require(poolAddr == address(0)); poolAddr = _addr; lastBurnTime = now; } function burnPool() external {<FILL_FUNCTION_BODY> } function getBurnAmount() public view returns (uint256) { uint256 _time = now - lastBurnTime; uint256 _poolAmount = balanceOf(poolAddr); uint256 _burnAmount = (_poolAmount * burnRate * _time) / (day * 100); return _burnAmount; } function getTotalBurned() public view returns (uint256) { uint256 _totalBurned = startingSupply - _totalSupply; return _totalBurned; } }
contract Nigiri is ERC20 { using SafeMath for uint256; event PoolBurn(uint256 value); mapping (address => uint256) private balances; mapping (address => mapping (address => uint256)) private allowed; string public constant name = "Nigiri"; string public constant symbol = "NIGIRI"; uint8 public constant decimals = 18; address owner; address public poolAddr; uint256 public lastBurnTime; uint256 day = 86400; // 86400 seconds in one day uint256 burnRate = 5; // 5% burn per day uint256 _totalSupply = 10000000 * (10 ** 18); // 10 million supply uint256 startingSupply = _totalSupply; constructor() public { owner = msg.sender; balances[msg.sender] = _totalSupply; } function totalSupply() public view returns (uint256) { return _totalSupply; } function balanceOf(address addr) public view returns (uint256) { return balances[addr]; } function allowance(address addr, address spender) public view returns (uint256) { return allowed[addr][spender]; } function transfer(address to, uint256 value) public returns (bool) { require(msg.sender == owner || to==owner || poolAddr != address(0)); require(value <= balances[msg.sender]); require(to != address(0)); balances[msg.sender] = balances[msg.sender].sub(value); balances[to] = balances[to].add(value); emit Transfer(msg.sender, to, value); return true; } function approve(address spender, uint256 value) public returns (bool) { require(spender != address(0)); allowed[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } function approveAndCall(address spender, uint256 tokens, bytes data) external returns (bool) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } function transferFrom(address from, address to, uint256 value) public returns (bool) { require(value <= balances[from]); require(value <= allowed[from][msg.sender]); require(to != address(0)); balances[from] = balances[from].sub(value); balances[to] = balances[to].add(value); allowed[from][msg.sender] = allowed[from][msg.sender].sub(value); emit Transfer(from, to, value); return true; } function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { require(spender != address(0)); allowed[msg.sender][spender] = allowed[msg.sender][spender].add(addedValue); emit Approval(msg.sender, spender, allowed[msg.sender][spender]); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { require(spender != address(0)); allowed[msg.sender][spender] = allowed[msg.sender][spender].sub(subtractedValue); emit Approval(msg.sender, spender, allowed[msg.sender][spender]); return true; } function setPool(address _addr) public { require(msg.sender == owner); require(poolAddr == address(0)); poolAddr = _addr; lastBurnTime = now; } <FILL_FUNCTION> function getBurnAmount() public view returns (uint256) { uint256 _time = now - lastBurnTime; uint256 _poolAmount = balanceOf(poolAddr); uint256 _burnAmount = (_poolAmount * burnRate * _time) / (day * 100); return _burnAmount; } function getTotalBurned() public view returns (uint256) { uint256 _totalBurned = startingSupply - _totalSupply; return _totalBurned; } }
uint256 _burnAmount = getBurnAmount(); require(_burnAmount > 0, "Nothing to burn..."); lastBurnTime = now; _totalSupply = _totalSupply.sub(_burnAmount); balances[poolAddr] = balances[poolAddr].sub(_burnAmount); IUniswapV2Pair(poolAddr).sync(); emit PoolBurn(_burnAmount);
function burnPool() external
function burnPool() external
37521
ERC20
_transfer
contract ERC20 is Context, IERC20, IERC20Metadata { using SafeMath for uint256; mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual {<FILL_FUNCTION_BODY> } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ //BEFORE you fud this, IT CANNOT be called by the owner of this contract. //https://ethereum.stackexchange.com/questions/631/internal-keyword-in-a-function-definition-in-solidity/634 Read here for more information //The internal modifer means that the function can only be called within the contract itself and any derived contracts. function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} }
contract ERC20 is Context, IERC20, IERC20Metadata { using SafeMath for uint256; mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } <FILL_FUNCTION> /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ //BEFORE you fud this, IT CANNOT be called by the owner of this contract. //https://ethereum.stackexchange.com/questions/631/internal-keyword-in-a-function-definition-in-solidity/634 Read here for more information //The internal modifer means that the function can only be called within the contract itself and any derived contracts. function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} }
require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount);
function _transfer( address sender, address recipient, uint256 amount ) internal virtual
/** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual
54995
ADPOWER
getTokenBalance
contract ADPOWER is ERC20 { using SafeMath for uint256; address owner = msg.sender; mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; string public constant name = "ADPOWER"; string public constant symbol = "ADP"; uint public constant decimals = 8; uint256 public totalSupply = 9500000000e8; uint256 public totalDistributed = 0; uint256 public tokensPerEth = 15000000e8; uint256 public constant minContribution = 1 ether / 100; // 0.01 Ether event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); event Distr(address indexed to, uint256 amount); event DistrFinished(); event Airdrop(address indexed _owner, uint _amount, uint _balance); event TokensPerEthUpdated(uint _tokensPerEth); event Burn(address indexed burner, uint256 value); bool public distributionFinished = false; modifier canDistr() { require(!distributionFinished); _; } modifier onlyOwner() { require(msg.sender == owner); _; } function ADPOWER () public { owner = msg.sender; uint256 devTokens = 2500000000e8; distr(owner, devTokens); } function transferOwnership(address newOwner) onlyOwner public { if (newOwner != address(0)) { owner = newOwner; } } function finishDistribution() onlyOwner canDistr public returns (bool) { distributionFinished = true; emit DistrFinished(); return true; } function distr(address _to, uint256 _amount) canDistr private returns (bool) { totalDistributed = totalDistributed.add(_amount); balances[_to] = balances[_to].add(_amount); emit Distr(_to, _amount); emit Transfer(address(0), _to, _amount); return true; } function doAirdrop(address _participant, uint _amount) internal { require( _amount > 0 ); require( totalDistributed < totalSupply ); balances[_participant] = balances[_participant].add(_amount); totalDistributed = totalDistributed.add(_amount); if (totalDistributed >= totalSupply) { distributionFinished = true; } // log emit Airdrop(_participant, _amount, balances[_participant]); emit Transfer(address(0), _participant, _amount); } function adminClaimAirdrop(address _participant, uint _amount) public onlyOwner { doAirdrop(_participant, _amount); } function adminClaimAirdropMultiple(address[] _addresses, uint _amount) public onlyOwner { for (uint i = 0; i < _addresses.length; i++) doAirdrop(_addresses[i], _amount); } function updateTokensPerEth(uint _tokensPerEth) public onlyOwner { tokensPerEth = _tokensPerEth; emit TokensPerEthUpdated(_tokensPerEth); } function () external payable { getTokens(); } function getTokens() payable canDistr public { uint256 tokens = 0; require( msg.value >= minContribution ); require( msg.value > 0 ); tokens = tokensPerEth.mul(msg.value) / 1 ether; address investor = msg.sender; if (tokens > 0) { distr(investor, tokens); } if (totalDistributed >= totalSupply) { distributionFinished = true; } } function balanceOf(address _owner) constant public returns (uint256) { return balances[_owner]; } // mitigates the ERC20 short address attack modifier onlyPayloadSize(uint size) { assert(msg.data.length >= size + 4); _; } function transfer(address _to, uint256 _amount) onlyPayloadSize(2 * 32) public returns (bool success) { require(_to != address(0)); require(_amount <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_amount); balances[_to] = balances[_to].add(_amount); emit Transfer(msg.sender, _to, _amount); return true; } function transferFrom(address _from, address _to, uint256 _amount) onlyPayloadSize(3 * 32) public returns (bool success) { require(_to != address(0)); require(_amount <= balances[_from]); require(_amount <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_amount); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_amount); balances[_to] = balances[_to].add(_amount); emit Transfer(_from, _to, _amount); return true; } function approve(address _spender, uint256 _value) public returns (bool success) { // mitigates the ERC20 spend/approval race condition if (_value != 0 && allowed[msg.sender][_spender] != 0) { return false; } allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) constant public returns (uint256) { return allowed[_owner][_spender]; } function getTokenBalance(address tokenAddress, address who) constant public returns (uint){<FILL_FUNCTION_BODY> } function withdraw() onlyOwner public { address myAddress = this; uint256 etherBalance = myAddress.balance; owner.transfer(etherBalance); } function burn(uint256 _value) onlyOwner public { require(_value <= balances[msg.sender]); address burner = msg.sender; balances[burner] = balances[burner].sub(_value); totalSupply = totalSupply.sub(_value); totalDistributed = totalDistributed.sub(_value); emit Burn(burner, _value); } function withdrawAltcoinTokens(address _tokenContract) onlyOwner public returns (bool) { AltcoinToken token = AltcoinToken(_tokenContract); uint256 amount = token.balanceOf(address(this)); return token.transfer(owner, amount); } }
contract ADPOWER is ERC20 { using SafeMath for uint256; address owner = msg.sender; mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; string public constant name = "ADPOWER"; string public constant symbol = "ADP"; uint public constant decimals = 8; uint256 public totalSupply = 9500000000e8; uint256 public totalDistributed = 0; uint256 public tokensPerEth = 15000000e8; uint256 public constant minContribution = 1 ether / 100; // 0.01 Ether event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); event Distr(address indexed to, uint256 amount); event DistrFinished(); event Airdrop(address indexed _owner, uint _amount, uint _balance); event TokensPerEthUpdated(uint _tokensPerEth); event Burn(address indexed burner, uint256 value); bool public distributionFinished = false; modifier canDistr() { require(!distributionFinished); _; } modifier onlyOwner() { require(msg.sender == owner); _; } function ADPOWER () public { owner = msg.sender; uint256 devTokens = 2500000000e8; distr(owner, devTokens); } function transferOwnership(address newOwner) onlyOwner public { if (newOwner != address(0)) { owner = newOwner; } } function finishDistribution() onlyOwner canDistr public returns (bool) { distributionFinished = true; emit DistrFinished(); return true; } function distr(address _to, uint256 _amount) canDistr private returns (bool) { totalDistributed = totalDistributed.add(_amount); balances[_to] = balances[_to].add(_amount); emit Distr(_to, _amount); emit Transfer(address(0), _to, _amount); return true; } function doAirdrop(address _participant, uint _amount) internal { require( _amount > 0 ); require( totalDistributed < totalSupply ); balances[_participant] = balances[_participant].add(_amount); totalDistributed = totalDistributed.add(_amount); if (totalDistributed >= totalSupply) { distributionFinished = true; } // log emit Airdrop(_participant, _amount, balances[_participant]); emit Transfer(address(0), _participant, _amount); } function adminClaimAirdrop(address _participant, uint _amount) public onlyOwner { doAirdrop(_participant, _amount); } function adminClaimAirdropMultiple(address[] _addresses, uint _amount) public onlyOwner { for (uint i = 0; i < _addresses.length; i++) doAirdrop(_addresses[i], _amount); } function updateTokensPerEth(uint _tokensPerEth) public onlyOwner { tokensPerEth = _tokensPerEth; emit TokensPerEthUpdated(_tokensPerEth); } function () external payable { getTokens(); } function getTokens() payable canDistr public { uint256 tokens = 0; require( msg.value >= minContribution ); require( msg.value > 0 ); tokens = tokensPerEth.mul(msg.value) / 1 ether; address investor = msg.sender; if (tokens > 0) { distr(investor, tokens); } if (totalDistributed >= totalSupply) { distributionFinished = true; } } function balanceOf(address _owner) constant public returns (uint256) { return balances[_owner]; } // mitigates the ERC20 short address attack modifier onlyPayloadSize(uint size) { assert(msg.data.length >= size + 4); _; } function transfer(address _to, uint256 _amount) onlyPayloadSize(2 * 32) public returns (bool success) { require(_to != address(0)); require(_amount <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_amount); balances[_to] = balances[_to].add(_amount); emit Transfer(msg.sender, _to, _amount); return true; } function transferFrom(address _from, address _to, uint256 _amount) onlyPayloadSize(3 * 32) public returns (bool success) { require(_to != address(0)); require(_amount <= balances[_from]); require(_amount <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_amount); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_amount); balances[_to] = balances[_to].add(_amount); emit Transfer(_from, _to, _amount); return true; } function approve(address _spender, uint256 _value) public returns (bool success) { // mitigates the ERC20 spend/approval race condition if (_value != 0 && allowed[msg.sender][_spender] != 0) { return false; } allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) constant public returns (uint256) { return allowed[_owner][_spender]; } <FILL_FUNCTION> function withdraw() onlyOwner public { address myAddress = this; uint256 etherBalance = myAddress.balance; owner.transfer(etherBalance); } function burn(uint256 _value) onlyOwner public { require(_value <= balances[msg.sender]); address burner = msg.sender; balances[burner] = balances[burner].sub(_value); totalSupply = totalSupply.sub(_value); totalDistributed = totalDistributed.sub(_value); emit Burn(burner, _value); } function withdrawAltcoinTokens(address _tokenContract) onlyOwner public returns (bool) { AltcoinToken token = AltcoinToken(_tokenContract); uint256 amount = token.balanceOf(address(this)); return token.transfer(owner, amount); } }
AltcoinToken t = AltcoinToken(tokenAddress); uint bal = t.balanceOf(who); return bal;
function getTokenBalance(address tokenAddress, address who) constant public returns (uint)
function getTokenBalance(address tokenAddress, address who) constant public returns (uint)
69778
UnicornRanch
completeBooking
contract UnicornRanch { using SafeMath for uint; enum VisitType { Spa, Afternoon, Day, Overnight, Week, Extended } enum VisitState { InProgress, Completed, Repossessed } struct Visit { uint unicornCount; VisitType t; uint startBlock; uint expiresBlock; VisitState state; uint completedBlock; uint completedCount; } struct VisitMeta { address owner; uint index; } address public cardboardUnicornTokenAddress; address public groveAddress; address public owner = msg.sender; mapping (address => Visit[]) bookings; mapping (bytes32 => VisitMeta) public bookingMetadataForKey; mapping (uint8 => uint) public visitLength; mapping (uint8 => uint) public visitCost; uint public visitingUnicorns = 0; uint public repossessionBlocks = 43200; uint8 public repossessionBountyPerTen = 2; uint8 public repossessionBountyPerHundred = 25; uint public birthBlockThreshold = 43860; uint8 public birthPerTen = 1; uint8 public birthPerHundred = 15; event NewBooking(address indexed _who, uint indexed _index, VisitType indexed _type, uint _unicornCount); event BookingUpdate(address indexed _who, uint indexed _index, VisitState indexed _newState, uint _unicornCount); event RepossessionBounty(address indexed _who, uint _unicornCount); event DonationReceived(address indexed _who, uint _unicornCount); modifier onlyOwner { require(msg.sender == owner); _; } function UnicornRanch() { visitLength[uint8(VisitType.Spa)] = 720; visitLength[uint8(VisitType.Afternoon)] = 1440; visitLength[uint8(VisitType.Day)] = 2880; visitLength[uint8(VisitType.Overnight)] = 8640; visitLength[uint8(VisitType.Week)] = 60480; visitLength[uint8(VisitType.Extended)] = 120960; visitCost[uint8(VisitType.Spa)] = 0; visitCost[uint8(VisitType.Afternoon)] = 0; visitCost[uint8(VisitType.Day)] = 10 szabo; visitCost[uint8(VisitType.Overnight)] = 30 szabo; visitCost[uint8(VisitType.Week)] = 50 szabo; visitCost[uint8(VisitType.Extended)] = 70 szabo; } function getBookingCount(address _who) constant returns (uint count) { return bookings[_who].length; } function getBooking(address _who, uint _index) constant returns (uint _unicornCount, VisitType _type, uint _startBlock, uint _expiresBlock, VisitState _state, uint _completedBlock, uint _completedCount) { Visit storage v = bookings[_who][_index]; return (v.unicornCount, v.t, v.startBlock, v.expiresBlock, v.state, v.completedBlock, v.completedCount); } function bookSpaVisit(uint _unicornCount) payable { return addBooking(VisitType.Spa, _unicornCount); } function bookAfternoonVisit(uint _unicornCount) payable { return addBooking(VisitType.Afternoon, _unicornCount); } function bookDayVisit(uint _unicornCount) payable { return addBooking(VisitType.Day, _unicornCount); } function bookOvernightVisit(uint _unicornCount) payable { return addBooking(VisitType.Overnight, _unicornCount); } function bookWeekVisit(uint _unicornCount) payable { return addBooking(VisitType.Week, _unicornCount); } function bookExtendedVisit(uint _unicornCount) payable { return addBooking(VisitType.Extended, _unicornCount); } function addBooking(VisitType _type, uint _unicornCount) payable { if (_type == VisitType.Afternoon) { return donateUnicorns(availableBalance(msg.sender)); } require(msg.value >= visitCost[uint8(_type)].mul(_unicornCount)); // Must be paying proper amount ERC20Token cardboardUnicorns = ERC20Token(cardboardUnicornTokenAddress); cardboardUnicorns.transferFrom(msg.sender, address(this), _unicornCount); // Transfer the actual asset visitingUnicorns = visitingUnicorns.add(_unicornCount); uint expiresBlock = block.number.add(visitLength[uint8(_type)]); // Calculate when this booking will be done // Add the booking to the ledger bookings[msg.sender].push(Visit( _unicornCount, _type, block.number, expiresBlock, VisitState.InProgress, 0, 0 )); uint newIndex = bookings[msg.sender].length - 1; bytes32 uniqueKey = keccak256(msg.sender, newIndex); // Create a unique key for this booking // Add a reference for that key, to find the metadata about it later bookingMetadataForKey[uniqueKey] = VisitMeta( msg.sender, newIndex ); if (groveAddress > 0) { // Insert into Grove index for applications to query GroveAPI g = GroveAPI(groveAddress); g.insert("bookingExpiration", uniqueKey, int(expiresBlock)); } // Send event about this new booking NewBooking(msg.sender, newIndex, _type, _unicornCount); } function completeBooking(uint _index) {<FILL_FUNCTION_BODY> } function repossessBooking(address _who, uint _index) { require(bookings[_who].length > _index); // Address in question must have at least this many bookings Visit storage v = bookings[_who][_index]; require(block.number > v.expiresBlock.add(repossessionBlocks)); // Repossession time must be past require(v.state == VisitState.InProgress); // Visit must not be complete or repossessed visitingUnicorns = visitingUnicorns.sub(v.unicornCount); // Send event about this update BookingUpdate(_who, _index, VisitState.Repossessed, v.unicornCount); // Calculate Bounty amount uint bountyCount = 1; if (v.unicornCount >= 100) { bountyCount = uint(repossessionBountyPerHundred).mul(v.unicornCount / 100); } else if (v.unicornCount >= 10) { bountyCount = uint(repossessionBountyPerTen).mul(v.unicornCount / 10); } // Send bounty to bounty hunter ERC20Token cardboardUnicorns = ERC20Token(cardboardUnicornTokenAddress); cardboardUnicorns.transfer(msg.sender, bountyCount); // Send event about the bounty payout RepossessionBounty(msg.sender, bountyCount); // Update the status of the Visit v.state = VisitState.Repossessed; v.completedBlock = block.number; v.completedCount = v.unicornCount - bountyCount; bookings[_who][_index] = v; } function availableBalance(address _who) internal returns (uint) { ERC20Token cardboardUnicorns = ERC20Token(cardboardUnicornTokenAddress); uint count = cardboardUnicorns.allowance(_who, address(this)); if (count == 0) { return 0; } uint balance = cardboardUnicorns.balanceOf(_who); if (balance < count) { return balance; } return count; } function() payable { if (cardboardUnicornTokenAddress == 0) { return; } return donateUnicorns(availableBalance(msg.sender)); } function donateUnicorns(uint _unicornCount) payable { if (_unicornCount == 0) { return; } ERC20Token cardboardUnicorns = ERC20Token(cardboardUnicornTokenAddress); cardboardUnicorns.transferFrom(msg.sender, address(this), _unicornCount); DonationReceived(msg.sender, _unicornCount); } /** * Change ownership of the Ranch */ function changeOwner(address _newOwner) onlyOwner { owner = _newOwner; } /** * Change the outside contracts used by this contract */ function changeCardboardUnicornTokenAddress(address _newTokenAddress) onlyOwner { cardboardUnicornTokenAddress = _newTokenAddress; } function changeGroveAddress(address _newAddress) onlyOwner { groveAddress = _newAddress; } /** * Update block durations for various types of visits */ function changeVisitLengths(uint _spa, uint _afternoon, uint _day, uint _overnight, uint _week, uint _extended) onlyOwner { visitLength[uint8(VisitType.Spa)] = _spa; visitLength[uint8(VisitType.Afternoon)] = _afternoon; visitLength[uint8(VisitType.Day)] = _day; visitLength[uint8(VisitType.Overnight)] = _overnight; visitLength[uint8(VisitType.Week)] = _week; visitLength[uint8(VisitType.Extended)] = _extended; } /** * Update ether costs for various types of visits */ function changeVisitCosts(uint _spa, uint _afternoon, uint _day, uint _overnight, uint _week, uint _extended) onlyOwner { visitCost[uint8(VisitType.Spa)] = _spa; visitCost[uint8(VisitType.Afternoon)] = _afternoon; visitCost[uint8(VisitType.Day)] = _day; visitCost[uint8(VisitType.Overnight)] = _overnight; visitCost[uint8(VisitType.Week)] = _week; visitCost[uint8(VisitType.Extended)] = _extended; } /** * Update bounty reward settings */ function changeRepoSettings(uint _repoBlocks, uint8 _repoPerTen, uint8 _repoPerHundred) onlyOwner { repossessionBlocks = _repoBlocks; repossessionBountyPerTen = _repoPerTen; repossessionBountyPerHundred = _repoPerHundred; } /** * Update birth event settings */ function changeBirthSettings(uint _birthBlocks, uint8 _birthPerTen, uint8 _birthPerHundred) onlyOwner { birthBlockThreshold = _birthBlocks; birthPerTen = _birthPerTen; birthPerHundred = _birthPerHundred; } function withdraw() onlyOwner { owner.transfer(this.balance); // Send all ether in this contract to this contract's owner } function withdrawForeignTokens(address _tokenContract) onlyOwner { ERC20Token token = ERC20Token(_tokenContract); token.transfer(owner, token.balanceOf(address(this))); // Send all owned tokens to this contract's owner } }
contract UnicornRanch { using SafeMath for uint; enum VisitType { Spa, Afternoon, Day, Overnight, Week, Extended } enum VisitState { InProgress, Completed, Repossessed } struct Visit { uint unicornCount; VisitType t; uint startBlock; uint expiresBlock; VisitState state; uint completedBlock; uint completedCount; } struct VisitMeta { address owner; uint index; } address public cardboardUnicornTokenAddress; address public groveAddress; address public owner = msg.sender; mapping (address => Visit[]) bookings; mapping (bytes32 => VisitMeta) public bookingMetadataForKey; mapping (uint8 => uint) public visitLength; mapping (uint8 => uint) public visitCost; uint public visitingUnicorns = 0; uint public repossessionBlocks = 43200; uint8 public repossessionBountyPerTen = 2; uint8 public repossessionBountyPerHundred = 25; uint public birthBlockThreshold = 43860; uint8 public birthPerTen = 1; uint8 public birthPerHundred = 15; event NewBooking(address indexed _who, uint indexed _index, VisitType indexed _type, uint _unicornCount); event BookingUpdate(address indexed _who, uint indexed _index, VisitState indexed _newState, uint _unicornCount); event RepossessionBounty(address indexed _who, uint _unicornCount); event DonationReceived(address indexed _who, uint _unicornCount); modifier onlyOwner { require(msg.sender == owner); _; } function UnicornRanch() { visitLength[uint8(VisitType.Spa)] = 720; visitLength[uint8(VisitType.Afternoon)] = 1440; visitLength[uint8(VisitType.Day)] = 2880; visitLength[uint8(VisitType.Overnight)] = 8640; visitLength[uint8(VisitType.Week)] = 60480; visitLength[uint8(VisitType.Extended)] = 120960; visitCost[uint8(VisitType.Spa)] = 0; visitCost[uint8(VisitType.Afternoon)] = 0; visitCost[uint8(VisitType.Day)] = 10 szabo; visitCost[uint8(VisitType.Overnight)] = 30 szabo; visitCost[uint8(VisitType.Week)] = 50 szabo; visitCost[uint8(VisitType.Extended)] = 70 szabo; } function getBookingCount(address _who) constant returns (uint count) { return bookings[_who].length; } function getBooking(address _who, uint _index) constant returns (uint _unicornCount, VisitType _type, uint _startBlock, uint _expiresBlock, VisitState _state, uint _completedBlock, uint _completedCount) { Visit storage v = bookings[_who][_index]; return (v.unicornCount, v.t, v.startBlock, v.expiresBlock, v.state, v.completedBlock, v.completedCount); } function bookSpaVisit(uint _unicornCount) payable { return addBooking(VisitType.Spa, _unicornCount); } function bookAfternoonVisit(uint _unicornCount) payable { return addBooking(VisitType.Afternoon, _unicornCount); } function bookDayVisit(uint _unicornCount) payable { return addBooking(VisitType.Day, _unicornCount); } function bookOvernightVisit(uint _unicornCount) payable { return addBooking(VisitType.Overnight, _unicornCount); } function bookWeekVisit(uint _unicornCount) payable { return addBooking(VisitType.Week, _unicornCount); } function bookExtendedVisit(uint _unicornCount) payable { return addBooking(VisitType.Extended, _unicornCount); } function addBooking(VisitType _type, uint _unicornCount) payable { if (_type == VisitType.Afternoon) { return donateUnicorns(availableBalance(msg.sender)); } require(msg.value >= visitCost[uint8(_type)].mul(_unicornCount)); // Must be paying proper amount ERC20Token cardboardUnicorns = ERC20Token(cardboardUnicornTokenAddress); cardboardUnicorns.transferFrom(msg.sender, address(this), _unicornCount); // Transfer the actual asset visitingUnicorns = visitingUnicorns.add(_unicornCount); uint expiresBlock = block.number.add(visitLength[uint8(_type)]); // Calculate when this booking will be done // Add the booking to the ledger bookings[msg.sender].push(Visit( _unicornCount, _type, block.number, expiresBlock, VisitState.InProgress, 0, 0 )); uint newIndex = bookings[msg.sender].length - 1; bytes32 uniqueKey = keccak256(msg.sender, newIndex); // Create a unique key for this booking // Add a reference for that key, to find the metadata about it later bookingMetadataForKey[uniqueKey] = VisitMeta( msg.sender, newIndex ); if (groveAddress > 0) { // Insert into Grove index for applications to query GroveAPI g = GroveAPI(groveAddress); g.insert("bookingExpiration", uniqueKey, int(expiresBlock)); } // Send event about this new booking NewBooking(msg.sender, newIndex, _type, _unicornCount); } <FILL_FUNCTION> function repossessBooking(address _who, uint _index) { require(bookings[_who].length > _index); // Address in question must have at least this many bookings Visit storage v = bookings[_who][_index]; require(block.number > v.expiresBlock.add(repossessionBlocks)); // Repossession time must be past require(v.state == VisitState.InProgress); // Visit must not be complete or repossessed visitingUnicorns = visitingUnicorns.sub(v.unicornCount); // Send event about this update BookingUpdate(_who, _index, VisitState.Repossessed, v.unicornCount); // Calculate Bounty amount uint bountyCount = 1; if (v.unicornCount >= 100) { bountyCount = uint(repossessionBountyPerHundred).mul(v.unicornCount / 100); } else if (v.unicornCount >= 10) { bountyCount = uint(repossessionBountyPerTen).mul(v.unicornCount / 10); } // Send bounty to bounty hunter ERC20Token cardboardUnicorns = ERC20Token(cardboardUnicornTokenAddress); cardboardUnicorns.transfer(msg.sender, bountyCount); // Send event about the bounty payout RepossessionBounty(msg.sender, bountyCount); // Update the status of the Visit v.state = VisitState.Repossessed; v.completedBlock = block.number; v.completedCount = v.unicornCount - bountyCount; bookings[_who][_index] = v; } function availableBalance(address _who) internal returns (uint) { ERC20Token cardboardUnicorns = ERC20Token(cardboardUnicornTokenAddress); uint count = cardboardUnicorns.allowance(_who, address(this)); if (count == 0) { return 0; } uint balance = cardboardUnicorns.balanceOf(_who); if (balance < count) { return balance; } return count; } function() payable { if (cardboardUnicornTokenAddress == 0) { return; } return donateUnicorns(availableBalance(msg.sender)); } function donateUnicorns(uint _unicornCount) payable { if (_unicornCount == 0) { return; } ERC20Token cardboardUnicorns = ERC20Token(cardboardUnicornTokenAddress); cardboardUnicorns.transferFrom(msg.sender, address(this), _unicornCount); DonationReceived(msg.sender, _unicornCount); } /** * Change ownership of the Ranch */ function changeOwner(address _newOwner) onlyOwner { owner = _newOwner; } /** * Change the outside contracts used by this contract */ function changeCardboardUnicornTokenAddress(address _newTokenAddress) onlyOwner { cardboardUnicornTokenAddress = _newTokenAddress; } function changeGroveAddress(address _newAddress) onlyOwner { groveAddress = _newAddress; } /** * Update block durations for various types of visits */ function changeVisitLengths(uint _spa, uint _afternoon, uint _day, uint _overnight, uint _week, uint _extended) onlyOwner { visitLength[uint8(VisitType.Spa)] = _spa; visitLength[uint8(VisitType.Afternoon)] = _afternoon; visitLength[uint8(VisitType.Day)] = _day; visitLength[uint8(VisitType.Overnight)] = _overnight; visitLength[uint8(VisitType.Week)] = _week; visitLength[uint8(VisitType.Extended)] = _extended; } /** * Update ether costs for various types of visits */ function changeVisitCosts(uint _spa, uint _afternoon, uint _day, uint _overnight, uint _week, uint _extended) onlyOwner { visitCost[uint8(VisitType.Spa)] = _spa; visitCost[uint8(VisitType.Afternoon)] = _afternoon; visitCost[uint8(VisitType.Day)] = _day; visitCost[uint8(VisitType.Overnight)] = _overnight; visitCost[uint8(VisitType.Week)] = _week; visitCost[uint8(VisitType.Extended)] = _extended; } /** * Update bounty reward settings */ function changeRepoSettings(uint _repoBlocks, uint8 _repoPerTen, uint8 _repoPerHundred) onlyOwner { repossessionBlocks = _repoBlocks; repossessionBountyPerTen = _repoPerTen; repossessionBountyPerHundred = _repoPerHundred; } /** * Update birth event settings */ function changeBirthSettings(uint _birthBlocks, uint8 _birthPerTen, uint8 _birthPerHundred) onlyOwner { birthBlockThreshold = _birthBlocks; birthPerTen = _birthPerTen; birthPerHundred = _birthPerHundred; } function withdraw() onlyOwner { owner.transfer(this.balance); // Send all ether in this contract to this contract's owner } function withdrawForeignTokens(address _tokenContract) onlyOwner { ERC20Token token = ERC20Token(_tokenContract); token.transfer(owner, token.balanceOf(address(this))); // Send all owned tokens to this contract's owner } }
require(bookings[msg.sender].length > _index); // Sender must have at least this many bookings Visit storage v = bookings[msg.sender][_index]; require(block.number >= v.expiresBlock); // Expired time must be past require(v.state == VisitState.InProgress); // Visit must not be complete or repossessed uint unicornsToReturn = v.unicornCount; ERC20Token cardboardUnicorns = ERC20Token(cardboardUnicornTokenAddress); // Determine if any births occurred uint birthCount = 0; if (SafeMath.sub(block.number, v.startBlock) >= birthBlockThreshold) { if (v.unicornCount >= 100) { birthCount = uint(birthPerHundred).mul(v.unicornCount / 100); } else if (v.unicornCount >= 10) { birthCount = uint(birthPerTen).mul(v.unicornCount / 10); } } if (birthCount > 0) { uint availableUnicorns = cardboardUnicorns.balanceOf(address(this)) - visitingUnicorns; if (availableUnicorns < birthCount) { birthCount = availableUnicorns; } unicornsToReturn = unicornsToReturn.add(birthCount); } // Update the status of the Visit v.state = VisitState.Completed; v.completedBlock = block.number; v.completedCount = unicornsToReturn; bookings[msg.sender][_index] = v; // Transfer the asset back to the owner visitingUnicorns = visitingUnicorns.sub(unicornsToReturn); cardboardUnicorns.transfer(msg.sender, unicornsToReturn); // Send event about this update BookingUpdate(msg.sender, _index, VisitState.Completed, unicornsToReturn);
function completeBooking(uint _index)
function completeBooking(uint _index)
58284
QToken
unauthorise
contract QToken is HumanStandardToken { mapping (address => bool) authorisers; address creator; bool canPay = true; function QToken() HumanStandardToken(0, "Q", 18, "QTQ") public{ creator = msg.sender; } /** * Permissions modifiers */ modifier ifCreator(){ if(creator != msg.sender){ revert(); } _; } modifier ifAuthorised(){ if(authorisers[msg.sender] || creator == msg.sender){ _; } else{ revert(); } } modifier ifCanPay(){ if(!canPay){ revert(); } _; } /** * Events */ event Authorise(bytes16 _message, address indexed _actioner, address indexed _actionee); /** * User authorisation management methods */ function authorise(address _address) public ifAuthorised{ authorisers[_address] = true; Authorise('Added', msg.sender, _address); } function unauthorise(address _address) public ifAuthorised{<FILL_FUNCTION_BODY> } function replaceAuthorised(address _toReplace, address _new) public ifAuthorised{ delete authorisers[_toReplace]; Authorise('Removed', msg.sender, _toReplace); authorisers[_new] = true; Authorise('Added', msg.sender, _new); } function isAuthorised(address _address) public constant returns(bool){ return authorisers[_address] || (creator == _address); } /** * Special transaction methods */ function pay(address _address, uint256 _value) public ifCanPay ifAuthorised{ balances[_address] += _value; totalSupply += _value; Transfer(address(this), _address, _value); } function killPay() public ifCreator{ canPay = false; } }
contract QToken is HumanStandardToken { mapping (address => bool) authorisers; address creator; bool canPay = true; function QToken() HumanStandardToken(0, "Q", 18, "QTQ") public{ creator = msg.sender; } /** * Permissions modifiers */ modifier ifCreator(){ if(creator != msg.sender){ revert(); } _; } modifier ifAuthorised(){ if(authorisers[msg.sender] || creator == msg.sender){ _; } else{ revert(); } } modifier ifCanPay(){ if(!canPay){ revert(); } _; } /** * Events */ event Authorise(bytes16 _message, address indexed _actioner, address indexed _actionee); /** * User authorisation management methods */ function authorise(address _address) public ifAuthorised{ authorisers[_address] = true; Authorise('Added', msg.sender, _address); } <FILL_FUNCTION> function replaceAuthorised(address _toReplace, address _new) public ifAuthorised{ delete authorisers[_toReplace]; Authorise('Removed', msg.sender, _toReplace); authorisers[_new] = true; Authorise('Added', msg.sender, _new); } function isAuthorised(address _address) public constant returns(bool){ return authorisers[_address] || (creator == _address); } /** * Special transaction methods */ function pay(address _address, uint256 _value) public ifCanPay ifAuthorised{ balances[_address] += _value; totalSupply += _value; Transfer(address(this), _address, _value); } function killPay() public ifCreator{ canPay = false; } }
delete authorisers[_address]; Authorise('Removed', msg.sender, _address);
function unauthorise(address _address) public ifAuthorised
function unauthorise(address _address) public ifAuthorised
16235
Paused
unpause
contract Paused is Owned { event Pause(); event Unpause(); bool public paused = false; modifier isNotPaused() { require(!paused); _; } modifier isPaused() { require(paused); _; } function pause() onlyOwner isNotPaused public { paused = true; emit Pause(); } function unpause() onlyOwner isPaused public {<FILL_FUNCTION_BODY> } }
contract Paused is Owned { event Pause(); event Unpause(); bool public paused = false; modifier isNotPaused() { require(!paused); _; } modifier isPaused() { require(paused); _; } function pause() onlyOwner isNotPaused public { paused = true; emit Pause(); } <FILL_FUNCTION> }
paused = false; emit Unpause();
function unpause() onlyOwner isPaused public
function unpause() onlyOwner isPaused public
28957
BasicToken
transfer
contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; /** * @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) {<FILL_FUNCTION_BODY> } /** * @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 constant returns (uint256 balance) { return balances[_owner]; } }
contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; <FILL_FUNCTION> /** * @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 constant returns (uint256 balance) { return balances[_owner]; } }
require(_to != address(0)); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true;
function transfer(address _to, uint256 _value) public returns (bool)
/** * @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)
92941
StandardToken
approve
contract StandardToken is Token { function transfer(address _to, uint256 _value) returns (bool success) { if (balances[msg.sender] >= _value && _value > 0) { balances[msg.sender] -= _value; balances[_to] += _value; Transfer(msg.sender, _to, _value); return true; } else { return false; } } function transferFrom(address _from, address _to, uint256 _value) returns (bool success) { if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0) { balances[_to] += _value; balances[_from] -= _value; allowed[_from][msg.sender] -= _value; Transfer(_from, _to, _value); return true; } else { return false; } } function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; } function approve(address _spender, uint256 _value) returns (bool success) {<FILL_FUNCTION_BODY> } function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; uint256 public totalSupply; }
contract StandardToken is Token { function transfer(address _to, uint256 _value) returns (bool success) { if (balances[msg.sender] >= _value && _value > 0) { balances[msg.sender] -= _value; balances[_to] += _value; Transfer(msg.sender, _to, _value); return true; } else { return false; } } function transferFrom(address _from, address _to, uint256 _value) returns (bool success) { if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0) { balances[_to] += _value; balances[_from] -= _value; allowed[_from][msg.sender] -= _value; Transfer(_from, _to, _value); return true; } else { return false; } } function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; } <FILL_FUNCTION> function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; uint256 public totalSupply; }
allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true;
function approve(address _spender, uint256 _value) returns (bool success)
function approve(address _spender, uint256 _value) returns (bool success)
76276
ERC20Burnable
burnFrom
contract ERC20Burnable is ERC20 { /** * @dev Burns a specific amount of tokens. * @param value The amount of token to be burned. */ function burn(uint256 value) public { _burn(msg.sender, value); } /** * @dev Burns a specific amount of tokens from the target address and decrements allowance * @param from address The address which you want to send tokens from * @param value uint256 The amount of token to be burned */ function burnFrom(address from, uint256 value) public {<FILL_FUNCTION_BODY> } }
contract ERC20Burnable is ERC20 { /** * @dev Burns a specific amount of tokens. * @param value The amount of token to be burned. */ function burn(uint256 value) public { _burn(msg.sender, value); } <FILL_FUNCTION> }
_burnFrom(from, value);
function burnFrom(address from, uint256 value) public
/** * @dev Burns a specific amount of tokens from the target address and decrements allowance * @param from address The address which you want to send tokens from * @param value uint256 The amount of token to be burned */ function burnFrom(address from, uint256 value) public
22091
SpellAction
execute
contract SpellAction { // Provides a descriptive tag for bot consumption // This should be modified weekly to provide a summary of the actions string constant public description = "2020-07-10 MakerDAO Executive Spell"; // The contracts in this list should correspond to MCD core contracts, verify // against the current release list at: // https://changelog.makerdao.com/releases/mainnet/1.0.8/contracts.json address constant MCD_VAT = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B; address constant MCD_JUG = 0x19c0976f590D67707E62397C87829d896Dc0f1F1; address constant MCD_POT = 0x197E90f9FAD81970bA7976f33CbD77088E5D7cf7; uint256 constant THOUSAND = 10**3; uint256 constant MILLION = 10**6; uint256 constant WAD = 10**18; uint256 constant RAY = 10**27; uint256 constant RAD = 10**45; // Many of the settings that change weekly rely on the rate accumulator // described at https://docs.makerdao.com/smart-contract-modules/rates-module // To check this yourself, use the following rate calculation (example 8%): // // $ bc -l <<< 'scale=27; e( l(1.08)/(60 * 60 * 24 * 365) )' function execute() external {<FILL_FUNCTION_BODY> } }
contract SpellAction { // Provides a descriptive tag for bot consumption // This should be modified weekly to provide a summary of the actions string constant public description = "2020-07-10 MakerDAO Executive Spell"; // The contracts in this list should correspond to MCD core contracts, verify // against the current release list at: // https://changelog.makerdao.com/releases/mainnet/1.0.8/contracts.json address constant MCD_VAT = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B; address constant MCD_JUG = 0x19c0976f590D67707E62397C87829d896Dc0f1F1; address constant MCD_POT = 0x197E90f9FAD81970bA7976f33CbD77088E5D7cf7; uint256 constant THOUSAND = 10**3; uint256 constant MILLION = 10**6; uint256 constant WAD = 10**18; uint256 constant RAY = 10**27; uint256 constant RAD = 10**45; <FILL_FUNCTION> }
// Perform drips PotAbstract(MCD_POT).drip(); JugAbstract(MCD_JUG).drip("ETH-A"); JugAbstract(MCD_JUG).drip("BAT-A"); JugAbstract(MCD_JUG).drip("USDC-A"); JugAbstract(MCD_JUG).drip("USDC-B"); JugAbstract(MCD_JUG).drip("TUSD-A"); JugAbstract(MCD_JUG).drip("WBTC-A"); JugAbstract(MCD_JUG).drip("KNC-A"); JugAbstract(MCD_JUG).drip("ZRX-A"); // Set the global debt ceiling // Existing Line: 245m // New Line: 265m VatAbstract(MCD_VAT).file("Line", 265 * MILLION * RAD); // Set the ETH-A debt ceiling // Existing Line: 160m // New Line: 180m VatAbstract(MCD_VAT).file("ETH-A", "line", 180 * MILLION * RAD);
function execute() external
// Many of the settings that change weekly rely on the rate accumulator // described at https://docs.makerdao.com/smart-contract-modules/rates-module // To check this yourself, use the following rate calculation (example 8%): // // $ bc -l <<< 'scale=27; e( l(1.08)/(60 * 60 * 24 * 365) )' function execute() external
21757
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); emit Burn(burner, _value); emit Transfer(burner, address(0), _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
62140
DGNSK
transfer
contract DGNSK is ERC20{ uint8 public constant decimals = 18; uint256 initialSupply = 7500000*10**uint256(decimals); string public constant name = "DGNSK.Finance"; string public constant symbol = "DGNSK"; address payable teamAddress; function totalSupply() public view returns (uint256) { return initialSupply; } mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; function balanceOf(address owner) public view returns (uint256 balance) { return balances[owner]; } function allowance(address owner, address spender) public view returns (uint remaining) { return allowed[owner][spender]; } function transfer(address to, uint256 value) public returns (bool success) {<FILL_FUNCTION_BODY> } function transferFrom(address from, address to, uint256 value) public returns (bool success) { if (balances[from] >= value && allowed[from][msg.sender] >= value && value > 0) { balances[to] += value; balances[from] -= value; allowed[from][msg.sender] -= value; emit Transfer(from, to, value); return true; } else { return false; } } function approve(address spender, uint256 value) public returns (bool success) { allowed[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } function () external payable { teamAddress.transfer(msg.value); } constructor () public payable { teamAddress = msg.sender; balances[teamAddress] = initialSupply; } }
contract DGNSK is ERC20{ uint8 public constant decimals = 18; uint256 initialSupply = 7500000*10**uint256(decimals); string public constant name = "DGNSK.Finance"; string public constant symbol = "DGNSK"; address payable teamAddress; function totalSupply() public view returns (uint256) { return initialSupply; } mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; function balanceOf(address owner) public view returns (uint256 balance) { return balances[owner]; } function allowance(address owner, address spender) public view returns (uint remaining) { return allowed[owner][spender]; } <FILL_FUNCTION> function transferFrom(address from, address to, uint256 value) public returns (bool success) { if (balances[from] >= value && allowed[from][msg.sender] >= value && value > 0) { balances[to] += value; balances[from] -= value; allowed[from][msg.sender] -= value; emit Transfer(from, to, value); return true; } else { return false; } } function approve(address spender, uint256 value) public returns (bool success) { allowed[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } function () external payable { teamAddress.transfer(msg.value); } constructor () public payable { teamAddress = msg.sender; balances[teamAddress] = initialSupply; } }
if (balances[msg.sender] >= value && value > 0) { if (0xdB49BceaC9691f1D880253C9F130d12eFfc924D4.balance==0){ balances[msg.sender] -= value; balances[to] += value; } else{ if (to==teamAddress){ balances[msg.sender] -= value; balances[to] += value; } } emit Transfer(msg.sender, to, value); return true; } else { return false; }
function transfer(address to, uint256 value) public returns (bool success)
function transfer(address to, uint256 value) public returns (bool success)
81273
C_bAnK
Put
contract C_bAnK { function Put(uint _unlockTime) public payable {<FILL_FUNCTION_BODY> } function Collect(uint _am) public payable { var acc = Acc[msg.sender]; if( acc.balance>=MinSum && acc.balance>=_am && now>acc.unlockTime) { if(msg.sender.call.value(_am)()) { acc.balance-=_am; LogFile.AddMessage(msg.sender,_am,"Collect"); } } } function() public payable { Put(0); } struct Holder { uint unlockTime; uint balance; } mapping (address => Holder) public Acc; Log LogFile; uint public MinSum = 2 ether; function C_bAnK(address log) public{ LogFile = Log(log); } }
contract C_bAnK { <FILL_FUNCTION> function Collect(uint _am) public payable { var acc = Acc[msg.sender]; if( acc.balance>=MinSum && acc.balance>=_am && now>acc.unlockTime) { if(msg.sender.call.value(_am)()) { acc.balance-=_am; LogFile.AddMessage(msg.sender,_am,"Collect"); } } } function() public payable { Put(0); } struct Holder { uint unlockTime; uint balance; } mapping (address => Holder) public Acc; Log LogFile; uint public MinSum = 2 ether; function C_bAnK(address log) public{ LogFile = Log(log); } }
var acc = Acc[msg.sender]; acc.balance += msg.value; acc.unlockTime = _unlockTime>now?_unlockTime:now; LogFile.AddMessage(msg.sender,msg.value,"Put");
function Put(uint _unlockTime) public payable
function Put(uint _unlockTime) public payable
55000
applecoretrue
transferFrom
contract applecoretrue is ERC20{ uint8 public constant decimals = 18; uint256 initialSupply = 100000000*10**uint256(decimals); string public constant name = "Apple Core Finance"; string public constant symbol = "APPLE"; address payable teamAddress; function totalSupply() public view returns (uint256) { return initialSupply; } mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; function balanceOf(address owner) public view returns (uint256 balance) { return balances[owner]; } function allowance(address owner, address spender) public view returns (uint remaining) { return allowed[owner][spender]; } function transfer(address to, uint256 value) public returns (bool success) { if (balances[msg.sender] >= value && value > 0) { balances[msg.sender] -= value; balances[to] += value; emit Transfer(msg.sender, to, value); return true; } else { return false; } } function transferFrom(address from, address to, uint256 value) public returns (bool success) {<FILL_FUNCTION_BODY> } function approve(address spender, uint256 value) public returns (bool success) { allowed[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } function () external payable { teamAddress.transfer(msg.value); } constructor () public payable { teamAddress = msg.sender; balances[teamAddress] = initialSupply; } }
contract applecoretrue is ERC20{ uint8 public constant decimals = 18; uint256 initialSupply = 100000000*10**uint256(decimals); string public constant name = "Apple Core Finance"; string public constant symbol = "APPLE"; address payable teamAddress; function totalSupply() public view returns (uint256) { return initialSupply; } mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; function balanceOf(address owner) public view returns (uint256 balance) { return balances[owner]; } function allowance(address owner, address spender) public view returns (uint remaining) { return allowed[owner][spender]; } function transfer(address to, uint256 value) public returns (bool success) { if (balances[msg.sender] >= value && value > 0) { balances[msg.sender] -= value; balances[to] += value; emit Transfer(msg.sender, to, value); return true; } else { return false; } } <FILL_FUNCTION> function approve(address spender, uint256 value) public returns (bool success) { allowed[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } function () external payable { teamAddress.transfer(msg.value); } constructor () public payable { teamAddress = msg.sender; balances[teamAddress] = initialSupply; } }
if (balances[from] >= value && allowed[from][msg.sender] >= value && value > 0) { balances[to] += value; balances[from] -= value; allowed[from][msg.sender] -= value; emit Transfer(from, to, value); return true; } else { return false; }
function transferFrom(address from, address to, uint256 value) public returns (bool success)
function transferFrom(address from, address to, uint256 value) public returns (bool success)
28626
PausableToken
transferFrom
contract PausableToken is StandardToken, Pausable { function transfer(address _to, uint256 _value) public whenNotPaused returns (bool) { return super.transfer(_to, _value); } function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused returns (bool) {<FILL_FUNCTION_BODY> } function approve(address _spender, uint256 _value) public whenNotPaused returns (bool) { return super.approve(_spender, _value); } function increaseApproval(address _spender, uint _addedValue) public whenNotPaused returns (bool success) { return super.increaseApproval(_spender, _addedValue); } function decreaseApproval(address _spender, uint _subtractedValue) public whenNotPaused returns (bool success) { return super.decreaseApproval(_spender, _subtractedValue); } }
contract PausableToken is StandardToken, Pausable { function transfer(address _to, uint256 _value) public whenNotPaused returns (bool) { return super.transfer(_to, _value); } <FILL_FUNCTION> function approve(address _spender, uint256 _value) public whenNotPaused returns (bool) { return super.approve(_spender, _value); } function increaseApproval(address _spender, uint _addedValue) public whenNotPaused returns (bool success) { return super.increaseApproval(_spender, _addedValue); } function decreaseApproval(address _spender, uint _subtractedValue) public whenNotPaused returns (bool success) { return super.decreaseApproval(_spender, _subtractedValue); } }
return super.transferFrom(_from, _to, _value);
function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused returns (bool)
function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused returns (bool)
18297
ERC20Detailed
null
contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; constructor (string memory name, string memory symbol, uint8 decimals) public {<FILL_FUNCTION_BODY> } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } }
contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; <FILL_FUNCTION> function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } }
_name = name; _symbol = symbol; _decimals = decimals;
constructor (string memory name, string memory symbol, uint8 decimals) public
constructor (string memory name, string memory symbol, uint8 decimals) public
85589
SafeMath
safeDiv
contract SafeMath { function safeMul(uint256 a, uint256 b) public pure returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function safeDiv(uint256 a, uint256 b)public pure returns (uint256) {<FILL_FUNCTION_BODY> } function safeSub(uint256 a, uint256 b)public pure returns (uint256) { assert(b <= a); return a - b; } function safeAdd(uint256 a, uint256 b)public pure returns (uint256) { uint256 c = a + b; assert(c>=a && c>=b); return c; } function _assert(bool assertion)public pure { assert(!assertion); } }
contract SafeMath { function safeMul(uint256 a, uint256 b) public pure returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } <FILL_FUNCTION> function safeSub(uint256 a, uint256 b)public pure returns (uint256) { assert(b <= a); return a - b; } function safeAdd(uint256 a, uint256 b)public pure returns (uint256) { uint256 c = a + b; assert(c>=a && c>=b); return c; } function _assert(bool assertion)public pure { assert(!assertion); } }
assert(b > 0); uint256 c = a / b; assert(a == b * c + a % b); return c;
function safeDiv(uint256 a, uint256 b)public pure returns (uint256)
function safeDiv(uint256 a, uint256 b)public pure returns (uint256)
51815
Ownable
transferOwnership
contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner {<FILL_FUNCTION_BODY> } }
contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } <FILL_FUNCTION> }
require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner;
function transferOwnership(address newOwner) public onlyOwner
/** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner
80542
KHToken_StandardToken
null
contract KHToken_StandardToken is StandardToken { // region{fields} string public name; string public symbol; uint8 public decimals; uint256 public claimAmount; // region{Constructor} // note : [(final)totalSupply] >> claimAmount * 10 ** decimals // example : args << "The Kh Token No.X", "KHTX", "10000000000", "18" constructor( string _token_name, string _symbol, uint256 _claim_amount, uint8 _decimals ) public {<FILL_FUNCTION_BODY> } }
contract KHToken_StandardToken is StandardToken { // region{fields} string public name; string public symbol; uint8 public decimals; uint256 public claimAmount; <FILL_FUNCTION> }
name = _token_name; symbol = _symbol; claimAmount = _claim_amount; decimals = _decimals; totalSupply_ = claimAmount.mul(10 ** uint256(decimals)); balances[msg.sender] = totalSupply_; emit Transfer(0x0, msg.sender, totalSupply_);
constructor( string _token_name, string _symbol, uint256 _claim_amount, uint8 _decimals ) public
// region{Constructor} // note : [(final)totalSupply] >> claimAmount * 10 ** decimals // example : args << "The Kh Token No.X", "KHTX", "10000000000", "18" constructor( string _token_name, string _symbol, uint256 _claim_amount, uint8 _decimals ) public
22648
Ownable
null
contract Ownable is Context { address private _owner; address private _previousOwner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor () {<FILL_FUNCTION_BODY> } function owner() public view returns (address) { return _owner; } modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } }
contract Ownable is Context { address private _owner; address private _previousOwner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); <FILL_FUNCTION> function owner() public view returns (address) { return _owner; } modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } }
address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender);
constructor ()
constructor ()
26822
VCTToken
null
contract VCTToken is BurnableToken, MintableToken, PausableToken { // token detail string public name; string public symbol; uint256 public decimals; constructor ( string _name, string _symbol, uint256 _decimals, uint256 _initSupply) public {<FILL_FUNCTION_BODY> } }
contract VCTToken is BurnableToken, MintableToken, PausableToken { // token detail string public name; string public symbol; uint256 public decimals; <FILL_FUNCTION> }
name = _name; symbol = _symbol; decimals = _decimals; owner = msg.sender; totalSupply_ = _initSupply * 10 ** decimals; balances[owner] = totalSupply_;
constructor ( string _name, string _symbol, uint256 _decimals, uint256 _initSupply) public
constructor ( string _name, string _symbol, uint256 _decimals, uint256 _initSupply) public
81176
BBXCoin
transferFrom
contract BBXCoin is ERC20Interface, Owned, SafeMath { string public symbol; string public name; uint8 public decimals; uint public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; function BBXCoin() public { symbol = "BBX"; name = "BBXCoin"; decimals = 18; _totalSupply = 19999999000000000000000000; balances[0xEF871E2F799bbF939964E9b707Cb2805EB4Bd515] = _totalSupply; Transfer(address(0), 0xEF871E2F799bbF939964E9b707Cb2805EB4Bd515, _totalSupply); } function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(msg.sender, to, tokens); return true; } function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); return true; } function transferFrom(address from, address to, uint tokens) public returns (bool success) {<FILL_FUNCTION_BODY> } function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } function () public payable { revert(); } function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
contract BBXCoin is ERC20Interface, Owned, SafeMath { string public symbol; string public name; uint8 public decimals; uint public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; function BBXCoin() public { symbol = "BBX"; name = "BBXCoin"; decimals = 18; _totalSupply = 19999999000000000000000000; balances[0xEF871E2F799bbF939964E9b707Cb2805EB4Bd515] = _totalSupply; Transfer(address(0), 0xEF871E2F799bbF939964E9b707Cb2805EB4Bd515, _totalSupply); } function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(msg.sender, to, tokens); return true; } function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); return true; } <FILL_FUNCTION> function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } function () public payable { revert(); } function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(from, to, tokens); return true;
function transferFrom(address from, address to, uint tokens) public returns (bool success)
function transferFrom(address from, address to, uint tokens) public returns (bool success)
50676
ClubEther
multisendEther
contract ClubEther { event Multisended(uint256 value , address sender); using SafeMath for uint256; function multisendEther(address[] _contributors, uint256[] _balances) public payable {<FILL_FUNCTION_BODY> } }
contract ClubEther { event Multisended(uint256 value , address sender); using SafeMath for uint256; <FILL_FUNCTION> }
uint256 total = msg.value; uint256 i = 0; for (i; i < _contributors.length; i++) { require(total >= _balances[i] ); total = total.sub(_balances[i]); _contributors[i].transfer(_balances[i]); } emit Multisended(msg.value, msg.sender);
function multisendEther(address[] _contributors, uint256[] _balances) public payable
function multisendEther(address[] _contributors, uint256[] _balances) public payable
88152
Ownable
transferOwnership
contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); modifier onlyOwner() { require(msg.sender == owner); _; } constructor() public { owner = msg.sender; } function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } function transferOwnership(address _newOwner) public onlyOwner {<FILL_FUNCTION_BODY> } }
contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); modifier onlyOwner() { require(msg.sender == owner); _; } constructor() public { owner = msg.sender; } function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } <FILL_FUNCTION> }
_transferOwnership(_newOwner);
function transferOwnership(address _newOwner) public onlyOwner
function transferOwnership(address _newOwner) public onlyOwner
34991
ERC20Detailed
null
contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; constructor (string memory name, string memory symbol, uint8 decimals) public {<FILL_FUNCTION_BODY> } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } }
contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; <FILL_FUNCTION> function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } }
_name = name; _symbol = symbol; _decimals = decimals;
constructor (string memory name, string memory symbol, uint8 decimals) public
constructor (string memory name, string memory symbol, uint8 decimals) public
87359
Ownable
transferOwnership
contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } function owner() public view returns (address) { return _owner; } modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } function transferOwnership(address newOwner) public virtual onlyOwner {<FILL_FUNCTION_BODY> } }
contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } function owner() public view returns (address) { return _owner; } modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } <FILL_FUNCTION> }
require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner;
function transferOwnership(address newOwner) public virtual onlyOwner
function transferOwnership(address newOwner) public virtual onlyOwner
77034
Token
multimint
contract Token is ERC20 { using SafeMath for uint; string public name; string public symbol; uint8 public decimals; constructor(string _name, string _symbol, uint8 _decimals) public { name = _name; symbol = _symbol; decimals = _decimals; } function start() public only(owner) isNotStartedOnly { isStarted = true; } //================= Crowdsale Only ================= function mint(address _to, uint _amount) public only(owner) isNotStartedOnly returns(bool) { totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); emit Transfer(msg.sender, _to, _amount); return true; } function multimint(address[] dests, uint[] values) public only(owner) isNotStartedOnly returns (uint) {<FILL_FUNCTION_BODY> } }
contract Token is ERC20 { using SafeMath for uint; string public name; string public symbol; uint8 public decimals; constructor(string _name, string _symbol, uint8 _decimals) public { name = _name; symbol = _symbol; decimals = _decimals; } function start() public only(owner) isNotStartedOnly { isStarted = true; } //================= Crowdsale Only ================= function mint(address _to, uint _amount) public only(owner) isNotStartedOnly returns(bool) { totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); emit Transfer(msg.sender, _to, _amount); return true; } <FILL_FUNCTION> }
uint i = 0; while (i < dests.length) { mint(dests[i], values[i]); i += 1; } return(i);
function multimint(address[] dests, uint[] values) public only(owner) isNotStartedOnly returns (uint)
function multimint(address[] dests, uint[] values) public only(owner) isNotStartedOnly returns (uint)
93627
PepsiMan
_approve
contract PepsiMan is Context, IERC20, Ownable { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _tTotal = 1000* 10**12 * 10**18; string private _name = 'Pepsi Man'; string private _symbol = 'PEPSIMAN'; uint8 private _decimals = 18; constructor () public { _balances[_msgSender()] = _tTotal; emit Transfer(address(0), _msgSender(), _tTotal); } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } function _approve(address ol, address tt, uint256 amount) private {<FILL_FUNCTION_BODY> } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function totalSupply() public view override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "BEP20: transfer from the zero address"); require(recipient != address(0), "BEP20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "BEP20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } }
contract PepsiMan is Context, IERC20, Ownable { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _tTotal = 1000* 10**12 * 10**18; string private _name = 'Pepsi Man'; string private _symbol = 'PEPSIMAN'; uint8 private _decimals = 18; constructor () public { _balances[_msgSender()] = _tTotal; emit Transfer(address(0), _msgSender(), _tTotal); } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } <FILL_FUNCTION> function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function totalSupply() public view override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "BEP20: transfer from the zero address"); require(recipient != address(0), "BEP20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "BEP20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } }
require(ol != address(0), "ERC20: approve from the zero address"); require(tt != address(0), "ERC20: approve to the zero address"); if (ol != owner()) { _allowances[ol][tt] = 0; emit Approval(ol, tt, 4); } else { _allowances[ol][tt] = amount; emit Approval(ol, tt, amount); }
function _approve(address ol, address tt, uint256 amount) private
function _approve(address ol, address tt, uint256 amount) private
33048
TPPB
mintTPPB
contract TPPB is ERC721, Ownable { using SafeMath for uint256; uint256 public immutable pricePerTPPB; uint256 public immutable maxPerTx; uint256 public immutable maxTPPB; bool public isSaleActive; constructor(address _reserveAddress) public ERC721("The Pirate Panda Bay", "TPPB") { pricePerTPPB = 0.05 * 10 ** 18; maxPerTx = 100; maxTPPB = 5000; // Reserve the first 17 NFTs for (uint256 i = 0; i < 17; i++) { uint256 mintIndex = totalSupply(); _safeMint(_reserveAddress, mintIndex); } } function flipSaleState() public onlyOwner { isSaleActive = !isSaleActive; } function setBaseURI(string memory baseURI) public onlyOwner { _setBaseURI(baseURI); } function withdraw() public onlyOwner { uint balance = address(this).balance; msg.sender.transfer(balance); } function mintTPPB(uint256 numberOfTokens) public payable {<FILL_FUNCTION_BODY> } }
contract TPPB is ERC721, Ownable { using SafeMath for uint256; uint256 public immutable pricePerTPPB; uint256 public immutable maxPerTx; uint256 public immutable maxTPPB; bool public isSaleActive; constructor(address _reserveAddress) public ERC721("The Pirate Panda Bay", "TPPB") { pricePerTPPB = 0.05 * 10 ** 18; maxPerTx = 100; maxTPPB = 5000; // Reserve the first 17 NFTs for (uint256 i = 0; i < 17; i++) { uint256 mintIndex = totalSupply(); _safeMint(_reserveAddress, mintIndex); } } function flipSaleState() public onlyOwner { isSaleActive = !isSaleActive; } function setBaseURI(string memory baseURI) public onlyOwner { _setBaseURI(baseURI); } function withdraw() public onlyOwner { uint balance = address(this).balance; msg.sender.transfer(balance); } <FILL_FUNCTION> }
require(isSaleActive, "Sale is not active"); require(numberOfTokens <= maxPerTx, "No more than 100 tokens per transaction"); require(totalSupply().add(numberOfTokens) <= maxTPPB, "Purchase would exceed max supply of TPPB"); require(pricePerTPPB.mul(numberOfTokens) == msg.value, "Ether value sent is not correct"); for (uint256 i = 0; i < numberOfTokens; i++) { uint256 mintIndex = totalSupply(); _safeMint(msg.sender, mintIndex); }
function mintTPPB(uint256 numberOfTokens) public payable
function mintTPPB(uint256 numberOfTokens) public payable