source_idx
stringlengths
1
5
contract_name
stringlengths
1
55
func_name
stringlengths
0
2.45k
masked_body
stringlengths
60
686k
masked_all
stringlengths
34
686k
func_body
stringlengths
6
324k
signature_only
stringlengths
11
2.47k
signature_extend
stringlengths
11
8.95k
39385
AxelToken
sendBatches
contract AxelToken is ERC20Token { string public name = 'AXEL-AIRDROP'; uint8 public decimals = 18; string public symbol = 'AXEL'; string public version = '1'; /** * @notice token contructor. 250000000 */ constructor() public { //totalSupply = 50000000000 * 10 ** uint256(decimals); //50.000.000.000 tokens initial supply; totalSupply = 56601700 * 10 ** uint256(decimals); //50.000.000.000 tokens initial supply; balances[msg.sender] = totalSupply; emit Transfer(0, msg.sender, totalSupply); } /** * @notice Function to claim any token stuck on contract */ function externalTokensRecovery(Token _address) onlyAdmin public { uint256 remainder = _address.balanceOf(this); //Check remainder tokens _address.transfer(msg.sender,remainder); //Transfer tokens to admin } /** Allow transfers of tokens in groups of addresses */ function sendBatches(address[] _addrs, uint256[] tokensValue) onlyAdmin public {<FILL_FUNCTION_BODY> } /** Allow the admin to burn tokens */ function burn(uint256 _value) onlyAdmin whenNotPaused public { require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); totalSupply = totalSupply.sub(_value); emit Burn(msg.sender, _value); emit Transfer(msg.sender, address(0), _value); } /** * @notice this contract will revert on direct non-function calls, also it's not payable * @dev Function to handle callback calls to contract */ function() public { revert(); } event Burn(address indexed burner, uint256 value); }
contract AxelToken is ERC20Token { string public name = 'AXEL-AIRDROP'; uint8 public decimals = 18; string public symbol = 'AXEL'; string public version = '1'; /** * @notice token contructor. 250000000 */ constructor() public { //totalSupply = 50000000000 * 10 ** uint256(decimals); //50.000.000.000 tokens initial supply; totalSupply = 56601700 * 10 ** uint256(decimals); //50.000.000.000 tokens initial supply; balances[msg.sender] = totalSupply; emit Transfer(0, msg.sender, totalSupply); } /** * @notice Function to claim any token stuck on contract */ function externalTokensRecovery(Token _address) onlyAdmin public { uint256 remainder = _address.balanceOf(this); //Check remainder tokens _address.transfer(msg.sender,remainder); //Transfer tokens to admin } <FILL_FUNCTION> /** Allow the admin to burn tokens */ function burn(uint256 _value) onlyAdmin whenNotPaused public { require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); totalSupply = totalSupply.sub(_value); emit Burn(msg.sender, _value); emit Transfer(msg.sender, address(0), _value); } /** * @notice this contract will revert on direct non-function calls, also it's not payable * @dev Function to handle callback calls to contract */ function() public { revert(); } event Burn(address indexed burner, uint256 value); }
require(_addrs.length == tokensValue.length); for(uint256 i = 0; i < _addrs.length; i++) { require(transfer(_addrs[i], tokensValue[i])); require(setLocked(_addrs[i], 1561766400)); // Locked for 06/29/2019 }
function sendBatches(address[] _addrs, uint256[] tokensValue) onlyAdmin public
/** Allow transfers of tokens in groups of addresses */ function sendBatches(address[] _addrs, uint256[] tokensValue) onlyAdmin public
19462
ERC20
null
contract ERC20 is ERC20Interface,SafeMath { mapping(address => uint256) public balanceOf; mapping(address => mapping(address => uint256)) allowed; constructor(string memory _name) public {<FILL_FUNCTION_BODY> } function transfer(address _to, uint256 _value)public returns (bool success) { require(_to != address(0)); require(balanceOf[msg.sender] >= _value); require(SafeMath.safeAdd(balanceOf[ _to],_value) >= balanceOf[ _to]); balanceOf[msg.sender] =SafeMath.safeSub(balanceOf[msg.sender],_value) ; balanceOf[_to] = SafeMath.safeAdd(balanceOf[_to] ,_value); emit Transfer(msg.sender, _to, _value); return true; } function transferFrom(address _from, address _to, uint256 _value)public returns (bool success) { require(_to != address(0)); require(allowed[_from][msg.sender] >= _value); require(balanceOf[_from] >= _value); require(SafeMath.safeAdd(balanceOf[ _to],_value) >= balanceOf[_to]); balanceOf[_from] =SafeMath.safeSub(balanceOf[_from],_value) ; balanceOf[_to] = SafeMath.safeAdd(balanceOf[_to],_value); allowed[_from][msg.sender] = SafeMath.safeSub(allowed[_from][msg.sender], _value); emit Transfer(msg.sender, _to, _value); return true; } function approve(address _spender, uint256 _value)public returns (bool success) { require((_value==0)||(allowed[msg.sender][_spender]==0)); allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender)public view returns (uint256 remaining) { return allowed[_owner][_spender]; } }
contract ERC20 is ERC20Interface,SafeMath { mapping(address => uint256) public balanceOf; mapping(address => mapping(address => uint256)) allowed; <FILL_FUNCTION> function transfer(address _to, uint256 _value)public returns (bool success) { require(_to != address(0)); require(balanceOf[msg.sender] >= _value); require(SafeMath.safeAdd(balanceOf[ _to],_value) >= balanceOf[ _to]); balanceOf[msg.sender] =SafeMath.safeSub(balanceOf[msg.sender],_value) ; balanceOf[_to] = SafeMath.safeAdd(balanceOf[_to] ,_value); emit Transfer(msg.sender, _to, _value); return true; } function transferFrom(address _from, address _to, uint256 _value)public returns (bool success) { require(_to != address(0)); require(allowed[_from][msg.sender] >= _value); require(balanceOf[_from] >= _value); require(SafeMath.safeAdd(balanceOf[ _to],_value) >= balanceOf[_to]); balanceOf[_from] =SafeMath.safeSub(balanceOf[_from],_value) ; balanceOf[_to] = SafeMath.safeAdd(balanceOf[_to],_value); allowed[_from][msg.sender] = SafeMath.safeSub(allowed[_from][msg.sender], _value); emit Transfer(msg.sender, _to, _value); return true; } function approve(address _spender, uint256 _value)public returns (bool success) { require((_value==0)||(allowed[msg.sender][_spender]==0)); allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender)public view returns (uint256 remaining) { return allowed[_owner][_spender]; } }
name = _name; symbol = "avmASM"; decimals = 18; totalSupply = 0; balanceOf[msg.sender] = totalSupply;
constructor(string memory _name) public
constructor(string memory _name) public
33151
ERC721Token
_burn
contract ERC721Token is SupportsInterfaceWithLookup, ERC721BasicToken, ERC721 { // Token name string internal name_; // Token symbol string internal symbol_; // Mapping from owner to list of owned token IDs mapping(address => uint256[]) internal ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) internal ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] internal allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) internal allTokensIndex; // Optional mapping for token URIs mapping(uint256 => string) internal tokenURIs; /** * @dev Constructor function */ constructor(string _name, string _symbol) public { name_ = _name; symbol_ = _symbol; // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(InterfaceId_ERC721Enumerable); _registerInterface(InterfaceId_ERC721Metadata); } /** * @dev Gets the token name * @return string representing the token name */ function name() external view returns (string) { return name_; } /** * @dev Gets the token symbol * @return string representing the token symbol */ function symbol() external view returns (string) { return symbol_; } /** * @dev Returns an URI for a given token ID * Throws if the token ID does not exist. May return an empty string. * @param _tokenId uint256 ID of the token to query */ function tokenURI(uint256 _tokenId) public view returns (string) { require(exists(_tokenId)); return tokenURIs[_tokenId]; } /** * @dev Gets the token ID at a given index of the tokens list of the requested owner * @param _owner address owning the tokens list to be accessed * @param _index uint256 representing the index to be accessed of the requested tokens list * @return uint256 token ID at the given index of the tokens list owned by the requested address */ function tokenOfOwnerByIndex( address _owner, uint256 _index ) public view returns (uint256) { require(_index < balanceOf(_owner)); return ownedTokens[_owner][_index]; } /** * @dev Gets the total amount of tokens stored by the contract * @return uint256 representing the total amount of tokens */ function totalSupply() public view returns (uint256) { return allTokens.length; } /** * @dev Gets the token ID at a given index of all the tokens in this contract * Reverts if the index is greater or equal to the total number of tokens * @param _index uint256 representing the index to be accessed of the tokens list * @return uint256 token ID at the given index of the tokens list */ function tokenByIndex(uint256 _index) public view returns (uint256) { require(_index < totalSupply()); return allTokens[_index]; } /** * @dev Internal function to set the token URI for a given token * Reverts if the token ID does not exist * @param _tokenId uint256 ID of the token to set its URI * @param _uri string URI to assign */ function _setTokenURI(uint256 _tokenId, string _uri) internal { require(exists(_tokenId)); tokenURIs[_tokenId] = _uri; } /** * @dev Internal function to add a token ID to the list of a given address * @param _to address representing the new owner of the given token ID * @param _tokenId uint256 ID of the token to be added to the tokens list of the given address */ function addTokenTo(address _to, uint256 _tokenId) internal { super.addTokenTo(_to, _tokenId); uint256 length = ownedTokens[_to].length; ownedTokens[_to].push(_tokenId); ownedTokensIndex[_tokenId] = length; } /** * @dev Internal function to remove a token ID from the list of a given address * @param _from address representing the previous owner of the given token ID * @param _tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function removeTokenFrom(address _from, uint256 _tokenId) internal { super.removeTokenFrom(_from, _tokenId); // To prevent a gap in the array, we store the last token in the index of the token to delete, and // then delete the last slot. uint256 tokenIndex = ownedTokensIndex[_tokenId]; uint256 lastTokenIndex = ownedTokens[_from].length.sub(1); uint256 lastToken = ownedTokens[_from][lastTokenIndex]; ownedTokens[_from][tokenIndex] = lastToken; // This also deletes the contents at the last position of the array ownedTokens[_from].length--; // Note that this will handle single-element arrays. In that case, both tokenIndex and lastTokenIndex are going to // be zero. Then we can make sure that we will remove _tokenId from the ownedTokens list since we are first swapping // the lastToken to the first position, and then dropping the element placed in the last position of the list ownedTokensIndex[_tokenId] = 0; ownedTokensIndex[lastToken] = tokenIndex; } /** * @dev Internal function to mint a new token * Reverts if the given token ID already exists * @param _to address the beneficiary that will own the minted token * @param _tokenId uint256 ID of the token to be minted by the msg.sender */ function _mint(address _to, uint256 _tokenId) internal { super._mint(_to, _tokenId); allTokensIndex[_tokenId] = allTokens.length; allTokens.push(_tokenId); } /** * @dev Internal function to burn a specific token * Reverts if the token does not exist * @param _owner owner of the token to burn * @param _tokenId uint256 ID of the token being burned by the msg.sender */ function _burn(address _owner, uint256 _tokenId) internal {<FILL_FUNCTION_BODY> } }
contract ERC721Token is SupportsInterfaceWithLookup, ERC721BasicToken, ERC721 { // Token name string internal name_; // Token symbol string internal symbol_; // Mapping from owner to list of owned token IDs mapping(address => uint256[]) internal ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) internal ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] internal allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) internal allTokensIndex; // Optional mapping for token URIs mapping(uint256 => string) internal tokenURIs; /** * @dev Constructor function */ constructor(string _name, string _symbol) public { name_ = _name; symbol_ = _symbol; // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(InterfaceId_ERC721Enumerable); _registerInterface(InterfaceId_ERC721Metadata); } /** * @dev Gets the token name * @return string representing the token name */ function name() external view returns (string) { return name_; } /** * @dev Gets the token symbol * @return string representing the token symbol */ function symbol() external view returns (string) { return symbol_; } /** * @dev Returns an URI for a given token ID * Throws if the token ID does not exist. May return an empty string. * @param _tokenId uint256 ID of the token to query */ function tokenURI(uint256 _tokenId) public view returns (string) { require(exists(_tokenId)); return tokenURIs[_tokenId]; } /** * @dev Gets the token ID at a given index of the tokens list of the requested owner * @param _owner address owning the tokens list to be accessed * @param _index uint256 representing the index to be accessed of the requested tokens list * @return uint256 token ID at the given index of the tokens list owned by the requested address */ function tokenOfOwnerByIndex( address _owner, uint256 _index ) public view returns (uint256) { require(_index < balanceOf(_owner)); return ownedTokens[_owner][_index]; } /** * @dev Gets the total amount of tokens stored by the contract * @return uint256 representing the total amount of tokens */ function totalSupply() public view returns (uint256) { return allTokens.length; } /** * @dev Gets the token ID at a given index of all the tokens in this contract * Reverts if the index is greater or equal to the total number of tokens * @param _index uint256 representing the index to be accessed of the tokens list * @return uint256 token ID at the given index of the tokens list */ function tokenByIndex(uint256 _index) public view returns (uint256) { require(_index < totalSupply()); return allTokens[_index]; } /** * @dev Internal function to set the token URI for a given token * Reverts if the token ID does not exist * @param _tokenId uint256 ID of the token to set its URI * @param _uri string URI to assign */ function _setTokenURI(uint256 _tokenId, string _uri) internal { require(exists(_tokenId)); tokenURIs[_tokenId] = _uri; } /** * @dev Internal function to add a token ID to the list of a given address * @param _to address representing the new owner of the given token ID * @param _tokenId uint256 ID of the token to be added to the tokens list of the given address */ function addTokenTo(address _to, uint256 _tokenId) internal { super.addTokenTo(_to, _tokenId); uint256 length = ownedTokens[_to].length; ownedTokens[_to].push(_tokenId); ownedTokensIndex[_tokenId] = length; } /** * @dev Internal function to remove a token ID from the list of a given address * @param _from address representing the previous owner of the given token ID * @param _tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function removeTokenFrom(address _from, uint256 _tokenId) internal { super.removeTokenFrom(_from, _tokenId); // To prevent a gap in the array, we store the last token in the index of the token to delete, and // then delete the last slot. uint256 tokenIndex = ownedTokensIndex[_tokenId]; uint256 lastTokenIndex = ownedTokens[_from].length.sub(1); uint256 lastToken = ownedTokens[_from][lastTokenIndex]; ownedTokens[_from][tokenIndex] = lastToken; // This also deletes the contents at the last position of the array ownedTokens[_from].length--; // Note that this will handle single-element arrays. In that case, both tokenIndex and lastTokenIndex are going to // be zero. Then we can make sure that we will remove _tokenId from the ownedTokens list since we are first swapping // the lastToken to the first position, and then dropping the element placed in the last position of the list ownedTokensIndex[_tokenId] = 0; ownedTokensIndex[lastToken] = tokenIndex; } /** * @dev Internal function to mint a new token * Reverts if the given token ID already exists * @param _to address the beneficiary that will own the minted token * @param _tokenId uint256 ID of the token to be minted by the msg.sender */ function _mint(address _to, uint256 _tokenId) internal { super._mint(_to, _tokenId); allTokensIndex[_tokenId] = allTokens.length; allTokens.push(_tokenId); } <FILL_FUNCTION> }
super._burn(_owner, _tokenId); // Clear metadata (if any) if (bytes(tokenURIs[_tokenId]).length != 0) { delete tokenURIs[_tokenId]; } // Reorg all tokens array uint256 tokenIndex = allTokensIndex[_tokenId]; uint256 lastTokenIndex = allTokens.length.sub(1); uint256 lastToken = allTokens[lastTokenIndex]; allTokens[tokenIndex] = lastToken; allTokens[lastTokenIndex] = 0; allTokens.length--; allTokensIndex[_tokenId] = 0; allTokensIndex[lastToken] = tokenIndex;
function _burn(address _owner, uint256 _tokenId) internal
/** * @dev Internal function to burn a specific token * Reverts if the token does not exist * @param _owner owner of the token to burn * @param _tokenId uint256 ID of the token being burned by the msg.sender */ function _burn(address _owner, uint256 _tokenId) internal
61416
Ownable
transferOwnership
contract Ownable { address public owner; mapping (address => bool) public admin; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor() public { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner,"I am not the owner of the wallet."); _; } modifier onlyOwnerOrAdmin() { require(msg.sender == owner || admin[msg.sender] == true,"It is not the owner or manager wallet address."); _; } function transferOwnership(address newOwner) onlyOwner public {<FILL_FUNCTION_BODY> } function setAdmin(address newAdmin) onlyOwner public { require(admin[newAdmin] != true && owner != newAdmin,"It is not an existing administrator wallet, and it must not be the owner wallet of the token."); admin[newAdmin] = true; } function unsetAdmin(address Admin) onlyOwner public { require(admin[Admin] != false && owner != Admin,"This is an existing admin wallet, it must not be a token holder wallet."); admin[Admin] = false; } }
contract Ownable { address public owner; mapping (address => bool) public admin; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor() public { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner,"I am not the owner of the wallet."); _; } modifier onlyOwnerOrAdmin() { require(msg.sender == owner || admin[msg.sender] == true,"It is not the owner or manager wallet address."); _; } <FILL_FUNCTION> function setAdmin(address newAdmin) onlyOwner public { require(admin[newAdmin] != true && owner != newAdmin,"It is not an existing administrator wallet, and it must not be the owner wallet of the token."); admin[newAdmin] = true; } function unsetAdmin(address Admin) onlyOwner public { require(admin[Admin] != false && owner != Admin,"This is an existing admin wallet, it must not be a token holder wallet."); admin[Admin] = false; } }
require(newOwner != address(0) && newOwner != owner && admin[newOwner] == true,"It must be the existing manager wallet, not the existing owner's wallet."); emit OwnershipTransferred(owner, newOwner); owner = newOwner;
function transferOwnership(address newOwner) onlyOwner public
function transferOwnership(address newOwner) onlyOwner public
80712
CocaCoinaCrowdsale
mintTokens
contract CocaCoinaCrowdsale is CappedCrowdsale, RefundableCrowdsale { function CocaCoinaCrowdsale(uint256 _startTime, uint256 _endTime, uint256 _rate, uint256 _goal, uint256 _cap, address _wallet, CocaCoinaCoin _token) public CappedCrowdsale(_cap) FinalizableCrowdsale() RefundableCrowdsale(_goal) Crowdsale(_startTime, _endTime, _rate, _wallet, _token) { require(_goal <= _cap); } // Changes the rate of the tokensale against 1ETH -> ERA/ETH function changeRate(uint256 newRate) public onlyOwner { require(newRate > 0); rate = newRate; } // Changes the bonus rate of the tokensale in percentage (40% = 140 , 15% = 115 , 10% = 110 , 5% = 105) function changeBonus(uint256 newBonus) public onlyOwner { require(newBonus >= 100 && newBonus <= 140); bonus = newBonus; } // Mint new tokens and send them to specific address function mintTokens(address addressToSend, uint256 tokensToMint) public onlyOwner {<FILL_FUNCTION_BODY> } function changeTokenOwner(address newOwner) public onlyOwner { token.transferOwnership(newOwner); } }
contract CocaCoinaCrowdsale is CappedCrowdsale, RefundableCrowdsale { function CocaCoinaCrowdsale(uint256 _startTime, uint256 _endTime, uint256 _rate, uint256 _goal, uint256 _cap, address _wallet, CocaCoinaCoin _token) public CappedCrowdsale(_cap) FinalizableCrowdsale() RefundableCrowdsale(_goal) Crowdsale(_startTime, _endTime, _rate, _wallet, _token) { require(_goal <= _cap); } // Changes the rate of the tokensale against 1ETH -> ERA/ETH function changeRate(uint256 newRate) public onlyOwner { require(newRate > 0); rate = newRate; } // Changes the bonus rate of the tokensale in percentage (40% = 140 , 15% = 115 , 10% = 110 , 5% = 105) function changeBonus(uint256 newBonus) public onlyOwner { require(newBonus >= 100 && newBonus <= 140); bonus = newBonus; } <FILL_FUNCTION> function changeTokenOwner(address newOwner) public onlyOwner { token.transferOwnership(newOwner); } }
require(tokensToMint > 0); require(addressToSend != 0); tokensToMint = SafeMath.mul(tokensToMint,1000000000000000000); token.mint(addressToSend,tokensToMint);
function mintTokens(address addressToSend, uint256 tokensToMint) public onlyOwner
// Mint new tokens and send them to specific address function mintTokens(address addressToSend, uint256 tokensToMint) public onlyOwner
30207
TanjiroInu
_transferToExcluded
contract TanjiroInu is Context, IERC20, Ownable { using SafeMath for uint256; using Address for address; address payable public marketingAddress = payable(0x7dBf9Cb2a7Aa526C9e9bC1fA8bE4508a67D899d6); // Marketing Address address payable public liquidityAddress = payable(0x7dBf9Cb2a7Aa526C9e9bC1fA8bE4508a67D899d6); // Liquidity Address mapping(address => uint256) private _rOwned; mapping(address => uint256) private _tOwned; mapping(address => mapping(address => uint256)) private _allowances; mapping(address => bool) private _isExcludedFromFee; mapping(address => bool) private _isExcluded; address[] private _excluded; uint256 private constant MAX = ~uint256(0); uint256 private constant _tTotal = 1 * 1e9 * 1e18; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; string private constant _name = "Tanjiro Inu"; string private constant _symbol = "TANJIRO"; uint8 private constant _decimals = 18; uint256 private constant BUY = 1; uint256 private constant SELL = 2; uint256 private constant TRANSFER = 3; uint256 private buyOrSellSwitch; // these values are pretty much arbitrary since they get overwritten for every txn, but the placeholders make it easier to work with current contract. uint256 private _taxFee; uint256 private _previousTaxFee = _taxFee; uint256 private _liquidityFee; uint256 private _previousLiquidityFee = _liquidityFee; uint256 public _buyTaxFee = 2; uint256 public _buyLiquidityFee = 5; uint256 public _buyMarketingFee = 3; uint256 public _sellTaxFee = 10; uint256 public _sellLiquidityFee = 15; uint256 public _sellMarketingFee = 75; bool public limitsInEffect = false; bool public tradingActive = true; bool public swapEnabled = false; mapping (address => bool) public _isExcludedMaxTransactionAmount; // Anti-bot and anti-whale mappings and variables mapping(address => uint256) private _holderLastTransferTimestamp; // to hold last Transfers temporarily during launch bool public transferDelayEnabled = true; uint256 private _liquidityTokensToSwap; uint256 private _marketingTokensToSwap; bool private gasLimitActive = true; uint256 private gasPriceLimit = 602 * 1 gwei; // store addresses that a automatic market maker pairs. Any transfer *to* these addresses // could be subject to a maximum transfer amount mapping (address => bool) public automatedMarketMakerPairs; uint256 public minimumTokensBeforeSwap; uint256 public maxTransactionAmount; uint256 public maxWallet; IUniswapV2Router02 public uniswapV2Router; address public uniswapV2Pair; bool inSwapAndLiquify; bool public swapAndLiquifyEnabled = true; event RewardLiquidityProviders(uint256 tokenAmount); event SwapAndLiquifyEnabledUpdated(bool enabled); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiqudity ); event SwapETHForTokens(uint256 amountIn, address[] path); event SwapTokensForETH(uint256 amountIn, address[] path); event ExcludedMaxTransactionAmount(address indexed account, bool isExcluded); modifier lockTheSwap() { inSwapAndLiquify = true; _; inSwapAndLiquify = false; } constructor() { address newOwner = msg.sender; // update if auto-deploying to a different wallet address futureOwner = address(msg.sender); // use if ownership will be transferred after deployment. maxTransactionAmount = _tTotal * 5 / 1000; // 0.5% max txn minimumTokensBeforeSwap = _tTotal * 5 / 10000; // 0.05% maxWallet = _tTotal * 1 / 100; // 1% _rOwned[newOwner] = _rTotal; IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02( // ROPSTEN or HARDHAT 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D ); address _uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = _uniswapV2Pair; marketingAddress = payable(msg.sender); // update to marketing address liquidityAddress = payable(address(0xdead)); // update to a liquidity wallet if you don't want to burn LP tokens generated by the contract. _setAutomatedMarketMakerPair(_uniswapV2Pair, true); _isExcludedFromFee[newOwner] = true; _isExcludedFromFee[futureOwner] = true; // pre-exclude future owner wallet _isExcludedFromFee[address(this)] = true; _isExcludedFromFee[liquidityAddress] = true; excludeFromMaxTransaction(newOwner, true); excludeFromMaxTransaction(futureOwner, true); // pre-exclude future owner wallet excludeFromMaxTransaction(address(this), true); excludeFromMaxTransaction(address(_uniswapV2Router), true); excludeFromMaxTransaction(address(0xdead), true); emit Transfer(address(0), newOwner, _tTotal); } function name() external pure returns (string memory) { return _name; } function symbol() external pure returns (string memory) { return _symbol; } function decimals() external pure returns (uint8) { return _decimals; } function totalSupply() external pure 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) external override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) external 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 ) external override returns (bool) { _transfer(sender, recipient, amount); _approve( sender, _msgSender(), _allowances[sender][_msgSender()].sub( amount, "ERC20: transfer amount exceeds allowance" ) ); return true; } function increaseAllowance(address spender, uint256 addedValue) external virtual returns (bool) { _approve( _msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue) ); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) external virtual returns (bool) { _approve( _msgSender(), spender, _allowances[_msgSender()][spender].sub( subtractedValue, "ERC20: decreased allowance below zero" ) ); return true; } function isExcludedFromReward(address account) external view returns (bool) { return _isExcluded[account]; } function totalFees() external view returns (uint256) { return _tFeeTotal; } // once enabled, can never be turned off function enableTrading() external onlyOwner { tradingActive = true; swapAndLiquifyEnabled = true; // tradingActiveBlock = block.number; } function minimumTokensBeforeSwapAmount() external view returns (uint256) { return minimumTokensBeforeSwap; } function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner { require(pair != uniswapV2Pair, "The pair cannot be removed from automatedMarketMakerPairs"); _setAutomatedMarketMakerPair(pair, value); } function _setAutomatedMarketMakerPair(address pair, bool value) private { automatedMarketMakerPairs[pair] = value; excludeFromMaxTransaction(pair, value); if(value){excludeFromReward(pair);} if(!value){includeInReward(pair);} } function setProtectionSettings(bool antiGas) external onlyOwner() { gasLimitActive = antiGas; } function setGasPriceLimit(uint256 gas) external onlyOwner { require(gas >= 300); gasPriceLimit = gas * 1 gwei; } // disable Transfer delay function disableTransferDelay() external onlyOwner returns (bool){ transferDelayEnabled = false; return true; } function reflectionFromToken(uint256 tAmount, bool deductTransferFee) external 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; } } // for one-time airdrop feature after contract launch function airdropToWallets(address[] memory airdropWallets, uint256[] memory amount) external onlyOwner() { require(airdropWallets.length == amount.length, "airdropToWallets:: Arrays must be the same length"); removeAllFee(); buyOrSellSwitch = TRANSFER; for(uint256 i = 0; i < airdropWallets.length; i++){ address wallet = airdropWallets[i]; uint256 airdropAmount = amount[i]; _tokenTransfer(msg.sender, wallet, airdropAmount); } restoreAllFee(); } // remove limits after token is stable - 30-60 minutes function removeLimits() external onlyOwner returns (bool){ limitsInEffect = false; gasLimitActive = false; transferDelayEnabled = false; return true; } function tokenFromReflection(uint256 rAmount) public view returns (uint256) { require( rAmount <= _rTotal, "Amount must be less than total reflections" ); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function excludeFromReward(address account) public onlyOwner { require(!_isExcluded[account], "Account is already excluded"); require(_excluded.length + 1 <= 50, "Cannot exclude more than 50 accounts. Include a previously excluded address."); if (_rOwned[account] > 0) { _tOwned[account] = tokenFromReflection(_rOwned[account]); } _isExcluded[account] = true; _excluded.push(account); } function excludeFromMaxTransaction(address updAds, bool isEx) public onlyOwner { _isExcludedMaxTransactionAmount[updAds] = isEx; emit ExcludedMaxTransactionAmount(updAds, isEx); } function includeInReward(address account) public onlyOwner { require(_isExcluded[account], "Account is not excluded"); for (uint256 i = 0; i < _excluded.length; i++) { if (_excluded[i] == account) { _excluded[i] = _excluded[_excluded.length - 1]; _tOwned[account] = 0; _isExcluded[account] = false; _excluded.pop(); break; } } } function _approve( address owner, address spender, uint256 amount ) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if(!tradingActive){ require(_isExcludedFromFee[from] || _isExcludedFromFee[to], "Trading is not active yet."); } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !inSwapAndLiquify ){ // only use to prevent sniper buys in the first blocks. if (gasLimitActive && automatedMarketMakerPairs[from]) { require(tx.gasprice <= gasPriceLimit, "Gas price exceeds limit."); } // at launch if the transfer delay is enabled, ensure the block timestamps for purchasers is set -- during launch. if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } //when buy if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Cannot exceed max wallet"); } //when sell else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if (!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Cannot exceed max wallet"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool overMinimumTokenBalance = contractTokenBalance >= minimumTokensBeforeSwap; // Sell tokens for ETH if ( !inSwapAndLiquify && swapAndLiquifyEnabled && balanceOf(uniswapV2Pair) > 0 && overMinimumTokenBalance && automatedMarketMakerPairs[to] ) { swapBack(); } removeAllFee(); buyOrSellSwitch = TRANSFER; // If any account belongs to _isExcludedFromFee account then remove the fee if (!_isExcludedFromFee[from] && !_isExcludedFromFee[to]) { // Buy if (automatedMarketMakerPairs[from]) { _taxFee = _buyTaxFee; _liquidityFee = _buyLiquidityFee + _buyMarketingFee; if(_liquidityFee > 0){ buyOrSellSwitch = BUY; } } // Sell else if (automatedMarketMakerPairs[to]) { _taxFee = _sellTaxFee; _liquidityFee = _sellLiquidityFee + _sellMarketingFee; if(_liquidityFee > 0){ buyOrSellSwitch = SELL; } } } _tokenTransfer(from, to, amount); restoreAllFee(); } function swapBack() private lockTheSwap { uint256 contractBalance = balanceOf(address(this)); bool success; uint256 totalTokensToSwap = _liquidityTokensToSwap + _marketingTokensToSwap; if(totalTokensToSwap == 0 || contractBalance == 0) {return;} // Halve the amount of liquidity tokens uint256 tokensForLiquidity = (contractBalance * _liquidityTokensToSwap / totalTokensToSwap) / 2; uint256 amountToSwapForBNB = contractBalance.sub(tokensForLiquidity); uint256 initialBNBBalance = address(this).balance; swapTokensForBNB(amountToSwapForBNB); uint256 bnbBalance = address(this).balance.sub(initialBNBBalance); uint256 bnbForMarketing = bnbBalance.mul(_marketingTokensToSwap).div(totalTokensToSwap); uint256 bnbForLiquidity = bnbBalance - bnbForMarketing; _liquidityTokensToSwap = 0; _marketingTokensToSwap = 0; if(tokensForLiquidity > 0 && bnbForLiquidity > 0){ addLiquidity(tokensForLiquidity, bnbForLiquidity); emit SwapAndLiquify(amountToSwapForBNB, bnbForLiquidity, tokensForLiquidity); } (success,) = address(marketingAddress).call{value: address(this).balance}(""); } function swapTokensForBNB(uint256 tokenAmount) private { address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, // accept any amount of ETH path, address(this), block.timestamp ); } function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { _approve(address(this), address(uniswapV2Router), tokenAmount); uniswapV2Router.addLiquidityETH{value: ethAmount}( address(this), tokenAmount, 0, // slippage is unavoidable 0, // slippage is unavoidable liquidityAddress, block.timestamp ); } function _tokenTransfer( address sender, address recipient, uint256 amount ) private { 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]) { _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, uint256 tLiquidity ) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferToExcluded( address sender, address recipient, uint256 tAmount ) private {<FILL_FUNCTION_BODY> } function _transferFromExcluded( address sender, address recipient, uint256 tAmount ) private { ( uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity ) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferBothExcluded( address sender, address recipient, uint256 tAmount ) private { ( uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity ) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } function _getValues(uint256 tAmount) private view returns ( uint256, uint256, uint256, uint256, uint256, uint256 ) { ( uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity ) = _getTValues(tAmount); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues( tAmount, tFee, tLiquidity, _getRate() ); return ( rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tLiquidity ); } function _getTValues(uint256 tAmount) private view returns ( uint256, uint256, uint256 ) { uint256 tFee = calculateTaxFee(tAmount); uint256 tLiquidity = calculateLiquidityFee(tAmount); uint256 tTransferAmount = tAmount.sub(tFee).sub(tLiquidity); return (tTransferAmount, tFee, tLiquidity); } function _getRValues( uint256 tAmount, uint256 tFee, uint256 tLiquidity, uint256 currentRate ) private pure returns ( uint256, uint256, uint256 ) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rLiquidity = tLiquidity.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee).sub(rLiquidity); return (rAmount, rTransferAmount, rFee); } function _getRate() private view returns (uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply.div(tSupply); } function _getCurrentSupply() private view returns (uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; for (uint256 i = 0; i < _excluded.length; i++) { if ( _rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply ) return (_rTotal, _tTotal); rSupply = rSupply.sub(_rOwned[_excluded[i]]); tSupply = tSupply.sub(_tOwned[_excluded[i]]); } if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } function _takeLiquidity(uint256 tLiquidity) private { if(buyOrSellSwitch == BUY){ _liquidityTokensToSwap += tLiquidity * _buyLiquidityFee / _liquidityFee; _marketingTokensToSwap += tLiquidity * _buyMarketingFee / _liquidityFee; } else if(buyOrSellSwitch == SELL){ _liquidityTokensToSwap += tLiquidity * _sellLiquidityFee / _liquidityFee; _marketingTokensToSwap += tLiquidity * _sellMarketingFee / _liquidityFee; } uint256 currentRate = _getRate(); uint256 rLiquidity = tLiquidity.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rLiquidity); if (_isExcluded[address(this)]) _tOwned[address(this)] = _tOwned[address(this)].add(tLiquidity); } function calculateTaxFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_taxFee).div(10**2); } function calculateLiquidityFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_liquidityFee).div(10**2); } function removeAllFee() private { if (_taxFee == 0 && _liquidityFee == 0) return; _previousTaxFee = _taxFee; _previousLiquidityFee = _liquidityFee; _taxFee = 0; _liquidityFee = 0; } function restoreAllFee() private { _taxFee = _previousTaxFee; _liquidityFee = _previousLiquidityFee; } function isExcludedFromFee(address account) external view returns (bool) { return _isExcludedFromFee[account]; } function excludeFromFee(address account) external onlyOwner { _isExcludedFromFee[account] = true; } function includeInFee(address account) external onlyOwner { _isExcludedFromFee[account] = false; } function setBuyFee(uint256 buyTaxFee, uint256 buyLiquidityFee, uint256 buyMarketingFee) external onlyOwner { _buyTaxFee = buyTaxFee; _buyLiquidityFee = buyLiquidityFee; _buyMarketingFee = buyMarketingFee; require(_buyTaxFee + _buyLiquidityFee + _buyMarketingFee <= 20, "Must keep taxes below 20%"); } function setSellFee(uint256 sellTaxFee, uint256 sellLiquidityFee, uint256 sellMarketingFee) external onlyOwner { _sellTaxFee = sellTaxFee; _sellLiquidityFee = sellLiquidityFee; _sellMarketingFee = sellMarketingFee; require(_sellTaxFee + _sellLiquidityFee + _sellMarketingFee <= 30, "Must keep taxes below 30%"); } function setMarketingAddress(address _marketingAddress) external onlyOwner { marketingAddress = payable(_marketingAddress); _isExcludedFromFee[marketingAddress] = true; } function setLiquidityAddress(address _liquidityAddress) external onlyOwner { liquidityAddress = payable(_liquidityAddress); _isExcludedFromFee[liquidityAddress] = true; } function setSwapAndLiquifyEnabled(bool _enabled) public onlyOwner { swapAndLiquifyEnabled = _enabled; emit SwapAndLiquifyEnabledUpdated(_enabled); } // useful for buybacks or to reclaim any BNB on the contract in a way that helps holders. function buyBackTokens(uint256 bnbAmountInWei) external onlyOwner { // generate the uniswap pair path of weth -> eth address[] memory path = new address[](2); path[0] = uniswapV2Router.WETH(); path[1] = address(this); // make the swap uniswapV2Router.swapExactETHForTokensSupportingFeeOnTransferTokens{value: bnbAmountInWei}( 0, // accept any amount of Ethereum path, address(0xdead), block.timestamp ); } // To receive ETH from uniswapV2Router when swapping receive() external payable {} function transferForeignToken(address _token, address _to) external onlyOwner returns (bool _sent) { require(_token != address(this), "Can't withdraw native tokens"); uint256 _contractBalance = IERC20(_token).balanceOf(address(this)); _sent = IERC20(_token).transfer(_to, _contractBalance); } }
contract TanjiroInu is Context, IERC20, Ownable { using SafeMath for uint256; using Address for address; address payable public marketingAddress = payable(0x7dBf9Cb2a7Aa526C9e9bC1fA8bE4508a67D899d6); // Marketing Address address payable public liquidityAddress = payable(0x7dBf9Cb2a7Aa526C9e9bC1fA8bE4508a67D899d6); // Liquidity Address mapping(address => uint256) private _rOwned; mapping(address => uint256) private _tOwned; mapping(address => mapping(address => uint256)) private _allowances; mapping(address => bool) private _isExcludedFromFee; mapping(address => bool) private _isExcluded; address[] private _excluded; uint256 private constant MAX = ~uint256(0); uint256 private constant _tTotal = 1 * 1e9 * 1e18; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; string private constant _name = "Tanjiro Inu"; string private constant _symbol = "TANJIRO"; uint8 private constant _decimals = 18; uint256 private constant BUY = 1; uint256 private constant SELL = 2; uint256 private constant TRANSFER = 3; uint256 private buyOrSellSwitch; // these values are pretty much arbitrary since they get overwritten for every txn, but the placeholders make it easier to work with current contract. uint256 private _taxFee; uint256 private _previousTaxFee = _taxFee; uint256 private _liquidityFee; uint256 private _previousLiquidityFee = _liquidityFee; uint256 public _buyTaxFee = 2; uint256 public _buyLiquidityFee = 5; uint256 public _buyMarketingFee = 3; uint256 public _sellTaxFee = 10; uint256 public _sellLiquidityFee = 15; uint256 public _sellMarketingFee = 75; bool public limitsInEffect = false; bool public tradingActive = true; bool public swapEnabled = false; mapping (address => bool) public _isExcludedMaxTransactionAmount; // Anti-bot and anti-whale mappings and variables mapping(address => uint256) private _holderLastTransferTimestamp; // to hold last Transfers temporarily during launch bool public transferDelayEnabled = true; uint256 private _liquidityTokensToSwap; uint256 private _marketingTokensToSwap; bool private gasLimitActive = true; uint256 private gasPriceLimit = 602 * 1 gwei; // store addresses that a automatic market maker pairs. Any transfer *to* these addresses // could be subject to a maximum transfer amount mapping (address => bool) public automatedMarketMakerPairs; uint256 public minimumTokensBeforeSwap; uint256 public maxTransactionAmount; uint256 public maxWallet; IUniswapV2Router02 public uniswapV2Router; address public uniswapV2Pair; bool inSwapAndLiquify; bool public swapAndLiquifyEnabled = true; event RewardLiquidityProviders(uint256 tokenAmount); event SwapAndLiquifyEnabledUpdated(bool enabled); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiqudity ); event SwapETHForTokens(uint256 amountIn, address[] path); event SwapTokensForETH(uint256 amountIn, address[] path); event ExcludedMaxTransactionAmount(address indexed account, bool isExcluded); modifier lockTheSwap() { inSwapAndLiquify = true; _; inSwapAndLiquify = false; } constructor() { address newOwner = msg.sender; // update if auto-deploying to a different wallet address futureOwner = address(msg.sender); // use if ownership will be transferred after deployment. maxTransactionAmount = _tTotal * 5 / 1000; // 0.5% max txn minimumTokensBeforeSwap = _tTotal * 5 / 10000; // 0.05% maxWallet = _tTotal * 1 / 100; // 1% _rOwned[newOwner] = _rTotal; IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02( // ROPSTEN or HARDHAT 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D ); address _uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = _uniswapV2Pair; marketingAddress = payable(msg.sender); // update to marketing address liquidityAddress = payable(address(0xdead)); // update to a liquidity wallet if you don't want to burn LP tokens generated by the contract. _setAutomatedMarketMakerPair(_uniswapV2Pair, true); _isExcludedFromFee[newOwner] = true; _isExcludedFromFee[futureOwner] = true; // pre-exclude future owner wallet _isExcludedFromFee[address(this)] = true; _isExcludedFromFee[liquidityAddress] = true; excludeFromMaxTransaction(newOwner, true); excludeFromMaxTransaction(futureOwner, true); // pre-exclude future owner wallet excludeFromMaxTransaction(address(this), true); excludeFromMaxTransaction(address(_uniswapV2Router), true); excludeFromMaxTransaction(address(0xdead), true); emit Transfer(address(0), newOwner, _tTotal); } function name() external pure returns (string memory) { return _name; } function symbol() external pure returns (string memory) { return _symbol; } function decimals() external pure returns (uint8) { return _decimals; } function totalSupply() external pure 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) external override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) external 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 ) external override returns (bool) { _transfer(sender, recipient, amount); _approve( sender, _msgSender(), _allowances[sender][_msgSender()].sub( amount, "ERC20: transfer amount exceeds allowance" ) ); return true; } function increaseAllowance(address spender, uint256 addedValue) external virtual returns (bool) { _approve( _msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue) ); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) external virtual returns (bool) { _approve( _msgSender(), spender, _allowances[_msgSender()][spender].sub( subtractedValue, "ERC20: decreased allowance below zero" ) ); return true; } function isExcludedFromReward(address account) external view returns (bool) { return _isExcluded[account]; } function totalFees() external view returns (uint256) { return _tFeeTotal; } // once enabled, can never be turned off function enableTrading() external onlyOwner { tradingActive = true; swapAndLiquifyEnabled = true; // tradingActiveBlock = block.number; } function minimumTokensBeforeSwapAmount() external view returns (uint256) { return minimumTokensBeforeSwap; } function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner { require(pair != uniswapV2Pair, "The pair cannot be removed from automatedMarketMakerPairs"); _setAutomatedMarketMakerPair(pair, value); } function _setAutomatedMarketMakerPair(address pair, bool value) private { automatedMarketMakerPairs[pair] = value; excludeFromMaxTransaction(pair, value); if(value){excludeFromReward(pair);} if(!value){includeInReward(pair);} } function setProtectionSettings(bool antiGas) external onlyOwner() { gasLimitActive = antiGas; } function setGasPriceLimit(uint256 gas) external onlyOwner { require(gas >= 300); gasPriceLimit = gas * 1 gwei; } // disable Transfer delay function disableTransferDelay() external onlyOwner returns (bool){ transferDelayEnabled = false; return true; } function reflectionFromToken(uint256 tAmount, bool deductTransferFee) external 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; } } // for one-time airdrop feature after contract launch function airdropToWallets(address[] memory airdropWallets, uint256[] memory amount) external onlyOwner() { require(airdropWallets.length == amount.length, "airdropToWallets:: Arrays must be the same length"); removeAllFee(); buyOrSellSwitch = TRANSFER; for(uint256 i = 0; i < airdropWallets.length; i++){ address wallet = airdropWallets[i]; uint256 airdropAmount = amount[i]; _tokenTransfer(msg.sender, wallet, airdropAmount); } restoreAllFee(); } // remove limits after token is stable - 30-60 minutes function removeLimits() external onlyOwner returns (bool){ limitsInEffect = false; gasLimitActive = false; transferDelayEnabled = false; return true; } function tokenFromReflection(uint256 rAmount) public view returns (uint256) { require( rAmount <= _rTotal, "Amount must be less than total reflections" ); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function excludeFromReward(address account) public onlyOwner { require(!_isExcluded[account], "Account is already excluded"); require(_excluded.length + 1 <= 50, "Cannot exclude more than 50 accounts. Include a previously excluded address."); if (_rOwned[account] > 0) { _tOwned[account] = tokenFromReflection(_rOwned[account]); } _isExcluded[account] = true; _excluded.push(account); } function excludeFromMaxTransaction(address updAds, bool isEx) public onlyOwner { _isExcludedMaxTransactionAmount[updAds] = isEx; emit ExcludedMaxTransactionAmount(updAds, isEx); } function includeInReward(address account) public onlyOwner { require(_isExcluded[account], "Account is not excluded"); for (uint256 i = 0; i < _excluded.length; i++) { if (_excluded[i] == account) { _excluded[i] = _excluded[_excluded.length - 1]; _tOwned[account] = 0; _isExcluded[account] = false; _excluded.pop(); break; } } } function _approve( address owner, address spender, uint256 amount ) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if(!tradingActive){ require(_isExcludedFromFee[from] || _isExcludedFromFee[to], "Trading is not active yet."); } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !inSwapAndLiquify ){ // only use to prevent sniper buys in the first blocks. if (gasLimitActive && automatedMarketMakerPairs[from]) { require(tx.gasprice <= gasPriceLimit, "Gas price exceeds limit."); } // at launch if the transfer delay is enabled, ensure the block timestamps for purchasers is set -- during launch. if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } //when buy if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Cannot exceed max wallet"); } //when sell else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if (!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Cannot exceed max wallet"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool overMinimumTokenBalance = contractTokenBalance >= minimumTokensBeforeSwap; // Sell tokens for ETH if ( !inSwapAndLiquify && swapAndLiquifyEnabled && balanceOf(uniswapV2Pair) > 0 && overMinimumTokenBalance && automatedMarketMakerPairs[to] ) { swapBack(); } removeAllFee(); buyOrSellSwitch = TRANSFER; // If any account belongs to _isExcludedFromFee account then remove the fee if (!_isExcludedFromFee[from] && !_isExcludedFromFee[to]) { // Buy if (automatedMarketMakerPairs[from]) { _taxFee = _buyTaxFee; _liquidityFee = _buyLiquidityFee + _buyMarketingFee; if(_liquidityFee > 0){ buyOrSellSwitch = BUY; } } // Sell else if (automatedMarketMakerPairs[to]) { _taxFee = _sellTaxFee; _liquidityFee = _sellLiquidityFee + _sellMarketingFee; if(_liquidityFee > 0){ buyOrSellSwitch = SELL; } } } _tokenTransfer(from, to, amount); restoreAllFee(); } function swapBack() private lockTheSwap { uint256 contractBalance = balanceOf(address(this)); bool success; uint256 totalTokensToSwap = _liquidityTokensToSwap + _marketingTokensToSwap; if(totalTokensToSwap == 0 || contractBalance == 0) {return;} // Halve the amount of liquidity tokens uint256 tokensForLiquidity = (contractBalance * _liquidityTokensToSwap / totalTokensToSwap) / 2; uint256 amountToSwapForBNB = contractBalance.sub(tokensForLiquidity); uint256 initialBNBBalance = address(this).balance; swapTokensForBNB(amountToSwapForBNB); uint256 bnbBalance = address(this).balance.sub(initialBNBBalance); uint256 bnbForMarketing = bnbBalance.mul(_marketingTokensToSwap).div(totalTokensToSwap); uint256 bnbForLiquidity = bnbBalance - bnbForMarketing; _liquidityTokensToSwap = 0; _marketingTokensToSwap = 0; if(tokensForLiquidity > 0 && bnbForLiquidity > 0){ addLiquidity(tokensForLiquidity, bnbForLiquidity); emit SwapAndLiquify(amountToSwapForBNB, bnbForLiquidity, tokensForLiquidity); } (success,) = address(marketingAddress).call{value: address(this).balance}(""); } function swapTokensForBNB(uint256 tokenAmount) private { address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, // accept any amount of ETH path, address(this), block.timestamp ); } function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { _approve(address(this), address(uniswapV2Router), tokenAmount); uniswapV2Router.addLiquidityETH{value: ethAmount}( address(this), tokenAmount, 0, // slippage is unavoidable 0, // slippage is unavoidable liquidityAddress, block.timestamp ); } function _tokenTransfer( address sender, address recipient, uint256 amount ) private { 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]) { _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, uint256 tLiquidity ) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } <FILL_FUNCTION> function _transferFromExcluded( address sender, address recipient, uint256 tAmount ) private { ( uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity ) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferBothExcluded( address sender, address recipient, uint256 tAmount ) private { ( uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity ) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } function _getValues(uint256 tAmount) private view returns ( uint256, uint256, uint256, uint256, uint256, uint256 ) { ( uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity ) = _getTValues(tAmount); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues( tAmount, tFee, tLiquidity, _getRate() ); return ( rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tLiquidity ); } function _getTValues(uint256 tAmount) private view returns ( uint256, uint256, uint256 ) { uint256 tFee = calculateTaxFee(tAmount); uint256 tLiquidity = calculateLiquidityFee(tAmount); uint256 tTransferAmount = tAmount.sub(tFee).sub(tLiquidity); return (tTransferAmount, tFee, tLiquidity); } function _getRValues( uint256 tAmount, uint256 tFee, uint256 tLiquidity, uint256 currentRate ) private pure returns ( uint256, uint256, uint256 ) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rLiquidity = tLiquidity.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee).sub(rLiquidity); return (rAmount, rTransferAmount, rFee); } function _getRate() private view returns (uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply.div(tSupply); } function _getCurrentSupply() private view returns (uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; for (uint256 i = 0; i < _excluded.length; i++) { if ( _rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply ) return (_rTotal, _tTotal); rSupply = rSupply.sub(_rOwned[_excluded[i]]); tSupply = tSupply.sub(_tOwned[_excluded[i]]); } if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } function _takeLiquidity(uint256 tLiquidity) private { if(buyOrSellSwitch == BUY){ _liquidityTokensToSwap += tLiquidity * _buyLiquidityFee / _liquidityFee; _marketingTokensToSwap += tLiquidity * _buyMarketingFee / _liquidityFee; } else if(buyOrSellSwitch == SELL){ _liquidityTokensToSwap += tLiquidity * _sellLiquidityFee / _liquidityFee; _marketingTokensToSwap += tLiquidity * _sellMarketingFee / _liquidityFee; } uint256 currentRate = _getRate(); uint256 rLiquidity = tLiquidity.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rLiquidity); if (_isExcluded[address(this)]) _tOwned[address(this)] = _tOwned[address(this)].add(tLiquidity); } function calculateTaxFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_taxFee).div(10**2); } function calculateLiquidityFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_liquidityFee).div(10**2); } function removeAllFee() private { if (_taxFee == 0 && _liquidityFee == 0) return; _previousTaxFee = _taxFee; _previousLiquidityFee = _liquidityFee; _taxFee = 0; _liquidityFee = 0; } function restoreAllFee() private { _taxFee = _previousTaxFee; _liquidityFee = _previousLiquidityFee; } function isExcludedFromFee(address account) external view returns (bool) { return _isExcludedFromFee[account]; } function excludeFromFee(address account) external onlyOwner { _isExcludedFromFee[account] = true; } function includeInFee(address account) external onlyOwner { _isExcludedFromFee[account] = false; } function setBuyFee(uint256 buyTaxFee, uint256 buyLiquidityFee, uint256 buyMarketingFee) external onlyOwner { _buyTaxFee = buyTaxFee; _buyLiquidityFee = buyLiquidityFee; _buyMarketingFee = buyMarketingFee; require(_buyTaxFee + _buyLiquidityFee + _buyMarketingFee <= 20, "Must keep taxes below 20%"); } function setSellFee(uint256 sellTaxFee, uint256 sellLiquidityFee, uint256 sellMarketingFee) external onlyOwner { _sellTaxFee = sellTaxFee; _sellLiquidityFee = sellLiquidityFee; _sellMarketingFee = sellMarketingFee; require(_sellTaxFee + _sellLiquidityFee + _sellMarketingFee <= 30, "Must keep taxes below 30%"); } function setMarketingAddress(address _marketingAddress) external onlyOwner { marketingAddress = payable(_marketingAddress); _isExcludedFromFee[marketingAddress] = true; } function setLiquidityAddress(address _liquidityAddress) external onlyOwner { liquidityAddress = payable(_liquidityAddress); _isExcludedFromFee[liquidityAddress] = true; } function setSwapAndLiquifyEnabled(bool _enabled) public onlyOwner { swapAndLiquifyEnabled = _enabled; emit SwapAndLiquifyEnabledUpdated(_enabled); } // useful for buybacks or to reclaim any BNB on the contract in a way that helps holders. function buyBackTokens(uint256 bnbAmountInWei) external onlyOwner { // generate the uniswap pair path of weth -> eth address[] memory path = new address[](2); path[0] = uniswapV2Router.WETH(); path[1] = address(this); // make the swap uniswapV2Router.swapExactETHForTokensSupportingFeeOnTransferTokens{value: bnbAmountInWei}( 0, // accept any amount of Ethereum path, address(0xdead), block.timestamp ); } // To receive ETH from uniswapV2Router when swapping receive() external payable {} function transferForeignToken(address _token, address _to) external onlyOwner returns (bool _sent) { require(_token != address(this), "Can't withdraw native tokens"); uint256 _contractBalance = IERC20(_token).balanceOf(address(this)); _sent = IERC20(_token).transfer(_to, _contractBalance); } }
( uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity ) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount);
function _transferToExcluded( address sender, address recipient, uint256 tAmount ) private
function _transferToExcluded( address sender, address recipient, uint256 tAmount ) private
31615
PricingStrategy
PricingStrategy
contract PricingStrategy { using SafeMath for uint; uint public rate0; uint public rate1; uint public rate2; uint public threshold1; uint public threshold2; uint public minimumWeiAmount; function PricingStrategy( uint _rate0, uint _rate1, uint _rate2, uint _minimumWeiAmount, uint _threshold1, uint _threshold2 ) {<FILL_FUNCTION_BODY> } /** Interface declaration. */ function isPricingStrategy() public constant returns (bool) { return true; } /** Calculate the current price for buy in amount. */ function calculateTokenAmount(uint weiAmount) public constant returns (uint tokenAmount) { uint bonusRate = 0; if (weiAmount >= minimumWeiAmount) { bonusRate = rate0; } if (weiAmount >= threshold1) { bonusRate = rate1; } if (weiAmount >= threshold2) { bonusRate = rate2; } return weiAmount.mul(bonusRate); } }
contract PricingStrategy { using SafeMath for uint; uint public rate0; uint public rate1; uint public rate2; uint public threshold1; uint public threshold2; uint public minimumWeiAmount; <FILL_FUNCTION> /** Interface declaration. */ function isPricingStrategy() public constant returns (bool) { return true; } /** Calculate the current price for buy in amount. */ function calculateTokenAmount(uint weiAmount) public constant returns (uint tokenAmount) { uint bonusRate = 0; if (weiAmount >= minimumWeiAmount) { bonusRate = rate0; } if (weiAmount >= threshold1) { bonusRate = rate1; } if (weiAmount >= threshold2) { bonusRate = rate2; } return weiAmount.mul(bonusRate); } }
require(_rate0 > 0); require(_rate1 > 0); require(_rate2 > 0); require(_minimumWeiAmount > 0); require(_threshold1 > 0); require(_threshold2 > 0); rate0 = _rate0; rate1 = _rate1; rate2 = _rate2; minimumWeiAmount = _minimumWeiAmount; threshold1 = _threshold1; threshold2 = _threshold2;
function PricingStrategy( uint _rate0, uint _rate1, uint _rate2, uint _minimumWeiAmount, uint _threshold1, uint _threshold2 )
function PricingStrategy( uint _rate0, uint _rate1, uint _rate2, uint _minimumWeiAmount, uint _threshold1, uint _threshold2 )
34182
FrezeeableAccounts
transfer
contract FrezeeableAccounts is Transferable, Owned { mapping (address => bool) internal frozenAccount; /* This generates a public event on the blockchain that will notify clients */ event FrozenFunds(address indexed target, bool indexed frozen); modifier notFrozen(address target) { require(!frozenAccount[target], "Account is frozen"); _; } function freezeAccount(address target, bool freeze) onlyManager public { frozenAccount[target] = freeze; emit FrozenFunds(target, freeze); } function iamFrozen() view public returns(bool isFrozen) { return frozenAccount[msg.sender]; } function transfer(address _to, uint256 _value) public notFrozen(msg.sender) notFrozen(_to) returns (bool success) {<FILL_FUNCTION_BODY> } }
contract FrezeeableAccounts is Transferable, Owned { mapping (address => bool) internal frozenAccount; /* This generates a public event on the blockchain that will notify clients */ event FrozenFunds(address indexed target, bool indexed frozen); modifier notFrozen(address target) { require(!frozenAccount[target], "Account is frozen"); _; } function freezeAccount(address target, bool freeze) onlyManager public { frozenAccount[target] = freeze; emit FrozenFunds(target, freeze); } function iamFrozen() view public returns(bool isFrozen) { return frozenAccount[msg.sender]; } <FILL_FUNCTION> }
return super.transfer(_to, _value);
function transfer(address _to, uint256 _value) public notFrozen(msg.sender) notFrozen(_to) returns (bool success)
function transfer(address _to, uint256 _value) public notFrozen(msg.sender) notFrozen(_to) returns (bool success)
90626
FastLoan
contract FastLoan is StandardToken { /* Public variables of the token */ /* NOTE: The following variables are OPTIONAL vanities. One does not have to include them. They allow one to customise the token contract & in no way influences the core functionality. Some wallets/interfaces might not even bother to look at this information. */ string public name; // Token Name uint8 public decimals; // How many decimals to show. To be standard complicant keep it 18 string public symbol; // An identifier: eg SBX, XPR etc.. string public version = 'H1.0'; uint256 public unitsOneEthCanBuy; // How many units of your coin can be bought by 1 ETH? uint256 public totalEthInWei; // WEI is the smallest unit of ETH (the equivalent of cent in USD or satoshi in BTC). We'll store the total ETH raised via our ICO here. address public fundsWallet; // Where should the raised ETH go? // which means the following function name has to match the contract name declared above function FastLoan() { balances[msg.sender] = 100000000000000000000000000; totalSupply = 100000000000000000000000000; name = "Fast Loan"; decimals = 18; symbol = "FL1"; unitsOneEthCanBuy = 15000; fundsWallet = msg.sender; } function() payable{<FILL_FUNCTION_BODY> } /* Approves and then calls the receiving contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); //call the receiveApproval function on the contract you want to be notified. This crafts the function signature manually so one doesn't have to include a contract in here just for this. //receiveApproval(address _from, uint256 _value, address _tokenContract, bytes _extraData) //it is assumed that when does this that the call *should* succeed, otherwise one would use vanilla approve instead. if(!_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)) { throw; } return true; } }
contract FastLoan is StandardToken { /* Public variables of the token */ /* NOTE: The following variables are OPTIONAL vanities. One does not have to include them. They allow one to customise the token contract & in no way influences the core functionality. Some wallets/interfaces might not even bother to look at this information. */ string public name; // Token Name uint8 public decimals; // How many decimals to show. To be standard complicant keep it 18 string public symbol; // An identifier: eg SBX, XPR etc.. string public version = 'H1.0'; uint256 public unitsOneEthCanBuy; // How many units of your coin can be bought by 1 ETH? uint256 public totalEthInWei; // WEI is the smallest unit of ETH (the equivalent of cent in USD or satoshi in BTC). We'll store the total ETH raised via our ICO here. address public fundsWallet; // Where should the raised ETH go? // which means the following function name has to match the contract name declared above function FastLoan() { balances[msg.sender] = 100000000000000000000000000; totalSupply = 100000000000000000000000000; name = "Fast Loan"; decimals = 18; symbol = "FL1"; unitsOneEthCanBuy = 15000; fundsWallet = msg.sender; } <FILL_FUNCTION> /* Approves and then calls the receiving contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); //call the receiveApproval function on the contract you want to be notified. This crafts the function signature manually so one doesn't have to include a contract in here just for this. //receiveApproval(address _from, uint256 _value, address _tokenContract, bytes _extraData) //it is assumed that when does this that the call *should* succeed, otherwise one would use vanilla approve instead. if(!_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)) { throw; } return true; } }
totalEthInWei = totalEthInWei + msg.value; uint256 amount = msg.value * unitsOneEthCanBuy; require(balances[fundsWallet] >= amount); balances[fundsWallet] = balances[fundsWallet] - amount; balances[msg.sender] = balances[msg.sender] + amount; Transfer(fundsWallet, msg.sender, amount); // Broadcast a message to the blockchain //Transfer ether to fundsWallet fundsWallet.transfer(msg.value);
function() payable
function() payable
73337
owned
transferOwnership
contract owned { //Contract used to only allow the owner to call some functions address public owner; function owned() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address newOwner) onlyOwner public {<FILL_FUNCTION_BODY> } }
contract owned { //Contract used to only allow the owner to call some functions address public owner; function owned() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } <FILL_FUNCTION> }
owner = newOwner;
function transferOwnership(address newOwner) onlyOwner public
function transferOwnership(address newOwner) onlyOwner public
84331
CrowdsaleCompatible
initializeCrowdsale
contract CrowdsaleCompatible is BasicERC20, Ownable { BasicCrowdsale public crowdsale = BasicCrowdsale(0x0); // anyone can unfreeze tokens when crowdsale is finished function unfreezeTokens() public { assert(now > crowdsale.endTime()); isTokenTransferable = true; } // change owner to 0x0 to lock this function function initializeCrowdsale(address crowdsaleContractAddress, uint256 tokensAmount) onlyOwner public {<FILL_FUNCTION_BODY> } }
contract CrowdsaleCompatible is BasicERC20, Ownable { BasicCrowdsale public crowdsale = BasicCrowdsale(0x0); // anyone can unfreeze tokens when crowdsale is finished function unfreezeTokens() public { assert(now > crowdsale.endTime()); isTokenTransferable = true; } <FILL_FUNCTION> }
transfer((address)(0x0), tokensAmount); allowance[(address)(0x0)][crowdsaleContractAddress] = tokensAmount; crowdsale = BasicCrowdsale(crowdsaleContractAddress); isTokenTransferable = false; transferOwnership(0x0); // remove an owner
function initializeCrowdsale(address crowdsaleContractAddress, uint256 tokensAmount) onlyOwner public
// change owner to 0x0 to lock this function function initializeCrowdsale(address crowdsaleContractAddress, uint256 tokensAmount) onlyOwner public
66546
StandardToken
transferFrom
contract StandardToken is ERC20, SafeMath { //创建一个状态变量,该类型将一些address映射到无符号整数uint256。 mapping(address => uint) balances; mapping (address => mapping (address => uint)) allowed; /** * * 修复ERC20 short address attack * * http://vessenes.com/the-erc20-short-address-attack-explained/ */ modifier onlyPayloadSize(uint size) { if(msg.data.length < size + 4) { throw; } _; } function transfer(address _to, uint _value) onlyPayloadSize(2 * 32) returns (bool success) { //从消息发送者账户中减去token数量_value balances[msg.sender] = safeSub(balances[msg.sender], _value); //往接收账户增加token数量_value balances[_to] = safeAdd(balances[_to], _value); //触发转币交易事件 Transfer(msg.sender, _to, _value); return true; } function transferFrom(address _from, address _to, uint _value) returns (bool success) {<FILL_FUNCTION_BODY> } function balanceOf(address _owner) constant returns (uint balance) { return balances[_owner]; } function approve(address _spender, uint _value) returns (bool success) { if ((_value != 0) && (allowed[msg.sender][_spender] != 0)) throw; allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) constant returns (uint remaining) { //允许_spender从_owner中转出的token数 return allowed[_owner][_spender]; } }
contract StandardToken is ERC20, SafeMath { //创建一个状态变量,该类型将一些address映射到无符号整数uint256。 mapping(address => uint) balances; mapping (address => mapping (address => uint)) allowed; /** * * 修复ERC20 short address attack * * http://vessenes.com/the-erc20-short-address-attack-explained/ */ modifier onlyPayloadSize(uint size) { if(msg.data.length < size + 4) { throw; } _; } function transfer(address _to, uint _value) onlyPayloadSize(2 * 32) returns (bool success) { //从消息发送者账户中减去token数量_value balances[msg.sender] = safeSub(balances[msg.sender], _value); //往接收账户增加token数量_value balances[_to] = safeAdd(balances[_to], _value); //触发转币交易事件 Transfer(msg.sender, _to, _value); return true; } <FILL_FUNCTION> function balanceOf(address _owner) constant returns (uint balance) { return balances[_owner]; } function approve(address _spender, uint _value) returns (bool success) { if ((_value != 0) && (allowed[msg.sender][_spender] != 0)) throw; allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) constant returns (uint remaining) { //允许_spender从_owner中转出的token数 return allowed[_owner][_spender]; } }
var _allowance = allowed[_from][msg.sender]; //接收账户增加token数量_value balances[_to] = safeAdd(balances[_to], _value); //支出账户_from减去token数量_value balances[_from] = safeSub(balances[_from], _value); //消息发送者可以从账户_from中转出的数量减少_value allowed[_from][msg.sender] = safeSub(_allowance, _value); //触发转币交易事件 Transfer(_from, _to, _value); return true;
function transferFrom(address _from, address _to, uint _value) returns (bool success)
function transferFrom(address _from, address _to, uint _value) returns (bool success)
32599
ERC20Haltable
_mint
contract ERC20Haltable is ERC20Mintable, HalterRole { bool public paused; event Paused(address by); event Unpaused(address by); modifier notPaused() { require(!paused); _; } function pause() public onlyHalter { paused = true; emit Paused(msg.sender); } function unpause() public onlyHalter { paused = false; emit Unpaused(msg.sender); } function _transfer(address from, address to, uint256 value) internal notPaused { super._transfer(from, to, value); } function _mint(address account, uint256 value) internal notPaused {<FILL_FUNCTION_BODY> } function _burn(address account, uint256 amount) internal notPaused { super._burn(account, amount); } }
contract ERC20Haltable is ERC20Mintable, HalterRole { bool public paused; event Paused(address by); event Unpaused(address by); modifier notPaused() { require(!paused); _; } function pause() public onlyHalter { paused = true; emit Paused(msg.sender); } function unpause() public onlyHalter { paused = false; emit Unpaused(msg.sender); } function _transfer(address from, address to, uint256 value) internal notPaused { super._transfer(from, to, value); } <FILL_FUNCTION> function _burn(address account, uint256 amount) internal notPaused { super._burn(account, amount); } }
super._mint(account, value);
function _mint(address account, uint256 value) internal notPaused
function _mint(address account, uint256 value) internal notPaused
15367
dividendsContract
collectDividends
contract dividendsContract is Owned{ Ethernational dc; mapping(address => uint) paid; uint public totalSupply; uint public totalPaid; address public ICOaddress; function ICOaddress(address _t) onlyOwner{ dc = Ethernational(_t); ICOaddress = _t; totalSupply = dc.totalSupply() / 1000000000000; } function() payable{ } function collectDividends(address member) public returns (uint result) {<FILL_FUNCTION_BODY> } function thisBalance() constant returns (uint){ return this.balance; } function updatePaid(address from, address to, uint perc) { require (msg.sender == ICOaddress); uint val = ((paid[from] * 1000000) / perc) / 1000; paid[from] = paid[from] - val; paid[to] = paid[to] + val; } }
contract dividendsContract is Owned{ Ethernational dc; mapping(address => uint) paid; uint public totalSupply; uint public totalPaid; address public ICOaddress; function ICOaddress(address _t) onlyOwner{ dc = Ethernational(_t); ICOaddress = _t; totalSupply = dc.totalSupply() / 1000000000000; } function() payable{ } <FILL_FUNCTION> function thisBalance() constant returns (uint){ return this.balance; } function updatePaid(address from, address to, uint perc) { require (msg.sender == ICOaddress); uint val = ((paid[from] * 1000000) / perc) / 1000; paid[from] = paid[from] - val; paid[to] = paid[to] + val; } }
require (msg.sender == member && dc.endDate() < now); uint Ownes = dc.balanceOf(member) / 1000000000000; uint payout = (((address(this).balance + totalPaid)/totalSupply)*Ownes) - paid[member]; member.transfer(payout); paid[member] = paid[member] + payout; totalPaid = totalPaid + payout; return payout;
function collectDividends(address member) public returns (uint result)
function collectDividends(address member) public returns (uint result)
65751
ZanCoin
completeCrowdSale
contract ZanCoin is ERC20Interface, Owned { using SafeMath for uint; // ------------------------------------------------------------------------ // Metadata // ------------------------------------------------------------------------ string public symbol; string public name; uint8 public decimals; uint public _totalSupply; mapping(address => uint) public balances; mapping(address => mapping(address => uint)) public allowed; // ------------------------------------------------------------------------ // Crowdsale data // ------------------------------------------------------------------------ bool public isInPreSaleState; bool public isInRoundOneState; bool public isInRoundTwoState; bool public isInFinalState; uint public stateStartDate; uint public stateEndDate; uint public saleCap; uint public exchangeRate; uint public burnedTokensCount; event SwitchCrowdSaleStage(string stage, uint exchangeRate); event BurnTokens(address indexed burner, uint amount); event PurchaseZanTokens(address indexed contributor, uint eth_sent, uint zan_received); // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ function ZanCoin() public { symbol = "ZAN"; name = "ZAN Coin"; decimals = 18; _totalSupply = 17148385 * 10**uint(decimals); balances[owner] = _totalSupply; isInPreSaleState = false; isInRoundOneState = false; isInRoundTwoState = false; isInFinalState = false; burnedTokensCount = 0; } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account `tokenOwner` // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to `to` account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = balances[msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); emit Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer `tokens` from the `from` account to the `to` account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the `from` account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = balances[from].sub(tokens); allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); emit Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public 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; } // ------------------------------------------------------------------------ // Accepts ETH and transfers ZAN tokens based on exchage rate and state // ------------------------------------------------------------------------ function () public payable { uint eth_sent = msg.value; uint tokens_amount = eth_sent.mul(exchangeRate); require(eth_sent > 0); require(exchangeRate > 0); require(stateStartDate < now && now < stateEndDate); require(balances[owner] >= tokens_amount); require(_totalSupply - (balances[owner] - tokens_amount) <= saleCap); // Don't accept ETH in the final state require(!isInFinalState); require(isInPreSaleState || isInRoundOneState || isInRoundTwoState); balances[owner] = balances[owner].sub(tokens_amount); balances[msg.sender] = balances[msg.sender].add(tokens_amount); emit PurchaseZanTokens(msg.sender, eth_sent, tokens_amount); } // ------------------------------------------------------------------------ // Switches crowdsale stages: PreSale -> Round One -> Round Two // ------------------------------------------------------------------------ function switchCrowdSaleStage() external onlyOwner { require(!isInFinalState && !isInRoundTwoState); if (!isInPreSaleState) { isInPreSaleState = true; exchangeRate = 1500; saleCap = (3 * 10**6) * (uint(10) ** decimals); emit SwitchCrowdSaleStage("PreSale", exchangeRate); } else if (!isInRoundOneState) { isInRoundOneState = true; exchangeRate = 1200; saleCap = saleCap + ((4 * 10**6) * (uint(10) ** decimals)); emit SwitchCrowdSaleStage("RoundOne", exchangeRate); } else if (!isInRoundTwoState) { isInRoundTwoState = true; exchangeRate = 900; saleCap = saleCap + ((5 * 10**6) * (uint(10) ** decimals)); emit SwitchCrowdSaleStage("RoundTwo", exchangeRate); } stateStartDate = now + 5 minutes; stateEndDate = stateStartDate + 7 days; } // ------------------------------------------------------------------------ // Switches to Complete stage of the contract. Sends all funds collected // to the contract owner. // ------------------------------------------------------------------------ function completeCrowdSale() external onlyOwner {<FILL_FUNCTION_BODY> } // ------------------------------------------------------------------------ // Token holders are able to burn their tokens. // ------------------------------------------------------------------------ function burn(uint amount) public { require(amount > 0); require(amount <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(amount); _totalSupply = _totalSupply.sub(amount); burnedTokensCount = burnedTokensCount + amount; emit BurnTokens(msg.sender, amount); } // ------------------------------------------------------------------------ // 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 ZanCoin is ERC20Interface, Owned { using SafeMath for uint; // ------------------------------------------------------------------------ // Metadata // ------------------------------------------------------------------------ string public symbol; string public name; uint8 public decimals; uint public _totalSupply; mapping(address => uint) public balances; mapping(address => mapping(address => uint)) public allowed; // ------------------------------------------------------------------------ // Crowdsale data // ------------------------------------------------------------------------ bool public isInPreSaleState; bool public isInRoundOneState; bool public isInRoundTwoState; bool public isInFinalState; uint public stateStartDate; uint public stateEndDate; uint public saleCap; uint public exchangeRate; uint public burnedTokensCount; event SwitchCrowdSaleStage(string stage, uint exchangeRate); event BurnTokens(address indexed burner, uint amount); event PurchaseZanTokens(address indexed contributor, uint eth_sent, uint zan_received); // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ function ZanCoin() public { symbol = "ZAN"; name = "ZAN Coin"; decimals = 18; _totalSupply = 17148385 * 10**uint(decimals); balances[owner] = _totalSupply; isInPreSaleState = false; isInRoundOneState = false; isInRoundTwoState = false; isInFinalState = false; burnedTokensCount = 0; } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account `tokenOwner` // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to `to` account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = balances[msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); emit Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer `tokens` from the `from` account to the `to` account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the `from` account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = balances[from].sub(tokens); allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); emit Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public 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; } // ------------------------------------------------------------------------ // Accepts ETH and transfers ZAN tokens based on exchage rate and state // ------------------------------------------------------------------------ function () public payable { uint eth_sent = msg.value; uint tokens_amount = eth_sent.mul(exchangeRate); require(eth_sent > 0); require(exchangeRate > 0); require(stateStartDate < now && now < stateEndDate); require(balances[owner] >= tokens_amount); require(_totalSupply - (balances[owner] - tokens_amount) <= saleCap); // Don't accept ETH in the final state require(!isInFinalState); require(isInPreSaleState || isInRoundOneState || isInRoundTwoState); balances[owner] = balances[owner].sub(tokens_amount); balances[msg.sender] = balances[msg.sender].add(tokens_amount); emit PurchaseZanTokens(msg.sender, eth_sent, tokens_amount); } // ------------------------------------------------------------------------ // Switches crowdsale stages: PreSale -> Round One -> Round Two // ------------------------------------------------------------------------ function switchCrowdSaleStage() external onlyOwner { require(!isInFinalState && !isInRoundTwoState); if (!isInPreSaleState) { isInPreSaleState = true; exchangeRate = 1500; saleCap = (3 * 10**6) * (uint(10) ** decimals); emit SwitchCrowdSaleStage("PreSale", exchangeRate); } else if (!isInRoundOneState) { isInRoundOneState = true; exchangeRate = 1200; saleCap = saleCap + ((4 * 10**6) * (uint(10) ** decimals)); emit SwitchCrowdSaleStage("RoundOne", exchangeRate); } else if (!isInRoundTwoState) { isInRoundTwoState = true; exchangeRate = 900; saleCap = saleCap + ((5 * 10**6) * (uint(10) ** decimals)); emit SwitchCrowdSaleStage("RoundTwo", exchangeRate); } stateStartDate = now + 5 minutes; stateEndDate = stateStartDate + 7 days; } <FILL_FUNCTION> // ------------------------------------------------------------------------ // Token holders are able to burn their tokens. // ------------------------------------------------------------------------ function burn(uint amount) public { require(amount > 0); require(amount <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(amount); _totalSupply = _totalSupply.sub(amount); burnedTokensCount = burnedTokensCount + amount; emit BurnTokens(msg.sender, amount); } // ------------------------------------------------------------------------ // 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); } }
require(!isInFinalState); require(isInPreSaleState && isInRoundOneState && isInRoundTwoState); owner.transfer(address(this).balance); exchangeRate = 0; isInFinalState = true; emit SwitchCrowdSaleStage("Complete", exchangeRate);
function completeCrowdSale() external onlyOwner
// ------------------------------------------------------------------------ // Switches to Complete stage of the contract. Sends all funds collected // to the contract owner. // ------------------------------------------------------------------------ function completeCrowdSale() external onlyOwner
14018
SafeMath
safeAdd
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) { assert(b > 0); uint256 c = a / b; assert(a == b * c + a % b); return c; } 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) {<FILL_FUNCTION_BODY> } 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; } function safeDiv(uint256 a, uint256 b)public pure returns (uint256) { assert(b > 0); uint256 c = a / b; assert(a == b * c + a % b); return c; } function safeSub(uint256 a, uint256 b)public pure returns (uint256) { assert(b <= a); return a - b; } <FILL_FUNCTION> function _assert(bool assertion)public pure { assert(!assertion); } }
uint256 c = a + b; assert(c>=a && c>=b); return c;
function safeAdd(uint256 a, uint256 b)public pure returns (uint256)
function safeAdd(uint256 a, uint256 b)public pure returns (uint256)
13315
AuctionPotato
placeBid
contract AuctionPotato { using SafeMath for uint256; // static address public owner; uint public startTime; string name; // start auction manually at given time bool started; // pototo uint public potato; uint oldPotato; uint oldHighestBindingBid; // transfer ownership address creatureOwner; event CreatureOwnershipTransferred(address indexed _from, address indexed _to); uint public highestBindingBid; address public highestBidder; // used to immidiately block placeBids bool blockerPay; bool blockerWithdraw; mapping(address => uint256) public fundsByBidder; event LogBid(address bidder, address highestBidder, uint oldHighestBindingBid, uint highestBindingBid); event LogWithdrawal(address withdrawer, address withdrawalAccount, uint amount); // initial settings on contract creation constructor() public { blockerWithdraw = false; blockerPay = false; owner = msg.sender; creatureOwner = owner; // 1 ETH starting price highestBindingBid = 1000000000000000000; potato = 0; started = false; name = "Aetherian"; } function getHighestBid() internal constant returns (uint) { return fundsByBidder[highestBidder]; } function auctionName() public view returns (string _name) { return name; } // calculates the next bid amount so that you can have a one-click buy button function nextBid() public view returns (uint _nextBid) { return highestBindingBid.add(potato); } // command to start the auction function startAuction() public onlyOwner returns (bool success){ require(started == false); started = true; startTime = now; return true; } function isStarted() public view returns (bool success) { return started; } function placeBid() public payable onlyAfterStart onlyNotOwner returns (bool success) {<FILL_FUNCTION_BODY> } function withdraw() public // can withdraw once overbid returns (bool success) { require(blockerWithdraw == false); blockerWithdraw = true; address withdrawalAccount; uint withdrawalAmount; if (msg.sender == owner) { withdrawalAccount = owner; withdrawalAmount = fundsByBidder[withdrawalAccount]; // set funds to 0 fundsByBidder[withdrawalAccount] = 0; } // overbid people can withdraw their bid + profit // exclude owner because he is set above if (msg.sender != highestBidder && msg.sender != owner) { withdrawalAccount = msg.sender; withdrawalAmount = fundsByBidder[withdrawalAccount]; fundsByBidder[withdrawalAccount] = 0; } if (withdrawalAmount == 0) revert(); // send the funds msg.sender.transfer(withdrawalAmount); emit LogWithdrawal(msg.sender, withdrawalAccount, withdrawalAmount); blockerWithdraw = false; return true; } // amount owner can withdraw // that way you can easily compare the contract balance with your amount // if there is more in the contract than your balance someone didn't withdraw // let them know that :) function ownerCanWithdraw() public view returns (uint amount) { return fundsByBidder[owner]; } // just in case the contract is bust and can't pay // should never be needed but who knows function fuelContract() public onlyOwner payable { } function balance() public view returns (uint _balance) { return address(this).balance; } modifier onlyOwner { require(msg.sender == owner); _; } modifier onlyNotOwner { require(msg.sender != owner); _; } modifier onlyAfterStart { if (now < startTime) revert(); _; } // who owns the creature (not necessarily auction winner) function queryCreatureOwner() public view returns (address _creatureOwner) { return creatureOwner; } }
contract AuctionPotato { using SafeMath for uint256; // static address public owner; uint public startTime; string name; // start auction manually at given time bool started; // pototo uint public potato; uint oldPotato; uint oldHighestBindingBid; // transfer ownership address creatureOwner; event CreatureOwnershipTransferred(address indexed _from, address indexed _to); uint public highestBindingBid; address public highestBidder; // used to immidiately block placeBids bool blockerPay; bool blockerWithdraw; mapping(address => uint256) public fundsByBidder; event LogBid(address bidder, address highestBidder, uint oldHighestBindingBid, uint highestBindingBid); event LogWithdrawal(address withdrawer, address withdrawalAccount, uint amount); // initial settings on contract creation constructor() public { blockerWithdraw = false; blockerPay = false; owner = msg.sender; creatureOwner = owner; // 1 ETH starting price highestBindingBid = 1000000000000000000; potato = 0; started = false; name = "Aetherian"; } function getHighestBid() internal constant returns (uint) { return fundsByBidder[highestBidder]; } function auctionName() public view returns (string _name) { return name; } // calculates the next bid amount so that you can have a one-click buy button function nextBid() public view returns (uint _nextBid) { return highestBindingBid.add(potato); } // command to start the auction function startAuction() public onlyOwner returns (bool success){ require(started == false); started = true; startTime = now; return true; } function isStarted() public view returns (bool success) { return started; } <FILL_FUNCTION> function withdraw() public // can withdraw once overbid returns (bool success) { require(blockerWithdraw == false); blockerWithdraw = true; address withdrawalAccount; uint withdrawalAmount; if (msg.sender == owner) { withdrawalAccount = owner; withdrawalAmount = fundsByBidder[withdrawalAccount]; // set funds to 0 fundsByBidder[withdrawalAccount] = 0; } // overbid people can withdraw their bid + profit // exclude owner because he is set above if (msg.sender != highestBidder && msg.sender != owner) { withdrawalAccount = msg.sender; withdrawalAmount = fundsByBidder[withdrawalAccount]; fundsByBidder[withdrawalAccount] = 0; } if (withdrawalAmount == 0) revert(); // send the funds msg.sender.transfer(withdrawalAmount); emit LogWithdrawal(msg.sender, withdrawalAccount, withdrawalAmount); blockerWithdraw = false; return true; } // amount owner can withdraw // that way you can easily compare the contract balance with your amount // if there is more in the contract than your balance someone didn't withdraw // let them know that :) function ownerCanWithdraw() public view returns (uint amount) { return fundsByBidder[owner]; } // just in case the contract is bust and can't pay // should never be needed but who knows function fuelContract() public onlyOwner payable { } function balance() public view returns (uint _balance) { return address(this).balance; } modifier onlyOwner { require(msg.sender == owner); _; } modifier onlyNotOwner { require(msg.sender != owner); _; } modifier onlyAfterStart { if (now < startTime) revert(); _; } // who owns the creature (not necessarily auction winner) function queryCreatureOwner() public view returns (address _creatureOwner) { return creatureOwner; } }
// we are only allowing to increase in bidIncrements to make for true hot potato style // while still allowing overbid to happen in case some parties are trying to require(msg.value >= highestBindingBid.add(potato)); require(msg.sender != highestBidder); require(started == true); require(blockerPay == false); blockerPay = true; // if someone overbids, return their if (msg.value > highestBindingBid.add(potato)) { uint overbid = msg.value - highestBindingBid.add(potato); msg.sender.transfer(overbid); } // calculate the user's total bid based on the current amount they've sent to the contract // plus whatever has been sent with this transaction oldHighestBindingBid = highestBindingBid; // set new highest bidder highestBidder = msg.sender; highestBindingBid = highestBindingBid.add(potato); fundsByBidder[msg.sender] = fundsByBidder[msg.sender].add(highestBindingBid); oldPotato = potato; uint potatoShare; potatoShare = potato.div(2); potato = highestBindingBid.mul(5).div(10); // special case at start of auction if (creatureOwner == owner) { fundsByBidder[owner] = fundsByBidder[owner].add(highestBindingBid); } else { fundsByBidder[owner] = fundsByBidder[owner].add(potatoShare); fundsByBidder[creatureOwner] = fundsByBidder[creatureOwner].add(potatoShare); } emit LogBid(msg.sender, highestBidder, oldHighestBindingBid, highestBindingBid); emit CreatureOwnershipTransferred(creatureOwner, msg.sender); creatureOwner = msg.sender; blockerPay = false; return true;
function placeBid() public payable onlyAfterStart onlyNotOwner returns (bool success)
function placeBid() public payable onlyAfterStart onlyNotOwner returns (bool success)
83911
TokenERC20
_transfer
contract TokenERC20 { // 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 notifies clients about the amount burnt event Burn(address indexed from, uint256 value); /** * Constructor function * * Initializes contract with initial supply tokens to the creator of the contract */ function TokenERC20( uint256 initialSupply, string tokenName, string 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 {<FILL_FUNCTION_BODY> } /** * Transfer tokens * * Send `_value` tokens to `_to` from your account * * @param _to The address of the recipient * @param _value the amount to send */ function transfer(address _to, uint256 _value) public { _transfer(msg.sender, _to, _value); } /** * Transfer tokens from other address * * Send `_value` tokens to `_to` on behalf of `_from` * * @param _from The address of the sender * @param _to The address of the recipient * @param _value the amount to send */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_value <= allowance[_from][msg.sender]); // Check allowance allowance[_from][msg.sender] -= _value; _transfer(_from, _to, _value); return true; } /** * Set allowance for other address * * Allows `_spender` to spend no more than `_value` tokens on your behalf * * @param _spender The address authorized to spend * @param _value the max amount they can spend */ function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; return true; } /** * Set allowance for other address and notify * * Allows `_spender` to spend no more than `_value` tokens on your behalf, and then ping the contract about it * * @param _spender The address authorized to spend * @param _value the max amount they can spend * @param _extraData some extra information to send to the approved contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } /** * Destroy tokens * * Remove `_value` tokens from the system irreversibly * * @param _value the amount of money to burn */ function burn(uint256 _value) public returns (bool success) { require(balanceOf[msg.sender] >= _value); // Check if the sender has enough balanceOf[msg.sender] -= _value; // Subtract from the sender totalSupply -= _value; // Updates totalSupply Burn(msg.sender, _value); return true; } /** * Destroy tokens from other account * * Remove `_value` tokens from the system irreversibly on behalf of `_from`. * * @param _from the address of the sender * @param _value the amount of money to burn */ function burnFrom(address _from, uint256 _value) public returns (bool success) { require(balanceOf[_from] >= _value); // Check if the targeted balance is enough require(_value <= allowance[_from][msg.sender]); // Check allowance balanceOf[_from] -= _value; // Subtract from the targeted balance allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance totalSupply -= _value; // Update totalSupply Burn(_from, _value); return true; } }
contract TokenERC20 { // 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 notifies clients about the amount burnt event Burn(address indexed from, uint256 value); /** * Constructor function * * Initializes contract with initial supply tokens to the creator of the contract */ function TokenERC20( uint256 initialSupply, string tokenName, string 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 } <FILL_FUNCTION> /** * Transfer tokens * * Send `_value` tokens to `_to` from your account * * @param _to The address of the recipient * @param _value the amount to send */ function transfer(address _to, uint256 _value) public { _transfer(msg.sender, _to, _value); } /** * Transfer tokens from other address * * Send `_value` tokens to `_to` on behalf of `_from` * * @param _from The address of the sender * @param _to The address of the recipient * @param _value the amount to send */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_value <= allowance[_from][msg.sender]); // Check allowance allowance[_from][msg.sender] -= _value; _transfer(_from, _to, _value); return true; } /** * Set allowance for other address * * Allows `_spender` to spend no more than `_value` tokens on your behalf * * @param _spender The address authorized to spend * @param _value the max amount they can spend */ function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; return true; } /** * Set allowance for other address and notify * * Allows `_spender` to spend no more than `_value` tokens on your behalf, and then ping the contract about it * * @param _spender The address authorized to spend * @param _value the max amount they can spend * @param _extraData some extra information to send to the approved contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } /** * Destroy tokens * * Remove `_value` tokens from the system irreversibly * * @param _value the amount of money to burn */ function burn(uint256 _value) public returns (bool success) { require(balanceOf[msg.sender] >= _value); // Check if the sender has enough balanceOf[msg.sender] -= _value; // Subtract from the sender totalSupply -= _value; // Updates totalSupply Burn(msg.sender, _value); return true; } /** * Destroy tokens from other account * * Remove `_value` tokens from the system irreversibly on behalf of `_from`. * * @param _from the address of the sender * @param _value the amount of money to burn */ function burnFrom(address _from, uint256 _value) public returns (bool success) { require(balanceOf[_from] >= _value); // Check if the targeted balance is enough require(_value <= allowance[_from][msg.sender]); // Check allowance balanceOf[_from] -= _value; // Subtract from the targeted balance allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance totalSupply -= _value; // Update totalSupply Burn(_from, _value); return true; } }
// Prevent transfer to 0x0 address. Use burn() instead require(_to != 0x0); // Check if the sender has enough require(balanceOf[_from] >= _value); // Check for overflows require(balanceOf[_to] + _value > balanceOf[_to]); // Save this for an assertion in the future uint previousBalances = balanceOf[_from] + balanceOf[_to]; // Subtract from the sender balanceOf[_from] -= _value; // Add the same to the recipient balanceOf[_to] += _value; Transfer(_from, _to, _value); // Asserts are used to use static analysis to find bugs in your code. They should never fail assert(balanceOf[_from] + balanceOf[_to] == previousBalances);
function _transfer(address _from, address _to, uint _value) internal
/** * Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) internal
66650
ERC20Mintable
mint
contract ERC20Mintable is ERC20, MinterRole { /** * @dev See {ERC20-_mint}. * * Requirements: * * - the caller must have the {MinterRole}. */ function mint(address account, uint256 amount) public onlyMinter returns (bool) {<FILL_FUNCTION_BODY> } }
contract ERC20Mintable is ERC20, MinterRole { <FILL_FUNCTION> }
_mint(account, amount); return true;
function mint(address account, uint256 amount) public onlyMinter returns (bool)
/** * @dev See {ERC20-_mint}. * * Requirements: * * - the caller must have the {MinterRole}. */ function mint(address account, uint256 amount) public onlyMinter returns (bool)
17468
HYIPToken
HYIPToken
contract HYIPToken is BurnableToken, UpgradeableToken { string public name; string public symbol; uint public decimals; address public owner; /** List of agents that are allowed to create new tokens */ mapping (address => bool) public mintAgents; event MintingAgentChanged(address addr, bool state); /** * Create new tokens and allocate them to an address.. * * Only callably by a crowdsale contract (mint agent). */ function mint(address receiver, uint amount) onlyMintAgent public { totalSupply = totalSupply + amount; balances[receiver] = balances[receiver] + amount; // This will make the mint transaction apper in EtherScan.io // We can remove this after there is a standardized minting event Transfer(0, receiver, amount); } /** * Owner can allow a crowdsale contract to mint new tokens. */ function setMintAgent(address addr, bool state) onlyOwner public { mintAgents[addr] = state; MintingAgentChanged(addr, state); } modifier onlyMintAgent() { // Only crowdsale contracts are allowed to mint new tokens if(!mintAgents[msg.sender]) { throw; } _; } modifier onlyOwner() { if (msg.sender != owner) { throw; } _; } function HYIPToken(address _owner, string _name, string _symbol, uint _totalSupply, uint _decimals) UpgradeableToken(_owner) {<FILL_FUNCTION_BODY> } }
contract HYIPToken is BurnableToken, UpgradeableToken { string public name; string public symbol; uint public decimals; address public owner; /** List of agents that are allowed to create new tokens */ mapping (address => bool) public mintAgents; event MintingAgentChanged(address addr, bool state); /** * Create new tokens and allocate them to an address.. * * Only callably by a crowdsale contract (mint agent). */ function mint(address receiver, uint amount) onlyMintAgent public { totalSupply = totalSupply + amount; balances[receiver] = balances[receiver] + amount; // This will make the mint transaction apper in EtherScan.io // We can remove this after there is a standardized minting event Transfer(0, receiver, amount); } /** * Owner can allow a crowdsale contract to mint new tokens. */ function setMintAgent(address addr, bool state) onlyOwner public { mintAgents[addr] = state; MintingAgentChanged(addr, state); } modifier onlyMintAgent() { // Only crowdsale contracts are allowed to mint new tokens if(!mintAgents[msg.sender]) { throw; } _; } modifier onlyOwner() { if (msg.sender != owner) { throw; } _; } <FILL_FUNCTION> }
name = _name; symbol = _symbol; totalSupply = _totalSupply; decimals = _decimals; // Allocate initial balance to the owner balances[_owner] = _totalSupply; owner = _owner;
function HYIPToken(address _owner, string _name, string _symbol, uint _totalSupply, uint _decimals) UpgradeableToken(_owner)
function HYIPToken(address _owner, string _name, string _symbol, uint _totalSupply, uint _decimals) UpgradeableToken(_owner)
94031
TimeLockToken
timelockAccount
contract TimeLockToken is StandardToken, Ownable { mapping (address => uint) public timelockAccounts; event TimeLockFunds(address target, uint releasetime); function timelockAccount(address target, uint releasetime) public onlyOwner {<FILL_FUNCTION_BODY> } function timeunlockAccount(address target) public onlyOwner { timelockAccounts[target] = now; emit TimeLockFunds(target, now); } function releasetime(address _target) view public returns (uint){ return timelockAccounts[_target]; } modifier ReleaseTimeTransfer(address _sender) { require(now >= timelockAccounts[_sender]); _; } function transfer(address _to, uint256 _value) public ReleaseTimeTransfer(msg.sender) returns (bool success) { return super.transfer(_to, _value); } function transferFrom(address _from, address _to, uint256 _value) public ReleaseTimeTransfer(_from) returns (bool success) { return super.transferFrom(_from, _to, _value); } }
contract TimeLockToken is StandardToken, Ownable { mapping (address => uint) public timelockAccounts; event TimeLockFunds(address target, uint releasetime); <FILL_FUNCTION> function timeunlockAccount(address target) public onlyOwner { timelockAccounts[target] = now; emit TimeLockFunds(target, now); } function releasetime(address _target) view public returns (uint){ return timelockAccounts[_target]; } modifier ReleaseTimeTransfer(address _sender) { require(now >= timelockAccounts[_sender]); _; } function transfer(address _to, uint256 _value) public ReleaseTimeTransfer(msg.sender) returns (bool success) { return super.transfer(_to, _value); } function transferFrom(address _from, address _to, uint256 _value) public ReleaseTimeTransfer(_from) returns (bool success) { return super.transferFrom(_from, _to, _value); } }
uint r_time; r_time = now + (releasetime * 1 days); timelockAccounts[target] = r_time; emit TimeLockFunds(target, r_time);
function timelockAccount(address target, uint releasetime) public onlyOwner
function timelockAccount(address target, uint releasetime) public onlyOwner
80199
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
60843
CommonBsPresale
contract CommonBsPresale is SafeMath, Ownable, Pausable { enum Currency { BTC, LTC, ZEC, DASH, WAVES, USD, EUR } // TODO rename to Buyer? struct Backer { uint256 weiReceived; // Amount of wei given by backer uint256 tokensSent; // Amount of tokens received in return to the given amount of ETH. } // TODO rename to buyers? // (buyer_eth_address -> struct) mapping(address => Backer) public backers; // currency_code => (tx_hash => tokens) mapping(uint8 => mapping(bytes32 => uint256)) public externalTxs; CommonBsToken public token; // Token contract reference. address public beneficiary; // Address that will receive ETH raised during this crowdsale. address public notifier; // Address that can this crowdsale about changed external conditions. uint256 public minTokensToBuy = 1 * 1e18; // Including bonuses. uint256 public maxCapWei = 50000 ether; uint public tokensPerWei = 1000; // Ordinary price: 1 ETH = 1000 tokens. uint public tokensPerWeiBonus333 = 1333; uint public tokensPerWeiBonus250 = 1250; uint public tokensPerWeiBonus111 = 1111; uint public startTime = 1410160700; // 2017-11-08T17:05:00Z uint public bonusEndTime333 = 1510333500; // 2017-11-10T17:05:00Z uint public bonusEndTime250 = 1510679100; // 2017-11-14T17:05:00Z uint public endTime = 1511024700; // 2017-11-18T17:05:00Z // Stats for current crowdsale // TODO rename to 'totalInWei' uint256 public totalWei = 0; // Grand total in wei uint256 public totalTokensSold = 0; // Total amount of tokens sold during this crowdsale. uint256 public totalEthSales = 0; // Total amount of ETH contributions during this crowdsale. uint256 public totalExternalSales = 0; // Total amount of external contributions (BTC, LTC, USD, etc.) during this crowdsale. uint256 public weiReceived = 0; // Total amount of wei received during this crowdsale smart contract. uint public finalizedTime = 0; // Unix timestamp when finalize() was called. bool public saleEnabled = true; // if false, then contract will not sell tokens on payment received event BeneficiaryChanged(address indexed _oldAddress, address indexed _newAddress); event NotifierChanged(address indexed _oldAddress, address indexed _newAddress); event EthReceived(address indexed _buyer, uint256 _amountWei); event ExternalSaleSha3(Currency _currency, bytes32 _txIdSha3, address indexed _buyer, uint256 _amountWei, uint256 _tokensE18); modifier respectTimeFrame() { require(isSaleOn()); _; } modifier canNotify() { require(msg.sender == owner || msg.sender == notifier); _; } function CommonBsPresale(address _token, address _beneficiary) { token = CommonBsToken(_token); owner = msg.sender; notifier = owner; beneficiary = _beneficiary; } // Override this method to mock current time. function getNow() public constant returns (uint) { return now; } function setSaleEnabled(bool _enabled) public onlyOwner { saleEnabled = _enabled; } function setBeneficiary(address _beneficiary) public onlyOwner { BeneficiaryChanged(beneficiary, _beneficiary); beneficiary = _beneficiary; } function setNotifier(address _notifier) public onlyOwner { NotifierChanged(notifier, _notifier); notifier = _notifier; } /* * The fallback function corresponds to a donation in ETH */ function() public payable {<FILL_FUNCTION_BODY> } function sellTokensForEth(address _buyer, uint256 _amountWei) internal ifNotPaused respectTimeFrame { totalWei = safeAdd(totalWei, _amountWei); weiReceived = safeAdd(weiReceived, _amountWei); require(totalWei <= maxCapWei); // If max cap reached. uint256 tokensE18 = weiToTokens(_amountWei); require(tokensE18 >= minTokensToBuy); require(token.sell(_buyer, tokensE18)); // Transfer tokens to buyer. totalTokensSold = safeAdd(totalTokensSold, tokensE18); totalEthSales++; Backer backer = backers[_buyer]; backer.tokensSent = safeAdd(backer.tokensSent, tokensE18); backer.weiReceived = safeAdd(backer.weiReceived, _amountWei); // Update the total wei collected during the crowdfunding for this backer EthReceived(_buyer, _amountWei); } // Calc how much tokens you can buy at current time. function weiToTokens(uint256 _amountWei) public constant returns (uint256) { return weiToTokensAtTime(_amountWei, getNow()); } function weiToTokensAtTime(uint256 _amountWei, uint _time) public constant returns (uint256) { uint256 rate = tokensPerWei; if (startTime <= _time && _time < bonusEndTime333) rate = tokensPerWeiBonus333; else if (bonusEndTime333 <= _time && _time < bonusEndTime250) rate = tokensPerWeiBonus250; else if (bonusEndTime250 <= _time && _time < endTime) rate = tokensPerWeiBonus111; return safeMul(_amountWei, rate); } //---------------------------------------------------------------------- // Begin of external sales. function externalSales( uint8[] _currencies, bytes32[] _txIdSha3, address[] _buyers, uint256[] _amountsWei, uint256[] _tokensE18 ) public ifNotPaused canNotify { require(_currencies.length > 0); require(_currencies.length == _txIdSha3.length); require(_currencies.length == _buyers.length); require(_currencies.length == _amountsWei.length); require(_currencies.length == _tokensE18.length); for (uint i = 0; i < _txIdSha3.length; i++) { _externalSaleSha3( Currency(_currencies[i]), _txIdSha3[i], _buyers[i], _amountsWei[i], _tokensE18[i] ); } } function _externalSaleSha3( Currency _currency, bytes32 _txIdSha3, // To get bytes32 use keccak256(txId) OR sha3(txId) address _buyer, uint256 _amountWei, uint256 _tokensE18 ) internal { require(_buyer > 0 && _amountWei > 0 && _tokensE18 > 0); var txsByCur = externalTxs[uint8(_currency)]; // If this foreign transaction has been already processed in this contract. require(txsByCur[_txIdSha3] == 0); totalWei = safeAdd(totalWei, _amountWei); require(totalWei <= maxCapWei); // Max cap should not be reached yet. require(token.sell(_buyer, _tokensE18)); // Transfer tokens to buyer. totalTokensSold = safeAdd(totalTokensSold, _tokensE18); totalExternalSales++; txsByCur[_txIdSha3] = _tokensE18; ExternalSaleSha3(_currency, _txIdSha3, _buyer, _amountWei, _tokensE18); } // Get id of currency enum. -------------------------------------------- function btcId() public constant returns (uint8) { return uint8(Currency.BTC); } function ltcId() public constant returns (uint8) { return uint8(Currency.LTC); } function zecId() public constant returns (uint8) { return uint8(Currency.ZEC); } function dashId() public constant returns (uint8) { return uint8(Currency.DASH); } function wavesId() public constant returns (uint8) { return uint8(Currency.WAVES); } function usdId() public constant returns (uint8) { return uint8(Currency.USD); } function eurId() public constant returns (uint8) { return uint8(Currency.EUR); } // Get token count by transaction id. ---------------------------------- function _tokensByTx(Currency _currency, string _txId) internal constant returns (uint256) { return tokensByTx(uint8(_currency), _txId); } function tokensByTx(uint8 _currency, string _txId) public constant returns (uint256) { return externalTxs[_currency][keccak256(_txId)]; } function tokensByBtcTx(string _txId) public constant returns (uint256) { return _tokensByTx(Currency.BTC, _txId); } function tokensByLtcTx(string _txId) public constant returns (uint256) { return _tokensByTx(Currency.LTC, _txId); } function tokensByZecTx(string _txId) public constant returns (uint256) { return _tokensByTx(Currency.ZEC, _txId); } function tokensByDashTx(string _txId) public constant returns (uint256) { return _tokensByTx(Currency.DASH, _txId); } function tokensByWavesTx(string _txId) public constant returns (uint256) { return _tokensByTx(Currency.WAVES, _txId); } function tokensByUsdTx(string _txId) public constant returns (uint256) { return _tokensByTx(Currency.USD, _txId); } function tokensByEurTx(string _txId) public constant returns (uint256) { return _tokensByTx(Currency.EUR, _txId); } // End of external sales. //---------------------------------------------------------------------- function totalSales() public constant returns (uint256) { return safeAdd(totalEthSales, totalExternalSales); } function isMaxCapReached() public constant returns (bool) { return totalWei >= maxCapWei; } function isSaleOn() public constant returns (bool) { uint _now = getNow(); return startTime <= _now && _now <= endTime; } function isSaleOver() public constant returns (bool) { return getNow() > endTime; } function isFinalized() public constant returns (bool) { return finalizedTime > 0; } /* * Finalize the crowdsale. Raised money can be sent to beneficiary only if crowdsale hit end time or max cap (15m USD). */ function finalize() public onlyOwner { // Cannot finalise before end day of crowdsale until max cap is reached. require(isMaxCapReached() || isSaleOver()); beneficiary.transfer(this.balance); finalizedTime = getNow(); } }
contract CommonBsPresale is SafeMath, Ownable, Pausable { enum Currency { BTC, LTC, ZEC, DASH, WAVES, USD, EUR } // TODO rename to Buyer? struct Backer { uint256 weiReceived; // Amount of wei given by backer uint256 tokensSent; // Amount of tokens received in return to the given amount of ETH. } // TODO rename to buyers? // (buyer_eth_address -> struct) mapping(address => Backer) public backers; // currency_code => (tx_hash => tokens) mapping(uint8 => mapping(bytes32 => uint256)) public externalTxs; CommonBsToken public token; // Token contract reference. address public beneficiary; // Address that will receive ETH raised during this crowdsale. address public notifier; // Address that can this crowdsale about changed external conditions. uint256 public minTokensToBuy = 1 * 1e18; // Including bonuses. uint256 public maxCapWei = 50000 ether; uint public tokensPerWei = 1000; // Ordinary price: 1 ETH = 1000 tokens. uint public tokensPerWeiBonus333 = 1333; uint public tokensPerWeiBonus250 = 1250; uint public tokensPerWeiBonus111 = 1111; uint public startTime = 1410160700; // 2017-11-08T17:05:00Z uint public bonusEndTime333 = 1510333500; // 2017-11-10T17:05:00Z uint public bonusEndTime250 = 1510679100; // 2017-11-14T17:05:00Z uint public endTime = 1511024700; // 2017-11-18T17:05:00Z // Stats for current crowdsale // TODO rename to 'totalInWei' uint256 public totalWei = 0; // Grand total in wei uint256 public totalTokensSold = 0; // Total amount of tokens sold during this crowdsale. uint256 public totalEthSales = 0; // Total amount of ETH contributions during this crowdsale. uint256 public totalExternalSales = 0; // Total amount of external contributions (BTC, LTC, USD, etc.) during this crowdsale. uint256 public weiReceived = 0; // Total amount of wei received during this crowdsale smart contract. uint public finalizedTime = 0; // Unix timestamp when finalize() was called. bool public saleEnabled = true; // if false, then contract will not sell tokens on payment received event BeneficiaryChanged(address indexed _oldAddress, address indexed _newAddress); event NotifierChanged(address indexed _oldAddress, address indexed _newAddress); event EthReceived(address indexed _buyer, uint256 _amountWei); event ExternalSaleSha3(Currency _currency, bytes32 _txIdSha3, address indexed _buyer, uint256 _amountWei, uint256 _tokensE18); modifier respectTimeFrame() { require(isSaleOn()); _; } modifier canNotify() { require(msg.sender == owner || msg.sender == notifier); _; } function CommonBsPresale(address _token, address _beneficiary) { token = CommonBsToken(_token); owner = msg.sender; notifier = owner; beneficiary = _beneficiary; } // Override this method to mock current time. function getNow() public constant returns (uint) { return now; } function setSaleEnabled(bool _enabled) public onlyOwner { saleEnabled = _enabled; } function setBeneficiary(address _beneficiary) public onlyOwner { BeneficiaryChanged(beneficiary, _beneficiary); beneficiary = _beneficiary; } function setNotifier(address _notifier) public onlyOwner { NotifierChanged(notifier, _notifier); notifier = _notifier; } <FILL_FUNCTION> function sellTokensForEth(address _buyer, uint256 _amountWei) internal ifNotPaused respectTimeFrame { totalWei = safeAdd(totalWei, _amountWei); weiReceived = safeAdd(weiReceived, _amountWei); require(totalWei <= maxCapWei); // If max cap reached. uint256 tokensE18 = weiToTokens(_amountWei); require(tokensE18 >= minTokensToBuy); require(token.sell(_buyer, tokensE18)); // Transfer tokens to buyer. totalTokensSold = safeAdd(totalTokensSold, tokensE18); totalEthSales++; Backer backer = backers[_buyer]; backer.tokensSent = safeAdd(backer.tokensSent, tokensE18); backer.weiReceived = safeAdd(backer.weiReceived, _amountWei); // Update the total wei collected during the crowdfunding for this backer EthReceived(_buyer, _amountWei); } // Calc how much tokens you can buy at current time. function weiToTokens(uint256 _amountWei) public constant returns (uint256) { return weiToTokensAtTime(_amountWei, getNow()); } function weiToTokensAtTime(uint256 _amountWei, uint _time) public constant returns (uint256) { uint256 rate = tokensPerWei; if (startTime <= _time && _time < bonusEndTime333) rate = tokensPerWeiBonus333; else if (bonusEndTime333 <= _time && _time < bonusEndTime250) rate = tokensPerWeiBonus250; else if (bonusEndTime250 <= _time && _time < endTime) rate = tokensPerWeiBonus111; return safeMul(_amountWei, rate); } //---------------------------------------------------------------------- // Begin of external sales. function externalSales( uint8[] _currencies, bytes32[] _txIdSha3, address[] _buyers, uint256[] _amountsWei, uint256[] _tokensE18 ) public ifNotPaused canNotify { require(_currencies.length > 0); require(_currencies.length == _txIdSha3.length); require(_currencies.length == _buyers.length); require(_currencies.length == _amountsWei.length); require(_currencies.length == _tokensE18.length); for (uint i = 0; i < _txIdSha3.length; i++) { _externalSaleSha3( Currency(_currencies[i]), _txIdSha3[i], _buyers[i], _amountsWei[i], _tokensE18[i] ); } } function _externalSaleSha3( Currency _currency, bytes32 _txIdSha3, // To get bytes32 use keccak256(txId) OR sha3(txId) address _buyer, uint256 _amountWei, uint256 _tokensE18 ) internal { require(_buyer > 0 && _amountWei > 0 && _tokensE18 > 0); var txsByCur = externalTxs[uint8(_currency)]; // If this foreign transaction has been already processed in this contract. require(txsByCur[_txIdSha3] == 0); totalWei = safeAdd(totalWei, _amountWei); require(totalWei <= maxCapWei); // Max cap should not be reached yet. require(token.sell(_buyer, _tokensE18)); // Transfer tokens to buyer. totalTokensSold = safeAdd(totalTokensSold, _tokensE18); totalExternalSales++; txsByCur[_txIdSha3] = _tokensE18; ExternalSaleSha3(_currency, _txIdSha3, _buyer, _amountWei, _tokensE18); } // Get id of currency enum. -------------------------------------------- function btcId() public constant returns (uint8) { return uint8(Currency.BTC); } function ltcId() public constant returns (uint8) { return uint8(Currency.LTC); } function zecId() public constant returns (uint8) { return uint8(Currency.ZEC); } function dashId() public constant returns (uint8) { return uint8(Currency.DASH); } function wavesId() public constant returns (uint8) { return uint8(Currency.WAVES); } function usdId() public constant returns (uint8) { return uint8(Currency.USD); } function eurId() public constant returns (uint8) { return uint8(Currency.EUR); } // Get token count by transaction id. ---------------------------------- function _tokensByTx(Currency _currency, string _txId) internal constant returns (uint256) { return tokensByTx(uint8(_currency), _txId); } function tokensByTx(uint8 _currency, string _txId) public constant returns (uint256) { return externalTxs[_currency][keccak256(_txId)]; } function tokensByBtcTx(string _txId) public constant returns (uint256) { return _tokensByTx(Currency.BTC, _txId); } function tokensByLtcTx(string _txId) public constant returns (uint256) { return _tokensByTx(Currency.LTC, _txId); } function tokensByZecTx(string _txId) public constant returns (uint256) { return _tokensByTx(Currency.ZEC, _txId); } function tokensByDashTx(string _txId) public constant returns (uint256) { return _tokensByTx(Currency.DASH, _txId); } function tokensByWavesTx(string _txId) public constant returns (uint256) { return _tokensByTx(Currency.WAVES, _txId); } function tokensByUsdTx(string _txId) public constant returns (uint256) { return _tokensByTx(Currency.USD, _txId); } function tokensByEurTx(string _txId) public constant returns (uint256) { return _tokensByTx(Currency.EUR, _txId); } // End of external sales. //---------------------------------------------------------------------- function totalSales() public constant returns (uint256) { return safeAdd(totalEthSales, totalExternalSales); } function isMaxCapReached() public constant returns (bool) { return totalWei >= maxCapWei; } function isSaleOn() public constant returns (bool) { uint _now = getNow(); return startTime <= _now && _now <= endTime; } function isSaleOver() public constant returns (bool) { return getNow() > endTime; } function isFinalized() public constant returns (bool) { return finalizedTime > 0; } /* * Finalize the crowdsale. Raised money can be sent to beneficiary only if crowdsale hit end time or max cap (15m USD). */ function finalize() public onlyOwner { // Cannot finalise before end day of crowdsale until max cap is reached. require(isMaxCapReached() || isSaleOver()); beneficiary.transfer(this.balance); finalizedTime = getNow(); } }
if (saleEnabled) sellTokensForEth(msg.sender, msg.value);
function() public payable
/* * The fallback function corresponds to a donation in ETH */ function() public payable
57362
UniswapPriceOracleV2
currentCumulativePrice
contract UniswapPriceOracleV2 is UniswapConfig { using FixedPoint for *; /// @notice The number of wei in 1 ETH uint public constant ethBaseUnit = 1e18; uint public constant usdtBaseUnit = 1e6; /// @notice A common scaling factor to maintain precision uint public constant expScale = 1e18; /// @notice The minimum amount of time in seconds required for the old uniswap price accumulator to be replaced uint public immutable anchorPeriod; /// @notice Official prices by symbol hash mapping(bytes32 => uint) public prices; /// @notice The old observation for each symbolHash mapping(bytes32 => Observation) public oldObservations; /// @notice The new observation for each symbolHash mapping(bytes32 => Observation) public newObservations; /// @notice The event emitted when new prices are posted but the stored price is not updated due to the anchor event PriceGuarded(string symbol, uint reporter, uint anchor); /// @notice The event emitted when the stored price is updated event PriceUpdated(string symbol, uint price); /// @notice The event emitted when anchor price is updated event AnchorPriceUpdated(string symbol, uint anchorPrice, uint oldTimestamp, uint newTimestamp); /// @notice The event emitted when the uniswap window changes event UniswapWindowUpdated(bytes32 indexed symbolHash, uint oldTimestamp, uint newTimestamp, uint oldPrice, uint newPrice); bytes32 constant ethHash = keccak256(abi.encodePacked("ETH")); constructor(uint anchorPeriod_, address[] memory gTokens_, address[] memory underlyings_, bytes32[] memory symbolHashs_, uint256[] memory baseUints_, PriceSource[] memory priceSources_, uint256[] memory fixedPrices_, address[] memory uniswapMarkets_, bool[] memory isPrice1FromUniswapArray_) UniswapConfig(gTokens_, underlyings_, symbolHashs_, baseUints_, priceSources_, fixedPrices_, uniswapMarkets_, isPrice1FromUniswapArray_) public { anchorPeriod = anchorPeriod_; for (uint i = 0; i < gTokens_.length; i++) { TokenConfig memory config = TokenConfig({ gToken : gTokens_[i], underlying : underlyings_[i], symbolHash : symbolHashs_[i], baseUnit : baseUints_[i], priceSource: priceSources_[i], fixedPrice: fixedPrices_[i], uniswapMarket : uniswapMarkets_[i], isPrice1FromUniswap : isPrice1FromUniswapArray_[i] }); require(config.baseUnit > 0, "baseUnit must be greater than zero"); address uniswapMarket = config.uniswapMarket; require(config.priceSource == PriceSource.FIXED_USD || config.priceSource == PriceSource.REPORTER_USD || config.priceSource == PriceSource.REPORTER_ETH, "unsupported PriceSource type"); if (config.priceSource == PriceSource.REPORTER_ETH || config.priceSource == PriceSource.REPORTER_USD) { require(uniswapMarket != address(0), "reported prices must have an anchor"); bytes32 symbolHash = config.symbolHash; uint cumulativePrice = currentCumulativePrice(config); oldObservations[symbolHash].timestamp = block.timestamp; newObservations[symbolHash].timestamp = block.timestamp; oldObservations[symbolHash].acc = cumulativePrice; newObservations[symbolHash].acc = cumulativePrice; emit UniswapWindowUpdated(symbolHash, block.timestamp, block.timestamp, cumulativePrice, cumulativePrice); } else { require(uniswapMarket == address(0), "only reported prices utilize an anchor"); } } } /** * @notice Get the official price for a symbol * @param symbol The symbol to fetch the price of * @return Price denominated in USD, with 6 decimals */ function price(string calldata symbol) external view returns (uint) { TokenConfig memory config = getTokenConfigBySymbol(symbol); return priceInternal(config); } function priceInternal(TokenConfig memory config) internal view returns (uint) { if (config.priceSource == PriceSource.REPORTER_ETH || config.priceSource == PriceSource.REPORTER_USD) return prices[config.symbolHash]; if (config.priceSource == PriceSource.FIXED_USD) return config.fixedPrice; return 0; } /** * @notice Get the underlying price of a gToken * @dev Implements the PriceOracle interface for Compound v2. * @param gToken The gToken address for price retrieval * @return Price denominated in USD, with 18 decimals, for the given gToken address */ function getUnderlyingPrice(address gToken) external view returns (uint) { TokenConfig memory config = getTokenConfigByCToken(gToken); // Comptroller needs prices in the format: ${raw price} * 1e(36 - baseUnit) // Since the prices in this view have 6 decimals, we must scale them by 1e(36 - 6 - baseUnit) return mul(1e30, priceInternal(config)) / config.baseUnit; } function refresh(string[] calldata symbols) external { uint ethPrice = fetchEthPrice(); // Try to update the view storage for (uint i = 0; i < symbols.length; i++) { postPriceInternal(symbols[i], ethPrice); } } function postPriceInternal(string memory symbol, uint ethPrice) internal { TokenConfig memory config = getTokenConfigBySymbol(symbol); bytes32 symbolHash = keccak256(abi.encodePacked(symbol)); uint anchorPrice; if (symbolHash == ethHash) { anchorPrice = ethPrice; } else if (config.priceSource == PriceSource.REPORTER_ETH){ anchorPrice = fetchAnchorPriceETH(symbol, config, ethPrice); } else if(config.priceSource == PriceSource.REPORTER_USD) { anchorPrice = fetchAnchorPriceUSD(symbol, config); } else{ revert("wrong config.priceSource"); } prices[symbolHash] = anchorPrice; emit PriceUpdated(symbol, anchorPrice); } /** * @dev Fetches the current token/eth price accumulator from uniswap. */ function currentCumulativePrice(TokenConfig memory config) internal view returns (uint) {<FILL_FUNCTION_BODY> } /** * @dev Fetches the current eth/usd price from dex swap, with 6 decimals of precision. * Conversion factor is 1e18 for eth/usdc market, since we decode uniswap price statically with 18 decimals. */ function fetchEthPrice() internal returns (uint) { return fetchAnchorPriceUSD("ETH", getTokenConfigBySymbolHash(ethHash)); } /** * price as usd = token/eth price * eth price * * @dev Fetches the current token usd price from dex swap, with 6 decimals of precision. * @param ethPrice : with 6 decimals of precision */ function fetchAnchorPriceETH(string memory symbol, TokenConfig memory config, uint ethPrice) internal virtual returns (uint) { (uint nowCumulativePrice, uint oldCumulativePrice, uint oldTimestamp) = pokeWindowValues(config); // This should be impossible, but better safe than sorry require(block.timestamp > oldTimestamp, "now must come after before"); uint timeElapsed = block.timestamp - oldTimestamp; // Calculate uniswap time-weighted average price // Underflow is a property of the accumulators: https://uniswap.org/audit.html#orgc9b3190 FixedPoint.uq112x112 memory priceAverage = FixedPoint.uq112x112(uint224((nowCumulativePrice - oldCumulativePrice) / timeElapsed)); uint rawUniswapPriceMantissa = priceAverage.decode112with18(); uint unscaledPriceMantissa = mul(rawUniswapPriceMantissa, ethPrice); uint anchorPrice = mul(unscaledPriceMantissa, config.baseUnit) / ethBaseUnit / expScale; emit AnchorPriceUpdated(symbol, anchorPrice, oldTimestamp, block.timestamp); return anchorPrice; } /** * @dev Fetches the current token/usd stable coin price from dex swap, with 6 decimals of precision. */ function fetchAnchorPriceUSD(string memory symbol, TokenConfig memory config) internal virtual returns (uint) { (uint nowCumulativePrice, uint oldCumulativePrice, uint oldTimestamp) = pokeWindowValues(config); // This should be impossible, but better safe than sorry require(block.timestamp > oldTimestamp, "now must come after before"); uint timeElapsed = block.timestamp - oldTimestamp; // Calculate uniswap time-weighted average price // Underflow is a property of the accumulators: https://uniswap.org/audit.html#orgc9b3190 FixedPoint.uq112x112 memory priceAverage = FixedPoint.uq112x112(uint224((nowCumulativePrice - oldCumulativePrice) / timeElapsed)); uint rawUniswapPriceMantissa = priceAverage.decode112with18(); uint unscaledPriceMantissa = mul(rawUniswapPriceMantissa, config.baseUnit); //uint anchorPrice = mul(unscaledPriceMantissa , 1e6) / usdtBaseUnit / expScale; // usdtBaseUnit == 1e6, // so , anchorPrice = unscaledPriceMantissa / expScale uint anchorPrice = unscaledPriceMantissa / expScale; emit AnchorPriceUpdated(symbol, anchorPrice, oldTimestamp, block.timestamp); return anchorPrice; } /** * @dev Get time-weighted average prices for a token at the current timestamp. * Update new and old observations of lagging window if period elapsed. */ function pokeWindowValues(TokenConfig memory config) internal returns (uint, uint, uint) { bytes32 symbolHash = config.symbolHash; uint cumulativePrice = currentCumulativePrice(config); Observation memory newObservation = newObservations[symbolHash]; // Update new and old observations if elapsed time is greater than or equal to anchor period uint timeElapsed = block.timestamp - newObservation.timestamp; if (timeElapsed >= anchorPeriod) { oldObservations[symbolHash].timestamp = newObservation.timestamp; oldObservations[symbolHash].acc = newObservation.acc; newObservations[symbolHash].timestamp = block.timestamp; newObservations[symbolHash].acc = cumulativePrice; emit UniswapWindowUpdated(config.symbolHash, newObservation.timestamp, block.timestamp, newObservation.acc, cumulativePrice); } return (cumulativePrice, oldObservations[symbolHash].acc, oldObservations[symbolHash].timestamp); } /** * @notice Recovers the source address which signed a message * @dev Comparing to a claimed address would add nothing, * as the caller could simply perform the recover and claim that address. * @param message The data that was presumably signed * @param signature The fingerprint of the data + private key * @return The source address which signed the message, presumably */ function source(bytes memory message, bytes memory signature) public pure returns (address) { (bytes32 r, bytes32 s, uint8 v) = abi.decode(signature, (bytes32, bytes32, uint8)); bytes32 hash = keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", keccak256(message))); return ecrecover(hash, v, r, s); } /// @dev Overflow proof multiplication function mul(uint a, uint b) internal pure returns (uint) { if (a == 0) return 0; uint c = a * b; require(c / a == b, "multiplication overflow"); return c; } // get market USD price from dex with 6 decimal // for web only , not for lend contract function getMarketPrice(string calldata symbol) external view returns (uint) { TokenConfig memory config = getTokenConfigBySymbol(symbol); uint marketPrice = 0; if(config.priceSource == PriceSource.FIXED_USD){ // Fixed price marketPrice = config.fixedPrice; }else if(config.priceSource == PriceSource.REPORTER_ETH){ // For ETH, it is divided into two steps, first calculate the pair of ETH, // and then convert it into USD, and USD decimal is 6 bits uint ethPrice = fetchMarketPriceByUsdtPair(getTokenConfigBySymbolHash(ethHash)); marketPrice = fetchMarketPriceByEthPair(config, ethPrice); }else if(config.priceSource == PriceSource.REPORTER_USD){ // For USD marketPrice = fetchMarketPriceByUsdtPair(config); } return marketPrice; } // fetch Token/WETH market price as USD with 6 decimal function fetchMarketPriceByEthPair(TokenConfig memory config, uint ethPrice) internal view virtual returns (uint) { uint marketPrice = 0; (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast) = IUniswapV2Pair(config.uniswapMarket).getReserves(); if(config.isPrice1FromUniswap){ if(reserve1 != 0){ // price = (reserve0 / ethBaseUnit) / (reserve1 / config.baseUnit) * ethPrice; // reserve0 is WETH, reserve1 is gtoken // Multiply before divide bigNumber marketPrice = mul(mul(reserve0, config.baseUnit), ethPrice) / ethBaseUnit / reserve1; } }else{ if(reserve0 != 0){ // price = (reserve1 / ethBaseUnit) / (reserve0 / config.baseUnit) * ethPrice; // reserve1 is WETH, reserve0 is gtoken marketPrice = mul(mul(reserve1, config.baseUnit), ethPrice) / ethBaseUnit / reserve0; } } return marketPrice; } function fetchMarketPriceByUsdtPair(TokenConfig memory config) internal view virtual returns (uint) { uint marketPrice = 0; (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast) = IUniswapV2Pair(config.uniswapMarket).getReserves(); if(config.isPrice1FromUniswap){ if(reserve1 != 0){ // price = (reserve0 / usdtBaseUnit) / (reserve1 / config.baseUnit) * 1e6; // price = reserve0 * config.baseUnit * 1e6 / usdtBaseUnit / reserve1; // reserve0 is USDT, reserve1 is underlying Token marketPrice = mul(mul(reserve0, config.baseUnit), 1e6) / usdtBaseUnit / reserve1; } }else{ if(reserve0 != 0){ // price = (reserve1 / usdtBaseUnit) / (reserve0 / config.baseUnit) * 1e6; // price = reserve1 * config.baseUnit * 1e6 / usdtBaseUnit / reserve0; // reserve1 is USDT, reserve0 is underlying Token marketPrice = mul(mul(reserve1, config.baseUnit), 1e6) / usdtBaseUnit / reserve0; } } return marketPrice; } }
contract UniswapPriceOracleV2 is UniswapConfig { using FixedPoint for *; /// @notice The number of wei in 1 ETH uint public constant ethBaseUnit = 1e18; uint public constant usdtBaseUnit = 1e6; /// @notice A common scaling factor to maintain precision uint public constant expScale = 1e18; /// @notice The minimum amount of time in seconds required for the old uniswap price accumulator to be replaced uint public immutable anchorPeriod; /// @notice Official prices by symbol hash mapping(bytes32 => uint) public prices; /// @notice The old observation for each symbolHash mapping(bytes32 => Observation) public oldObservations; /// @notice The new observation for each symbolHash mapping(bytes32 => Observation) public newObservations; /// @notice The event emitted when new prices are posted but the stored price is not updated due to the anchor event PriceGuarded(string symbol, uint reporter, uint anchor); /// @notice The event emitted when the stored price is updated event PriceUpdated(string symbol, uint price); /// @notice The event emitted when anchor price is updated event AnchorPriceUpdated(string symbol, uint anchorPrice, uint oldTimestamp, uint newTimestamp); /// @notice The event emitted when the uniswap window changes event UniswapWindowUpdated(bytes32 indexed symbolHash, uint oldTimestamp, uint newTimestamp, uint oldPrice, uint newPrice); bytes32 constant ethHash = keccak256(abi.encodePacked("ETH")); constructor(uint anchorPeriod_, address[] memory gTokens_, address[] memory underlyings_, bytes32[] memory symbolHashs_, uint256[] memory baseUints_, PriceSource[] memory priceSources_, uint256[] memory fixedPrices_, address[] memory uniswapMarkets_, bool[] memory isPrice1FromUniswapArray_) UniswapConfig(gTokens_, underlyings_, symbolHashs_, baseUints_, priceSources_, fixedPrices_, uniswapMarkets_, isPrice1FromUniswapArray_) public { anchorPeriod = anchorPeriod_; for (uint i = 0; i < gTokens_.length; i++) { TokenConfig memory config = TokenConfig({ gToken : gTokens_[i], underlying : underlyings_[i], symbolHash : symbolHashs_[i], baseUnit : baseUints_[i], priceSource: priceSources_[i], fixedPrice: fixedPrices_[i], uniswapMarket : uniswapMarkets_[i], isPrice1FromUniswap : isPrice1FromUniswapArray_[i] }); require(config.baseUnit > 0, "baseUnit must be greater than zero"); address uniswapMarket = config.uniswapMarket; require(config.priceSource == PriceSource.FIXED_USD || config.priceSource == PriceSource.REPORTER_USD || config.priceSource == PriceSource.REPORTER_ETH, "unsupported PriceSource type"); if (config.priceSource == PriceSource.REPORTER_ETH || config.priceSource == PriceSource.REPORTER_USD) { require(uniswapMarket != address(0), "reported prices must have an anchor"); bytes32 symbolHash = config.symbolHash; uint cumulativePrice = currentCumulativePrice(config); oldObservations[symbolHash].timestamp = block.timestamp; newObservations[symbolHash].timestamp = block.timestamp; oldObservations[symbolHash].acc = cumulativePrice; newObservations[symbolHash].acc = cumulativePrice; emit UniswapWindowUpdated(symbolHash, block.timestamp, block.timestamp, cumulativePrice, cumulativePrice); } else { require(uniswapMarket == address(0), "only reported prices utilize an anchor"); } } } /** * @notice Get the official price for a symbol * @param symbol The symbol to fetch the price of * @return Price denominated in USD, with 6 decimals */ function price(string calldata symbol) external view returns (uint) { TokenConfig memory config = getTokenConfigBySymbol(symbol); return priceInternal(config); } function priceInternal(TokenConfig memory config) internal view returns (uint) { if (config.priceSource == PriceSource.REPORTER_ETH || config.priceSource == PriceSource.REPORTER_USD) return prices[config.symbolHash]; if (config.priceSource == PriceSource.FIXED_USD) return config.fixedPrice; return 0; } /** * @notice Get the underlying price of a gToken * @dev Implements the PriceOracle interface for Compound v2. * @param gToken The gToken address for price retrieval * @return Price denominated in USD, with 18 decimals, for the given gToken address */ function getUnderlyingPrice(address gToken) external view returns (uint) { TokenConfig memory config = getTokenConfigByCToken(gToken); // Comptroller needs prices in the format: ${raw price} * 1e(36 - baseUnit) // Since the prices in this view have 6 decimals, we must scale them by 1e(36 - 6 - baseUnit) return mul(1e30, priceInternal(config)) / config.baseUnit; } function refresh(string[] calldata symbols) external { uint ethPrice = fetchEthPrice(); // Try to update the view storage for (uint i = 0; i < symbols.length; i++) { postPriceInternal(symbols[i], ethPrice); } } function postPriceInternal(string memory symbol, uint ethPrice) internal { TokenConfig memory config = getTokenConfigBySymbol(symbol); bytes32 symbolHash = keccak256(abi.encodePacked(symbol)); uint anchorPrice; if (symbolHash == ethHash) { anchorPrice = ethPrice; } else if (config.priceSource == PriceSource.REPORTER_ETH){ anchorPrice = fetchAnchorPriceETH(symbol, config, ethPrice); } else if(config.priceSource == PriceSource.REPORTER_USD) { anchorPrice = fetchAnchorPriceUSD(symbol, config); } else{ revert("wrong config.priceSource"); } prices[symbolHash] = anchorPrice; emit PriceUpdated(symbol, anchorPrice); } <FILL_FUNCTION> /** * @dev Fetches the current eth/usd price from dex swap, with 6 decimals of precision. * Conversion factor is 1e18 for eth/usdc market, since we decode uniswap price statically with 18 decimals. */ function fetchEthPrice() internal returns (uint) { return fetchAnchorPriceUSD("ETH", getTokenConfigBySymbolHash(ethHash)); } /** * price as usd = token/eth price * eth price * * @dev Fetches the current token usd price from dex swap, with 6 decimals of precision. * @param ethPrice : with 6 decimals of precision */ function fetchAnchorPriceETH(string memory symbol, TokenConfig memory config, uint ethPrice) internal virtual returns (uint) { (uint nowCumulativePrice, uint oldCumulativePrice, uint oldTimestamp) = pokeWindowValues(config); // This should be impossible, but better safe than sorry require(block.timestamp > oldTimestamp, "now must come after before"); uint timeElapsed = block.timestamp - oldTimestamp; // Calculate uniswap time-weighted average price // Underflow is a property of the accumulators: https://uniswap.org/audit.html#orgc9b3190 FixedPoint.uq112x112 memory priceAverage = FixedPoint.uq112x112(uint224((nowCumulativePrice - oldCumulativePrice) / timeElapsed)); uint rawUniswapPriceMantissa = priceAverage.decode112with18(); uint unscaledPriceMantissa = mul(rawUniswapPriceMantissa, ethPrice); uint anchorPrice = mul(unscaledPriceMantissa, config.baseUnit) / ethBaseUnit / expScale; emit AnchorPriceUpdated(symbol, anchorPrice, oldTimestamp, block.timestamp); return anchorPrice; } /** * @dev Fetches the current token/usd stable coin price from dex swap, with 6 decimals of precision. */ function fetchAnchorPriceUSD(string memory symbol, TokenConfig memory config) internal virtual returns (uint) { (uint nowCumulativePrice, uint oldCumulativePrice, uint oldTimestamp) = pokeWindowValues(config); // This should be impossible, but better safe than sorry require(block.timestamp > oldTimestamp, "now must come after before"); uint timeElapsed = block.timestamp - oldTimestamp; // Calculate uniswap time-weighted average price // Underflow is a property of the accumulators: https://uniswap.org/audit.html#orgc9b3190 FixedPoint.uq112x112 memory priceAverage = FixedPoint.uq112x112(uint224((nowCumulativePrice - oldCumulativePrice) / timeElapsed)); uint rawUniswapPriceMantissa = priceAverage.decode112with18(); uint unscaledPriceMantissa = mul(rawUniswapPriceMantissa, config.baseUnit); //uint anchorPrice = mul(unscaledPriceMantissa , 1e6) / usdtBaseUnit / expScale; // usdtBaseUnit == 1e6, // so , anchorPrice = unscaledPriceMantissa / expScale uint anchorPrice = unscaledPriceMantissa / expScale; emit AnchorPriceUpdated(symbol, anchorPrice, oldTimestamp, block.timestamp); return anchorPrice; } /** * @dev Get time-weighted average prices for a token at the current timestamp. * Update new and old observations of lagging window if period elapsed. */ function pokeWindowValues(TokenConfig memory config) internal returns (uint, uint, uint) { bytes32 symbolHash = config.symbolHash; uint cumulativePrice = currentCumulativePrice(config); Observation memory newObservation = newObservations[symbolHash]; // Update new and old observations if elapsed time is greater than or equal to anchor period uint timeElapsed = block.timestamp - newObservation.timestamp; if (timeElapsed >= anchorPeriod) { oldObservations[symbolHash].timestamp = newObservation.timestamp; oldObservations[symbolHash].acc = newObservation.acc; newObservations[symbolHash].timestamp = block.timestamp; newObservations[symbolHash].acc = cumulativePrice; emit UniswapWindowUpdated(config.symbolHash, newObservation.timestamp, block.timestamp, newObservation.acc, cumulativePrice); } return (cumulativePrice, oldObservations[symbolHash].acc, oldObservations[symbolHash].timestamp); } /** * @notice Recovers the source address which signed a message * @dev Comparing to a claimed address would add nothing, * as the caller could simply perform the recover and claim that address. * @param message The data that was presumably signed * @param signature The fingerprint of the data + private key * @return The source address which signed the message, presumably */ function source(bytes memory message, bytes memory signature) public pure returns (address) { (bytes32 r, bytes32 s, uint8 v) = abi.decode(signature, (bytes32, bytes32, uint8)); bytes32 hash = keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", keccak256(message))); return ecrecover(hash, v, r, s); } /// @dev Overflow proof multiplication function mul(uint a, uint b) internal pure returns (uint) { if (a == 0) return 0; uint c = a * b; require(c / a == b, "multiplication overflow"); return c; } // get market USD price from dex with 6 decimal // for web only , not for lend contract function getMarketPrice(string calldata symbol) external view returns (uint) { TokenConfig memory config = getTokenConfigBySymbol(symbol); uint marketPrice = 0; if(config.priceSource == PriceSource.FIXED_USD){ // Fixed price marketPrice = config.fixedPrice; }else if(config.priceSource == PriceSource.REPORTER_ETH){ // For ETH, it is divided into two steps, first calculate the pair of ETH, // and then convert it into USD, and USD decimal is 6 bits uint ethPrice = fetchMarketPriceByUsdtPair(getTokenConfigBySymbolHash(ethHash)); marketPrice = fetchMarketPriceByEthPair(config, ethPrice); }else if(config.priceSource == PriceSource.REPORTER_USD){ // For USD marketPrice = fetchMarketPriceByUsdtPair(config); } return marketPrice; } // fetch Token/WETH market price as USD with 6 decimal function fetchMarketPriceByEthPair(TokenConfig memory config, uint ethPrice) internal view virtual returns (uint) { uint marketPrice = 0; (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast) = IUniswapV2Pair(config.uniswapMarket).getReserves(); if(config.isPrice1FromUniswap){ if(reserve1 != 0){ // price = (reserve0 / ethBaseUnit) / (reserve1 / config.baseUnit) * ethPrice; // reserve0 is WETH, reserve1 is gtoken // Multiply before divide bigNumber marketPrice = mul(mul(reserve0, config.baseUnit), ethPrice) / ethBaseUnit / reserve1; } }else{ if(reserve0 != 0){ // price = (reserve1 / ethBaseUnit) / (reserve0 / config.baseUnit) * ethPrice; // reserve1 is WETH, reserve0 is gtoken marketPrice = mul(mul(reserve1, config.baseUnit), ethPrice) / ethBaseUnit / reserve0; } } return marketPrice; } function fetchMarketPriceByUsdtPair(TokenConfig memory config) internal view virtual returns (uint) { uint marketPrice = 0; (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast) = IUniswapV2Pair(config.uniswapMarket).getReserves(); if(config.isPrice1FromUniswap){ if(reserve1 != 0){ // price = (reserve0 / usdtBaseUnit) / (reserve1 / config.baseUnit) * 1e6; // price = reserve0 * config.baseUnit * 1e6 / usdtBaseUnit / reserve1; // reserve0 is USDT, reserve1 is underlying Token marketPrice = mul(mul(reserve0, config.baseUnit), 1e6) / usdtBaseUnit / reserve1; } }else{ if(reserve0 != 0){ // price = (reserve1 / usdtBaseUnit) / (reserve0 / config.baseUnit) * 1e6; // price = reserve1 * config.baseUnit * 1e6 / usdtBaseUnit / reserve0; // reserve1 is USDT, reserve0 is underlying Token marketPrice = mul(mul(reserve1, config.baseUnit), 1e6) / usdtBaseUnit / reserve0; } } return marketPrice; } }
(uint cumulativePrice0, uint cumulativePrice1,) = UniswapV2OracleLibrary.currentCumulativePrices(config.uniswapMarket); if (config.isPrice1FromUniswap) { return cumulativePrice1; } else { return cumulativePrice0; }
function currentCumulativePrice(TokenConfig memory config) internal view returns (uint)
/** * @dev Fetches the current token/eth price accumulator from uniswap. */ function currentCumulativePrice(TokenConfig memory config) internal view returns (uint)
66375
SHE
approve
contract SHE is ERC20 { using SafeMath for uint256; address owner = msg.sender; mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; mapping (address => bool) public blacklist; string public constant name = "SHE"; string public constant symbol = "SHE"; uint public constant decimals = 18; uint256 public totalSupply = 1000000000e18; uint256 public totalDistributed = 700000000e18; uint256 public totalRemaining = totalSupply.sub(totalDistributed); uint256 public value = 8000e18; 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 Burn(address indexed burner, uint256 value); bool public distributionFinished = false; modifier canDistr() { require(!distributionFinished); _; } modifier onlyOwner() { require(msg.sender == owner); _; } modifier onlyWhitelist() { require(blacklist[msg.sender] == false); _; } modifier valueAccepted() { require(msg.value%(1*10**16)==0); // 0.01 _; } constructor() public { owner = msg.sender; balances[owner] = totalDistributed; } function transferOwnership(address newOwner) onlyOwner public { if (newOwner != address(0)) { owner = newOwner; } } function finishDistribution() onlyOwner canDistr public returns (bool) { distributionFinished = true; emit DistrFinished(); return true; } function distr(address _to, uint256 _amount) canDistr private returns (bool) { totalDistributed = totalDistributed.add(_amount); totalRemaining = totalRemaining.sub(_amount); balances[_to] = balances[_to].add(_amount); emit Distr(_to, _amount); emit Transfer(address(0), _to, _amount); return true; if (totalDistributed >= totalSupply) { distributionFinished = true; } } function () external payable { getTokens(); } function getTokens() payable canDistr onlyWhitelist valueAccepted public { if (value > totalRemaining) { value = totalRemaining; } require(value <= totalRemaining); address investor = msg.sender; uint256 toGive = value; distr(investor, toGive); if (toGive > 0) { blacklist[investor] = true; } if (totalDistributed >= totalSupply) { distributionFinished = true; } value = value.div(100000).mul(99999); uint256 etherBalance = this.balance; if (etherBalance > 0) { owner.transfer(etherBalance); } } function balanceOf(address _owner) constant public returns (uint256) { return balances[_owner]; } 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) {<FILL_FUNCTION_BODY> } function allowance(address _owner, address _spender) constant public returns (uint256) { return allowed[_owner][_spender]; } function getTokenBalance(address tokenAddress, address who) constant public returns (uint){ ForeignToken t = ForeignToken(tokenAddress); uint bal = t.balanceOf(who); return bal; } function withdraw() onlyOwner public { uint256 etherBalance = address(this).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 withdrawForeignTokens(address _tokenContract) onlyOwner public returns (bool) { ForeignToken token = ForeignToken(_tokenContract); uint256 amount = token.balanceOf(address(this)); return token.transfer(owner, amount); } }
contract SHE is ERC20 { using SafeMath for uint256; address owner = msg.sender; mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; mapping (address => bool) public blacklist; string public constant name = "SHE"; string public constant symbol = "SHE"; uint public constant decimals = 18; uint256 public totalSupply = 1000000000e18; uint256 public totalDistributed = 700000000e18; uint256 public totalRemaining = totalSupply.sub(totalDistributed); uint256 public value = 8000e18; 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 Burn(address indexed burner, uint256 value); bool public distributionFinished = false; modifier canDistr() { require(!distributionFinished); _; } modifier onlyOwner() { require(msg.sender == owner); _; } modifier onlyWhitelist() { require(blacklist[msg.sender] == false); _; } modifier valueAccepted() { require(msg.value%(1*10**16)==0); // 0.01 _; } constructor() public { owner = msg.sender; balances[owner] = totalDistributed; } function transferOwnership(address newOwner) onlyOwner public { if (newOwner != address(0)) { owner = newOwner; } } function finishDistribution() onlyOwner canDistr public returns (bool) { distributionFinished = true; emit DistrFinished(); return true; } function distr(address _to, uint256 _amount) canDistr private returns (bool) { totalDistributed = totalDistributed.add(_amount); totalRemaining = totalRemaining.sub(_amount); balances[_to] = balances[_to].add(_amount); emit Distr(_to, _amount); emit Transfer(address(0), _to, _amount); return true; if (totalDistributed >= totalSupply) { distributionFinished = true; } } function () external payable { getTokens(); } function getTokens() payable canDistr onlyWhitelist valueAccepted public { if (value > totalRemaining) { value = totalRemaining; } require(value <= totalRemaining); address investor = msg.sender; uint256 toGive = value; distr(investor, toGive); if (toGive > 0) { blacklist[investor] = true; } if (totalDistributed >= totalSupply) { distributionFinished = true; } value = value.div(100000).mul(99999); uint256 etherBalance = this.balance; if (etherBalance > 0) { owner.transfer(etherBalance); } } function balanceOf(address _owner) constant public returns (uint256) { return balances[_owner]; } 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; } <FILL_FUNCTION> function allowance(address _owner, address _spender) constant public returns (uint256) { return allowed[_owner][_spender]; } function getTokenBalance(address tokenAddress, address who) constant public returns (uint){ ForeignToken t = ForeignToken(tokenAddress); uint bal = t.balanceOf(who); return bal; } function withdraw() onlyOwner public { uint256 etherBalance = address(this).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 withdrawForeignTokens(address _tokenContract) onlyOwner public returns (bool) { ForeignToken token = ForeignToken(_tokenContract); uint256 amount = token.balanceOf(address(this)); return token.transfer(owner, amount); } }
if (_value != 0 && allowed[msg.sender][_spender] != 0) { return false; } allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true;
function approve(address _spender, uint256 _value) public returns (bool success)
function approve(address _spender, uint256 _value) public returns (bool success)
37662
Manageable
removeManager
contract Manageable is Ownable { address[] public managers; event ManagerAdded(address indexed manager); event ManagerRemoved(address indexed manager); modifier onlyManager() { require(isManager(msg.sender)); _; } function countManagers() view public returns(uint) { return managers.length; } function getManagers() view public returns(address[]) { return managers; } function isManager(address _manager) view public returns(bool) { for(uint i = 0; i < managers.length; i++) { if(managers[i] == _manager) { return true; } } return false; } function addManager(address _manager) onlyOwner public { require(_manager != address(0)); require(!isManager(_manager)); managers.push(_manager); emit ManagerAdded(_manager); } function removeManager(address _manager) onlyOwner public {<FILL_FUNCTION_BODY> } }
contract Manageable is Ownable { address[] public managers; event ManagerAdded(address indexed manager); event ManagerRemoved(address indexed manager); modifier onlyManager() { require(isManager(msg.sender)); _; } function countManagers() view public returns(uint) { return managers.length; } function getManagers() view public returns(address[]) { return managers; } function isManager(address _manager) view public returns(bool) { for(uint i = 0; i < managers.length; i++) { if(managers[i] == _manager) { return true; } } return false; } function addManager(address _manager) onlyOwner public { require(_manager != address(0)); require(!isManager(_manager)); managers.push(_manager); emit ManagerAdded(_manager); } <FILL_FUNCTION> }
uint index = managers.length; for(uint i = 0; i < managers.length; i++) { if(managers[i] == _manager) { index = i; } } if(index >= managers.length) revert(); for(; index < managers.length - 1; index++) { managers[index] = managers[index + 1]; } managers.length--; emit ManagerRemoved(_manager);
function removeManager(address _manager) onlyOwner public
function removeManager(address _manager) onlyOwner public
79915
Token
transferERC20Token
contract Token is StandardToken, SafeMath { // Time of the contract creation uint public creationTime; function Token() { creationTime = now; } /// @dev Owner can transfer out any accidentally sent ERC20 tokens function transferERC20Token(address tokenAddress) public onlyOwner returns (bool) {<FILL_FUNCTION_BODY> } /// @dev Multiplies the given number by 10^(decimals) function withDecimals(uint number, uint decimals) internal returns (uint) { return mul(number, pow(10, decimals)); } }
contract Token is StandardToken, SafeMath { // Time of the contract creation uint public creationTime; function Token() { creationTime = now; } <FILL_FUNCTION> /// @dev Multiplies the given number by 10^(decimals) function withDecimals(uint number, uint decimals) internal returns (uint) { return mul(number, pow(10, decimals)); } }
uint balance = AbstractToken(tokenAddress).balanceOf(this); return AbstractToken(tokenAddress).transfer(owner, balance);
function transferERC20Token(address tokenAddress) public onlyOwner returns (bool)
/// @dev Owner can transfer out any accidentally sent ERC20 tokens function transferERC20Token(address tokenAddress) public onlyOwner returns (bool)
69768
Primetama
_transferStandard
contract Primetama is Context, IERC20, Ownable { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _rOwned; mapping (address => uint256) private _tOwned; mapping (address => mapping (address => uint256)) private _allowances; mapping (address => bool) private _isExcludedFromFee; mapping(address => bool) private _isExcludedFromMaxTx; mapping (address => bool) private _isExcluded; address[] private _excluded; uint256 private constant MAX = ~uint256(0); uint256 private _tTotal = 100000000000000 * 10**9; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; string private _name = "PRIMETAMA"; string private _symbol = "PTAMA"; uint8 private _decimals = 9; uint256 public _taxFee = 1; uint256 private _previousTaxFee = _taxFee; uint256 public _devFee = 8; uint256 private _previousDevFee = _devFee; uint256 public _liquidityFee = 1; uint256 private _previousLiquidityFee = _liquidityFee; uint256 public maxTxAmount = _tTotal.mul(20).div(1000); // 2% address payable private _devWallet = payable(0x80b625ea44CAB6F8C0C0CBa059B6f9283afee665); IUniswapV2Router02 public uniswapV2Router; address public uniswapV2Pair; bool inSwapAndLiquify; bool public swapAndLiquifyEnabled = true; uint256 private minTokensBeforeSwap = 100000000000 * 10**9; event MinTokensBeforeSwapUpdated(uint256 minTokensBeforeSwap); event SwapAndLiquifyEnabledUpdated(bool enabled); event SwapAndLiquify( uint256 tokensSwapped, uint256 liquidityEthBalance, uint256 devEthBalance ); modifier lockTheSwap { inSwapAndLiquify = true; _; inSwapAndLiquify = false; } constructor () public { _rOwned[_msgSender()] = _rTotal; IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); // Create a uniswap pair for this new token uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); // set the rest of the contract variables uniswapV2Router = _uniswapV2Router; //exclude owner and this contract from fee _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; // internal exclude from max tx _isExcludedFromMaxTx[owner()] = true; _isExcludedFromMaxTx[address(this)] = true; emit Transfer(address(0), _msgSender(), _tTotal); } function setRouterAddress(address newRouter) public onlyOwner() { IUniswapV2Router02 _newUniswapRouter = IUniswapV2Router02(newRouter); uniswapV2Pair = IUniswapV2Factory(_newUniswapRouter.factory()).createPair(address(this), _newUniswapRouter.WETH()); uniswapV2Router = _newUniswapRouter; } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } function totalSupply() public view override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { if (_isExcluded[account]) return _tOwned[account]; return tokenFromReflection(_rOwned[account]); } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function isExcludedFromReward(address account) public view returns (bool) { return _isExcluded[account]; } function totalFees() public view returns (uint256) { return _tFeeTotal; } function deliver(uint256 tAmount) public { address sender = _msgSender(); require(!_isExcluded[sender], "Excluded addresses cannot call this function"); (uint256 rAmount,,,,,,) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rTotal = _rTotal.sub(rAmount); _tFeeTotal = _tFeeTotal.add(tAmount); } function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns(uint256) { require(tAmount <= _tTotal, "Amount must be less than supply"); if (!deductTransferFee) { (uint256 rAmount,,,,,,) = _getValues(tAmount); return rAmount; } else { (,uint256 rTransferAmount,,,,,) = _getValues(tAmount); return rTransferAmount; } } function tokenFromReflection(uint256 rAmount) public view returns(uint256) { require(rAmount <= _rTotal, "Amount must be less than total reflections"); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function excludeFromReward(address account) public onlyOwner() { require(!_isExcluded[account], "Account is already excluded"); if(_rOwned[account] > 0) { _tOwned[account] = tokenFromReflection(_rOwned[account]); } _isExcluded[account] = true; _excluded.push(account); } function includeInReward(address account) external onlyOwner() { require(_isExcluded[account], "Account is already excluded"); for (uint256 i = 0; i < _excluded.length; i++) { if (_excluded[i] == account) { _excluded[i] = _excluded[_excluded.length - 1]; _tOwned[account] = 0; _isExcluded[account] = false; _excluded.pop(); break; } } } function _approve(address owner, address spender, uint256 amount) private { require(owner != address(0)); require(spender != address(0)); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function expectedRewards(address _sender) external view returns(uint256){ uint256 _balance = address(this).balance; address sender = _sender; uint256 holdersBal = balanceOf(sender); uint totalExcludedBal; for (uint256 i = 0; i < _excluded.length; i++){ totalExcludedBal = balanceOf(_excluded[i]).add(totalExcludedBal); } uint256 rewards = holdersBal.mul(_balance).div(_tTotal.sub(balanceOf(uniswapV2Pair)).sub(totalExcludedBal)); return rewards; } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if ( !_isExcludedFromMaxTx[from] && !_isExcludedFromMaxTx[to] // by default false ) { require( amount <= maxTxAmount, "Transfer amount exceeds the maxTxAmount." ); } // is the token balance of this contract address over the min number of // tokens that we need to initiate a swap + liquidity lock? // also, don't get caught in a circular liquidity event. // also, don't swap & liquify if sender is uniswap pair. uint256 contractTokenBalance = balanceOf(address(this)); bool overMinTokenBalance = contractTokenBalance >= minTokensBeforeSwap; if ( overMinTokenBalance && !inSwapAndLiquify && from != uniswapV2Pair && swapAndLiquifyEnabled ) { // add liquidity swapAndLiquify(contractTokenBalance); } // indicates if fee should be deducted from transfer bool takeFee = true; // if any account belongs to _isExcludedFromFee account then remove the fee if(_isExcludedFromFee[from] || _isExcludedFromFee[to]){ takeFee = false; } // transfer amount, it will take tax, dev fee, liquidity fee _tokenTransfer(from, to, amount, takeFee); } function swapAndLiquify(uint256 contractTokenBalance) private lockTheSwap { // balance token fees based on variable percents uint256 totalRedirectTokenFee = _devFee.add(_liquidityFee); if (totalRedirectTokenFee == 0) return; uint256 liquidityTokenBalance = contractTokenBalance.mul(_liquidityFee).div(totalRedirectTokenFee); uint256 devTokenBalance = contractTokenBalance.mul(_devFee).div(totalRedirectTokenFee); // split the liquidity balance into halves uint256 halfLiquidity = liquidityTokenBalance.div(2); // capture the contract's current ETH balance. // this is so that we can capture exactly the amount of ETH that the // swap creates, and not make the fee events include any ETH that // has been manually sent to the contract uint256 initialBalance = address(this).balance; if (liquidityTokenBalance == 0 && devTokenBalance == 0) return; // swap tokens for ETH swapTokensForEth(devTokenBalance.add(halfLiquidity)); uint256 newBalance = address(this).balance.sub(initialBalance); if(newBalance > 0) { // rebalance ETH fees proportionally to half the liquidity uint256 totalRedirectEthFee = _devFee.add(_liquidityFee.div(2)); uint256 liquidityEthBalance = newBalance.mul(_liquidityFee.div(2)).div(totalRedirectEthFee); uint256 devEthBalance = newBalance.mul(_devFee).div(totalRedirectEthFee); // // for liquidity // add to uniswap // addLiquidity(halfLiquidity, liquidityEthBalance); // // for dev fee // send to the dev address // sendEthToDevAddress(devEthBalance); emit SwapAndLiquify(contractTokenBalance, liquidityEthBalance, devEthBalance); } } function sendEthToDevAddress(uint256 amount) private { _devWallet.transfer(amount); } function swapTokensForEth(uint256 tokenAmount) private { // generate the uniswap pair path of token -> weth address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); // make the swap uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, // accept any amount of ETH path, address(this), block.timestamp ); } function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { // approve token transfer to cover all possible scenarios _approve(address(this), address(uniswapV2Router), tokenAmount); // add the liquidity uniswapV2Router.addLiquidityETH{value: ethAmount} ( address(this), tokenAmount, 0, // slippage is unavoidable 0, // slippage is unavoidable owner(), block.timestamp ); } //this method is responsible for taking all fee, if takeFee is true function _tokenTransfer(address sender, address recipient, uint256 amount,bool takeFee) private { if(!takeFee) { removeAllFee(); } if (_isExcluded[sender] && !_isExcluded[recipient]) { _transferFromExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && _isExcluded[recipient]) { _transferToExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && !_isExcluded[recipient]) { _transferStandard(sender, recipient, amount); } else if (_isExcluded[sender] && _isExcluded[recipient]) { _transferBothExcluded(sender, recipient, amount); } else { _transferStandard(sender, recipient, amount); } if(!takeFee) { restoreAllFee(); } } function _transferStandard(address sender, address recipient, uint256 tAmount) private {<FILL_FUNCTION_BODY> } function _transferToExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tDev, uint256 tLiquidity) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _takeDev(tDev); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferFromExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tDev, uint256 tLiquidity) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _takeDev(tDev); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferBothExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tDev, uint256 tLiquidity) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _takeDev(tDev); _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, uint256) { (uint256 tTransferAmount, uint256 tFee, uint256 tDev, uint256 tLiquidity) = _getTValues(tAmount); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tDev, tLiquidity, _getRate()); return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tDev, tLiquidity); } function _getTValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256) { uint256 tFee = calculateTaxFee(tAmount); uint256 tDev = calculateDevFee(tAmount); uint256 tLiquidity = calculateLiquidityFee(tAmount); uint256 tTransferAmount = tAmount.sub(tFee).sub(tDev).sub(tLiquidity); return (tTransferAmount, tFee, tDev, tLiquidity); } function _getRValues(uint256 tAmount, uint256 tFee, uint256 tDev, uint256 tLiquidity, uint256 currentRate) private pure returns (uint256, uint256, uint256) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rDev = tDev.mul(currentRate); uint256 rLiquidity = tLiquidity.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee).sub(rDev).sub(rLiquidity); return (rAmount, rTransferAmount, rFee); } function _getRate() private view returns(uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply.div(tSupply); } function _getCurrentSupply() private view returns(uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; for (uint256 i = 0; i < _excluded.length; i++) { if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal); rSupply = rSupply.sub(_rOwned[_excluded[i]]); tSupply = tSupply.sub(_tOwned[_excluded[i]]); } if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } function _takeLiquidity(uint256 tLiquidity) private { uint256 currentRate = _getRate(); uint256 rLiquidity = tLiquidity.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rLiquidity); if(_isExcluded[address(this)]) { _tOwned[address(this)] = _tOwned[address(this)].add(tLiquidity); } } function _takeDev(uint256 tDev) private { uint256 currentRate = _getRate(); uint256 rDev = tDev.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rDev); if(_isExcluded[address(this)]) { _tOwned[address(this)] = _tOwned[address(this)].add(tDev); } } function calculateTaxFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_taxFee).div(100); } function calculateDevFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_devFee).div(100); } function calculateLiquidityFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_liquidityFee).div(100); } function removeAllFee() private { if(_taxFee == 0 && _devFee == 0 && _liquidityFee == 0) return; _previousTaxFee = _taxFee; _previousDevFee = _devFee; _previousLiquidityFee = _liquidityFee; _taxFee = 0; _devFee = 0; _liquidityFee = 0; } function restoreAllFee() private { _taxFee = _previousTaxFee; _devFee = _previousDevFee; _liquidityFee = _previousLiquidityFee; } function manualSwap() external onlyOwner() { uint256 contractBalance = balanceOf(address(this)); swapTokensForEth(contractBalance); } function manualSend() external onlyOwner() { uint256 contractEthBalance = address(this).balance; sendEthToDevAddress(contractEthBalance); } function isExcludedFromFee(address account) external view returns(bool) { return _isExcludedFromFee[account]; } function excludeFromFee(address account) external onlyOwner { _isExcludedFromFee[account] = true; } function includeInFee(address account) external onlyOwner { _isExcludedFromFee[account] = false; } // for 0.5% input 5, for 1% input 10 function setMaxTxPercent(uint256 newMaxTx) external onlyOwner { require(newMaxTx >= 5, "Max TX should be above 0.5%"); maxTxAmount = _tTotal.mul(newMaxTx).div(1000); } function setTaxFeePercent(uint256 taxFee) external onlyOwner() { require(taxFee <= 8, "Maximum fee limit is 8 percent"); _taxFee = taxFee; } function setDevFeePercent(uint256 devFee) external onlyOwner() { require(devFee <= 8, "Maximum fee limit is 8 percent"); _devFee = devFee; } function setLiquidityFeePercent(uint256 liquidityFee) external onlyOwner() { require(liquidityFee <= 8, "Maximum fee limit is 8 percent"); _liquidityFee = liquidityFee; } function setSwapAndLiquifyEnabled(bool _enabled) external onlyOwner { swapAndLiquifyEnabled = _enabled; emit SwapAndLiquifyEnabledUpdated(_enabled); } function setMinTokensBeforeSwap(uint256 minTokens) external onlyOwner { minTokensBeforeSwap = minTokens * 10**9; emit MinTokensBeforeSwapUpdated(minTokens); } // to receive ETH from uniswapV2Router when swaping receive() external payable {} }
contract Primetama is Context, IERC20, Ownable { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _rOwned; mapping (address => uint256) private _tOwned; mapping (address => mapping (address => uint256)) private _allowances; mapping (address => bool) private _isExcludedFromFee; mapping(address => bool) private _isExcludedFromMaxTx; mapping (address => bool) private _isExcluded; address[] private _excluded; uint256 private constant MAX = ~uint256(0); uint256 private _tTotal = 100000000000000 * 10**9; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; string private _name = "PRIMETAMA"; string private _symbol = "PTAMA"; uint8 private _decimals = 9; uint256 public _taxFee = 1; uint256 private _previousTaxFee = _taxFee; uint256 public _devFee = 8; uint256 private _previousDevFee = _devFee; uint256 public _liquidityFee = 1; uint256 private _previousLiquidityFee = _liquidityFee; uint256 public maxTxAmount = _tTotal.mul(20).div(1000); // 2% address payable private _devWallet = payable(0x80b625ea44CAB6F8C0C0CBa059B6f9283afee665); IUniswapV2Router02 public uniswapV2Router; address public uniswapV2Pair; bool inSwapAndLiquify; bool public swapAndLiquifyEnabled = true; uint256 private minTokensBeforeSwap = 100000000000 * 10**9; event MinTokensBeforeSwapUpdated(uint256 minTokensBeforeSwap); event SwapAndLiquifyEnabledUpdated(bool enabled); event SwapAndLiquify( uint256 tokensSwapped, uint256 liquidityEthBalance, uint256 devEthBalance ); modifier lockTheSwap { inSwapAndLiquify = true; _; inSwapAndLiquify = false; } constructor () public { _rOwned[_msgSender()] = _rTotal; IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); // Create a uniswap pair for this new token uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); // set the rest of the contract variables uniswapV2Router = _uniswapV2Router; //exclude owner and this contract from fee _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; // internal exclude from max tx _isExcludedFromMaxTx[owner()] = true; _isExcludedFromMaxTx[address(this)] = true; emit Transfer(address(0), _msgSender(), _tTotal); } function setRouterAddress(address newRouter) public onlyOwner() { IUniswapV2Router02 _newUniswapRouter = IUniswapV2Router02(newRouter); uniswapV2Pair = IUniswapV2Factory(_newUniswapRouter.factory()).createPair(address(this), _newUniswapRouter.WETH()); uniswapV2Router = _newUniswapRouter; } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } function totalSupply() public view override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { if (_isExcluded[account]) return _tOwned[account]; return tokenFromReflection(_rOwned[account]); } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function isExcludedFromReward(address account) public view returns (bool) { return _isExcluded[account]; } function totalFees() public view returns (uint256) { return _tFeeTotal; } function deliver(uint256 tAmount) public { address sender = _msgSender(); require(!_isExcluded[sender], "Excluded addresses cannot call this function"); (uint256 rAmount,,,,,,) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rTotal = _rTotal.sub(rAmount); _tFeeTotal = _tFeeTotal.add(tAmount); } function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns(uint256) { require(tAmount <= _tTotal, "Amount must be less than supply"); if (!deductTransferFee) { (uint256 rAmount,,,,,,) = _getValues(tAmount); return rAmount; } else { (,uint256 rTransferAmount,,,,,) = _getValues(tAmount); return rTransferAmount; } } function tokenFromReflection(uint256 rAmount) public view returns(uint256) { require(rAmount <= _rTotal, "Amount must be less than total reflections"); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function excludeFromReward(address account) public onlyOwner() { require(!_isExcluded[account], "Account is already excluded"); if(_rOwned[account] > 0) { _tOwned[account] = tokenFromReflection(_rOwned[account]); } _isExcluded[account] = true; _excluded.push(account); } function includeInReward(address account) external onlyOwner() { require(_isExcluded[account], "Account is already excluded"); for (uint256 i = 0; i < _excluded.length; i++) { if (_excluded[i] == account) { _excluded[i] = _excluded[_excluded.length - 1]; _tOwned[account] = 0; _isExcluded[account] = false; _excluded.pop(); break; } } } function _approve(address owner, address spender, uint256 amount) private { require(owner != address(0)); require(spender != address(0)); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function expectedRewards(address _sender) external view returns(uint256){ uint256 _balance = address(this).balance; address sender = _sender; uint256 holdersBal = balanceOf(sender); uint totalExcludedBal; for (uint256 i = 0; i < _excluded.length; i++){ totalExcludedBal = balanceOf(_excluded[i]).add(totalExcludedBal); } uint256 rewards = holdersBal.mul(_balance).div(_tTotal.sub(balanceOf(uniswapV2Pair)).sub(totalExcludedBal)); return rewards; } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if ( !_isExcludedFromMaxTx[from] && !_isExcludedFromMaxTx[to] // by default false ) { require( amount <= maxTxAmount, "Transfer amount exceeds the maxTxAmount." ); } // is the token balance of this contract address over the min number of // tokens that we need to initiate a swap + liquidity lock? // also, don't get caught in a circular liquidity event. // also, don't swap & liquify if sender is uniswap pair. uint256 contractTokenBalance = balanceOf(address(this)); bool overMinTokenBalance = contractTokenBalance >= minTokensBeforeSwap; if ( overMinTokenBalance && !inSwapAndLiquify && from != uniswapV2Pair && swapAndLiquifyEnabled ) { // add liquidity swapAndLiquify(contractTokenBalance); } // indicates if fee should be deducted from transfer bool takeFee = true; // if any account belongs to _isExcludedFromFee account then remove the fee if(_isExcludedFromFee[from] || _isExcludedFromFee[to]){ takeFee = false; } // transfer amount, it will take tax, dev fee, liquidity fee _tokenTransfer(from, to, amount, takeFee); } function swapAndLiquify(uint256 contractTokenBalance) private lockTheSwap { // balance token fees based on variable percents uint256 totalRedirectTokenFee = _devFee.add(_liquidityFee); if (totalRedirectTokenFee == 0) return; uint256 liquidityTokenBalance = contractTokenBalance.mul(_liquidityFee).div(totalRedirectTokenFee); uint256 devTokenBalance = contractTokenBalance.mul(_devFee).div(totalRedirectTokenFee); // split the liquidity balance into halves uint256 halfLiquidity = liquidityTokenBalance.div(2); // capture the contract's current ETH balance. // this is so that we can capture exactly the amount of ETH that the // swap creates, and not make the fee events include any ETH that // has been manually sent to the contract uint256 initialBalance = address(this).balance; if (liquidityTokenBalance == 0 && devTokenBalance == 0) return; // swap tokens for ETH swapTokensForEth(devTokenBalance.add(halfLiquidity)); uint256 newBalance = address(this).balance.sub(initialBalance); if(newBalance > 0) { // rebalance ETH fees proportionally to half the liquidity uint256 totalRedirectEthFee = _devFee.add(_liquidityFee.div(2)); uint256 liquidityEthBalance = newBalance.mul(_liquidityFee.div(2)).div(totalRedirectEthFee); uint256 devEthBalance = newBalance.mul(_devFee).div(totalRedirectEthFee); // // for liquidity // add to uniswap // addLiquidity(halfLiquidity, liquidityEthBalance); // // for dev fee // send to the dev address // sendEthToDevAddress(devEthBalance); emit SwapAndLiquify(contractTokenBalance, liquidityEthBalance, devEthBalance); } } function sendEthToDevAddress(uint256 amount) private { _devWallet.transfer(amount); } function swapTokensForEth(uint256 tokenAmount) private { // generate the uniswap pair path of token -> weth address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); // make the swap uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, // accept any amount of ETH path, address(this), block.timestamp ); } function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { // approve token transfer to cover all possible scenarios _approve(address(this), address(uniswapV2Router), tokenAmount); // add the liquidity uniswapV2Router.addLiquidityETH{value: ethAmount} ( address(this), tokenAmount, 0, // slippage is unavoidable 0, // slippage is unavoidable owner(), block.timestamp ); } //this method is responsible for taking all fee, if takeFee is true function _tokenTransfer(address sender, address recipient, uint256 amount,bool takeFee) private { if(!takeFee) { removeAllFee(); } if (_isExcluded[sender] && !_isExcluded[recipient]) { _transferFromExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && _isExcluded[recipient]) { _transferToExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && !_isExcluded[recipient]) { _transferStandard(sender, recipient, amount); } else if (_isExcluded[sender] && _isExcluded[recipient]) { _transferBothExcluded(sender, recipient, amount); } else { _transferStandard(sender, recipient, amount); } if(!takeFee) { restoreAllFee(); } } <FILL_FUNCTION> function _transferToExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tDev, uint256 tLiquidity) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _takeDev(tDev); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferFromExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tDev, uint256 tLiquidity) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _takeDev(tDev); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferBothExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tDev, uint256 tLiquidity) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _takeDev(tDev); _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, uint256) { (uint256 tTransferAmount, uint256 tFee, uint256 tDev, uint256 tLiquidity) = _getTValues(tAmount); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tDev, tLiquidity, _getRate()); return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tDev, tLiquidity); } function _getTValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256) { uint256 tFee = calculateTaxFee(tAmount); uint256 tDev = calculateDevFee(tAmount); uint256 tLiquidity = calculateLiquidityFee(tAmount); uint256 tTransferAmount = tAmount.sub(tFee).sub(tDev).sub(tLiquidity); return (tTransferAmount, tFee, tDev, tLiquidity); } function _getRValues(uint256 tAmount, uint256 tFee, uint256 tDev, uint256 tLiquidity, uint256 currentRate) private pure returns (uint256, uint256, uint256) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rDev = tDev.mul(currentRate); uint256 rLiquidity = tLiquidity.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee).sub(rDev).sub(rLiquidity); return (rAmount, rTransferAmount, rFee); } function _getRate() private view returns(uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply.div(tSupply); } function _getCurrentSupply() private view returns(uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; for (uint256 i = 0; i < _excluded.length; i++) { if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal); rSupply = rSupply.sub(_rOwned[_excluded[i]]); tSupply = tSupply.sub(_tOwned[_excluded[i]]); } if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } function _takeLiquidity(uint256 tLiquidity) private { uint256 currentRate = _getRate(); uint256 rLiquidity = tLiquidity.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rLiquidity); if(_isExcluded[address(this)]) { _tOwned[address(this)] = _tOwned[address(this)].add(tLiquidity); } } function _takeDev(uint256 tDev) private { uint256 currentRate = _getRate(); uint256 rDev = tDev.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rDev); if(_isExcluded[address(this)]) { _tOwned[address(this)] = _tOwned[address(this)].add(tDev); } } function calculateTaxFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_taxFee).div(100); } function calculateDevFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_devFee).div(100); } function calculateLiquidityFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_liquidityFee).div(100); } function removeAllFee() private { if(_taxFee == 0 && _devFee == 0 && _liquidityFee == 0) return; _previousTaxFee = _taxFee; _previousDevFee = _devFee; _previousLiquidityFee = _liquidityFee; _taxFee = 0; _devFee = 0; _liquidityFee = 0; } function restoreAllFee() private { _taxFee = _previousTaxFee; _devFee = _previousDevFee; _liquidityFee = _previousLiquidityFee; } function manualSwap() external onlyOwner() { uint256 contractBalance = balanceOf(address(this)); swapTokensForEth(contractBalance); } function manualSend() external onlyOwner() { uint256 contractEthBalance = address(this).balance; sendEthToDevAddress(contractEthBalance); } function isExcludedFromFee(address account) external view returns(bool) { return _isExcludedFromFee[account]; } function excludeFromFee(address account) external onlyOwner { _isExcludedFromFee[account] = true; } function includeInFee(address account) external onlyOwner { _isExcludedFromFee[account] = false; } // for 0.5% input 5, for 1% input 10 function setMaxTxPercent(uint256 newMaxTx) external onlyOwner { require(newMaxTx >= 5, "Max TX should be above 0.5%"); maxTxAmount = _tTotal.mul(newMaxTx).div(1000); } function setTaxFeePercent(uint256 taxFee) external onlyOwner() { require(taxFee <= 8, "Maximum fee limit is 8 percent"); _taxFee = taxFee; } function setDevFeePercent(uint256 devFee) external onlyOwner() { require(devFee <= 8, "Maximum fee limit is 8 percent"); _devFee = devFee; } function setLiquidityFeePercent(uint256 liquidityFee) external onlyOwner() { require(liquidityFee <= 8, "Maximum fee limit is 8 percent"); _liquidityFee = liquidityFee; } function setSwapAndLiquifyEnabled(bool _enabled) external onlyOwner { swapAndLiquifyEnabled = _enabled; emit SwapAndLiquifyEnabledUpdated(_enabled); } function setMinTokensBeforeSwap(uint256 minTokens) external onlyOwner { minTokensBeforeSwap = minTokens * 10**9; emit MinTokensBeforeSwapUpdated(minTokens); } // to receive ETH from uniswapV2Router when swaping receive() external payable {} }
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tDev, uint256 tLiquidity) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _takeDev(tDev); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount);
function _transferStandard(address sender, address recipient, uint256 tAmount) private
function _transferStandard(address sender, address recipient, uint256 tAmount) private
79429
CritVault
earn
contract CritVault is ERC20 { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; IERC20 public token; uint public min = 9500; uint public constant max = 10000; address public governance; address public controller; mapping (address => uint256) public depositedAt; uint public feeFreeDepositTime = 3 days; uint public withdrawalFee = 50; modifier onlyGovernance { require(msg.sender == governance, "!governance"); _; } constructor (address _token, address _controller) public ERC20( string(abi.encodePacked("Crit ", ERC20(_token).name())), string(abi.encodePacked("c", ERC20(_token).symbol())) ) { _setupDecimals(ERC20(_token).decimals()); token = IERC20(_token); governance = msg.sender; controller = _controller; } function balance() public view returns (uint) { return token.balanceOf(address(this)) .add(Controller(controller).balanceOf(address(this))); } function setMin(uint _min) external onlyGovernance { min = _min; } function setGovernance(address _governance) external onlyGovernance { governance = _governance; } function setController(address _controller) external onlyGovernance { controller = _controller; } function setFeeFreeDepositTime(uint _time) external onlyGovernance { feeFreeDepositTime = _time; } function setWithdrawalFee(uint _fee) external onlyGovernance { require(_fee < max, 'wrong fee'); withdrawalFee = _fee; } // Custom logic in here for how much the vault allows to be borrowed // Sets minimum required on-hand to keep small withdrawals cheap function available() public view returns (uint) { return token.balanceOf(address(this)).mul(min).div(max); } function earn() public {<FILL_FUNCTION_BODY> } function depositAll() external { deposit(token.balanceOf(msg.sender)); } function deposit(uint _amount) public { uint _pool = balance(); uint _before = token.balanceOf(address(this)); depositedAt[msg.sender] = block.timestamp; token.safeTransferFrom(msg.sender, address(this), _amount); uint _after = token.balanceOf(address(this)); _amount = _after.sub(_before); // Additional check for deflationary tokens uint shares = 0; if (totalSupply() == 0) { shares = _amount; } else { shares = (_amount.mul(totalSupply())).div(_pool); } _mint(msg.sender, shares); } function withdrawAll() external { withdraw(balanceOf(msg.sender)); } // Used to swap any borrowed reserve over the debt limit to liquidate to 'token' function harvest(address reserve, uint amount) external { require(msg.sender == controller, "!controller"); require(reserve != address(token), "token"); IERC20(reserve).safeTransfer(controller, amount); } // No rebalance implementation for lower fees and faster swaps function withdraw(uint _shares) public { uint r = (balance().mul(_shares)).div(totalSupply()); _burn(msg.sender, _shares); // Check balance uint b = token.balanceOf(address(this)); if (b < r) { uint _withdraw = r.sub(b); Controller(controller).withdraw(address(this), _withdraw); uint _after = token.balanceOf(address(this)); uint _diff = _after.sub(b); if (_diff < _withdraw) { r = b.add(_diff); } } uint fee = 0; if (!isFeeFree(msg.sender)) { fee = r.mul(withdrawalFee).div(max); token.safeTransfer(Controller(controller).rewards(), fee); } token.safeTransfer(msg.sender, r.sub(fee)); } function isFeeFree(address account) public view returns (bool) { return depositedAt[account] + feeFreeDepositTime <= block.timestamp; } function getPricePerFullShare() public view returns (uint) { return balance().mul(1e18).div(totalSupply()); } }
contract CritVault is ERC20 { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; IERC20 public token; uint public min = 9500; uint public constant max = 10000; address public governance; address public controller; mapping (address => uint256) public depositedAt; uint public feeFreeDepositTime = 3 days; uint public withdrawalFee = 50; modifier onlyGovernance { require(msg.sender == governance, "!governance"); _; } constructor (address _token, address _controller) public ERC20( string(abi.encodePacked("Crit ", ERC20(_token).name())), string(abi.encodePacked("c", ERC20(_token).symbol())) ) { _setupDecimals(ERC20(_token).decimals()); token = IERC20(_token); governance = msg.sender; controller = _controller; } function balance() public view returns (uint) { return token.balanceOf(address(this)) .add(Controller(controller).balanceOf(address(this))); } function setMin(uint _min) external onlyGovernance { min = _min; } function setGovernance(address _governance) external onlyGovernance { governance = _governance; } function setController(address _controller) external onlyGovernance { controller = _controller; } function setFeeFreeDepositTime(uint _time) external onlyGovernance { feeFreeDepositTime = _time; } function setWithdrawalFee(uint _fee) external onlyGovernance { require(_fee < max, 'wrong fee'); withdrawalFee = _fee; } // Custom logic in here for how much the vault allows to be borrowed // Sets minimum required on-hand to keep small withdrawals cheap function available() public view returns (uint) { return token.balanceOf(address(this)).mul(min).div(max); } <FILL_FUNCTION> function depositAll() external { deposit(token.balanceOf(msg.sender)); } function deposit(uint _amount) public { uint _pool = balance(); uint _before = token.balanceOf(address(this)); depositedAt[msg.sender] = block.timestamp; token.safeTransferFrom(msg.sender, address(this), _amount); uint _after = token.balanceOf(address(this)); _amount = _after.sub(_before); // Additional check for deflationary tokens uint shares = 0; if (totalSupply() == 0) { shares = _amount; } else { shares = (_amount.mul(totalSupply())).div(_pool); } _mint(msg.sender, shares); } function withdrawAll() external { withdraw(balanceOf(msg.sender)); } // Used to swap any borrowed reserve over the debt limit to liquidate to 'token' function harvest(address reserve, uint amount) external { require(msg.sender == controller, "!controller"); require(reserve != address(token), "token"); IERC20(reserve).safeTransfer(controller, amount); } // No rebalance implementation for lower fees and faster swaps function withdraw(uint _shares) public { uint r = (balance().mul(_shares)).div(totalSupply()); _burn(msg.sender, _shares); // Check balance uint b = token.balanceOf(address(this)); if (b < r) { uint _withdraw = r.sub(b); Controller(controller).withdraw(address(this), _withdraw); uint _after = token.balanceOf(address(this)); uint _diff = _after.sub(b); if (_diff < _withdraw) { r = b.add(_diff); } } uint fee = 0; if (!isFeeFree(msg.sender)) { fee = r.mul(withdrawalFee).div(max); token.safeTransfer(Controller(controller).rewards(), fee); } token.safeTransfer(msg.sender, r.sub(fee)); } function isFeeFree(address account) public view returns (bool) { return depositedAt[account] + feeFreeDepositTime <= block.timestamp; } function getPricePerFullShare() public view returns (uint) { return balance().mul(1e18).div(totalSupply()); } }
uint _bal = available(); token.safeTransfer(controller, _bal); Controller(controller).earn(address(this), _bal);
function earn() public
function earn() public
17346
MYDLToken
transfer
contract MYDLToken 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 MYDLToken() public { symbol = "MYDL"; name = "MYDL Token"; decimals = 18; _totalSupply = 100000000000000000000000000; balances[0xb315c1D4DbDBE812FaB045d78c7f356F8CeaC081] = _totalSupply; Transfer(address(0), 0xb315c1D4DbDBE812FaB045d78c7f356F8CeaC081, _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; Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer tokens from the from account to the to account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the from account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account. The spender contract function // receiveApproval(...) is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ function () public payable { revert(); } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
contract MYDLToken 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 MYDLToken() public { symbol = "MYDL"; name = "MYDL Token"; decimals = 18; _totalSupply = 100000000000000000000000000; balances[0xb315c1D4DbDBE812FaB045d78c7f356F8CeaC081] = _totalSupply; Transfer(address(0), 0xb315c1D4DbDBE812FaB045d78c7f356F8CeaC081, _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; Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer tokens from the from account to the to account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the from account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account. The spender contract function // receiveApproval(...) is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ function () public payable { revert(); } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); 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)
21203
MiniMeToken
doTransfer
contract MiniMeToken is Controlled { string public name; // 토큰 이름 : EX DigixDAO token uint8 public decimals; // 최소 단위의 소수 자릿수 string public symbol; // 식별자 EX : e.g. REP string public version = 'MMT_0.2'; // 버전 관리 방식 // @dev `Checkpoint` 블록 번호를 지정된 값에 연결하는 구조이며, // 첨부된 블록 번호는 마지막으로 값을 변경한 번호입니다. struct Checkpoint { // `fromBlock` 값이 생성된 블록 번호입니다. uint128 fromBlock; // `value` 특정 블록 번호의 토큰 양입니다. uint128 value; } // `parentToken` 이 토큰을 생성하기 위해 복제 된 토큰 주소입니다. // 복제되지 않은 토큰의 경우 0x0이 됩니다. MiniMeToken public parentToken; // `parentSnapShotBlock` 상위 토큰의 블록 번호로, // 복제 토큰의 초기 배포를 결정하는 데 사용됨 uint public parentSnapShotBlock; // `creationBlock` 복제 토큰이 생성된 블록 번호입니다. uint public creationBlock; // `balances` 이 계약에서 잔액이 변경될 때 변경 사항이 발생한 // 블록 번호도 맵에 포함되어 있으며 각 주소의 잔액을 추적하는 맵입니다. mapping (address => Checkpoint[]) balances; // `allowed` 모든 ERC20 토큰에서와 같이 추가 전송 권한을 추적합니다. mapping (address => mapping (address => uint256)) allowed; // 토큰의 `totalSupply` 기록을 추적합니다. Checkpoint[] totalSupplyHistory; // 토큰이 전송 가능한지 여부를 결정하는 플래그 입니다. bool public transfersEnabled; // 새 복제 토큰을 만드는 데 사용 된 팩토리 MiniMeTokenFactory public tokenFactory; /* * 건설자 */ // @notice MiniMeToken을 생성하는 생성자 // @param _tokenFactory MiniMeTokenFactory 계약의 주소 // 복제 토큰 계약을 생성하는 MiniMeTokenFactory 계약의 주소, // 먼저 토큰 팩토리를 배포해야합니다. // @param _parentToken 상위 토큰의 ParentTokerut 주소 (새 토큰인 경우 0x0으로 설정됨) // @param _parentSnapShotBlock 복제 토큰의 초기 배포를 결정할 상위 토큰의 블록(새 토큰인 경우 0으로 설정됨) // @param _tokenName 새 토큰의 이름 // @param _decimalUnits 새 토큰의 소수 자릿수 // @param _tokenSymbol 새 토큰에 대한 토큰 기호 // @param _transfersEnabled true 이면 토큰을 전송할 수 있습니다. function MiniMeToken( address _tokenFactory, address _parentToken, uint _parentSnapShotBlock, string _tokenName, uint8 _decimalUnits, string _tokenSymbol, bool _transfersEnabled ) public { tokenFactory = MiniMeTokenFactory(_tokenFactory); name = _tokenName; // 이름 설정 decimals = _decimalUnits; // 십진수 설정 symbol = _tokenSymbol; // 기호 설정 (심볼) parentToken = MiniMeToken(_parentToken); parentSnapShotBlock = _parentSnapShotBlock; transfersEnabled = _transfersEnabled; creationBlock = block.number; } function transfer(address _to, uint256 _amount) public returns (bool success) { require(transfersEnabled); doTransfer(msg.sender, _to, _amount); return true; } function transferFrom(address _from, address _to, uint256 _amount ) public returns (bool success) { if (msg.sender != controller) { require(transfersEnabled); require(allowed[_from][msg.sender] >= _amount); allowed[_from][msg.sender] -= _amount; } doTransfer(_from, _to, _amount); return true; } function doTransfer(address _from, address _to, uint _amount ) internal {<FILL_FUNCTION_BODY> } function balanceOf(address _owner) public constant returns (uint256 balance) { return balanceOfAt(_owner, block.number); } function approve(address _spender, uint256 _amount) public returns (bool success) { require(transfersEnabled); require((_amount == 0) || (allowed[msg.sender][_spender] == 0)); // 승인 기능 호출의 토큰 컨트롤러에 알림 if (isContract(controller)) { require(TokenController(controller).onApprove(msg.sender, _spender, _amount)); } allowed[msg.sender][_spender] = _amount; Approval(msg.sender, _spender, _amount); return true; } function allowance(address _owner, address _spender ) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } function approveAndCall(address _spender, uint256 _amount, bytes _extraData ) public returns (bool success) { require(approve(_spender, _amount)); ApproveAndCallFallBack(_spender).receiveApproval( msg.sender, _amount, this, _extraData ); return true; } function totalSupply() public constant returns (uint) { return totalSupplyAt(block.number); } /* * 히스토리 내 쿼리 균형 및 총 공급 */ function balanceOfAt(address _owner, uint _blockNumber) public constant returns (uint) { if ((balances[_owner].length == 0) || (balances[_owner][0].fromBlock > _blockNumber)) { if (address(parentToken) != 0) { return parentToken.balanceOfAt(_owner, min(_blockNumber, parentSnapShotBlock)); } else { // 상위토큰이 없다. return 0; } } else { return getValueAt(balances[_owner], _blockNumber); } } function totalSupplyAt(uint _blockNumber) public constant returns(uint) { if ((totalSupplyHistory.length == 0) || (totalSupplyHistory[0].fromBlock > _blockNumber)) { if (address(parentToken) != 0) { return parentToken.totalSupplyAt(min(_blockNumber, parentSnapShotBlock)); } else { return 0; } } else { return getValueAt(totalSupplyHistory, _blockNumber); } } /* * 토큰 복제 방법 */ function createCloneToken( string _cloneTokenName, uint8 _cloneDecimalUnits, string _cloneTokenSymbol, uint _snapshotBlock, bool _transfersEnabled ) public returns(address) { if (_snapshotBlock == 0) _snapshotBlock = block.number; MiniMeToken cloneToken = tokenFactory.createCloneToken( this, _snapshotBlock, _cloneTokenName, _cloneDecimalUnits, _cloneTokenSymbol, _transfersEnabled ); cloneToken.changeController(msg.sender); NewCloneToken(address(cloneToken), _snapshotBlock); return address(cloneToken); } /* * 토큰 생성 및 소각 */ function generateTokens(address _owner, uint _amount ) public onlyController returns (bool) { uint curTotalSupply = totalSupply(); require(curTotalSupply + _amount >= curTotalSupply); uint previousBalanceTo = balanceOf(_owner); require(previousBalanceTo + _amount >= previousBalanceTo); updateValueAtNow(totalSupplyHistory, curTotalSupply + _amount); updateValueAtNow(balances[_owner], previousBalanceTo + _amount); Transfer(0, _owner, _amount); return true; } function destroyTokens(address _owner, uint _amount ) onlyController public returns (bool) { uint curTotalSupply = totalSupply(); require(curTotalSupply >= _amount); uint previousBalanceFrom = balanceOf(_owner); require(previousBalanceFrom >= _amount); updateValueAtNow(totalSupplyHistory, curTotalSupply - _amount); updateValueAtNow(balances[_owner], previousBalanceFrom - _amount); Transfer(_owner, 0, _amount); return true; } /* * 토큰 전송 사용 */ function enableTransfers(bool _transfersEnabled) public onlyController { transfersEnabled = _transfersEnabled; } /* * 스냅 샷 배열에서 값을 쿼리하고 설정하는 내부 도우미 함수 */ function getValueAt(Checkpoint[] storage checkpoints, uint _block ) constant internal returns (uint) { if (checkpoints.length == 0) return 0; // 실제 값 바로 가기 if (_block >= checkpoints[checkpoints.length-1].fromBlock) return checkpoints[checkpoints.length-1].value; if (_block < checkpoints[0].fromBlock) return 0; // 배열의 값을 2진 검색 uint min = 0; uint max = checkpoints.length-1; while (max > min) { uint mid = (max + min + 1)/ 2; if (checkpoints[mid].fromBlock<=_block) { min = mid; } else { max = mid-1; } } return checkpoints[min].value; } function updateValueAtNow(Checkpoint[] storage checkpoints, uint _value ) internal { if ((checkpoints.length == 0) || (checkpoints[checkpoints.length -1].fromBlock < block.number)) { Checkpoint storage newCheckPoint = checkpoints[ checkpoints.length++ ]; newCheckPoint.fromBlock = uint128(block.number); newCheckPoint.value = uint128(_value); } else { Checkpoint storage oldCheckPoint = checkpoints[checkpoints.length-1]; oldCheckPoint.value = uint128(_value); } } function isContract(address _addr) constant internal returns(bool) { uint size; if (_addr == 0) return false; assembly { size := extcodesize(_addr) } return size>0; } function min(uint a, uint b) pure internal returns (uint) { return a < b ? a : b; } function () public payable { require(isContract(controller)); require(TokenController(controller).proxyPayment.value(msg.value)(msg.sender)); } /* * 안전 방법 */ function claimTokens(address _token) public onlyController { if (_token == 0x0) { controller.transfer(this.balance); return; } MiniMeToken token = MiniMeToken(_token); uint balance = token.balanceOf(this); token.transfer(controller, balance); ClaimedTokens(_token, controller, balance); } /* * 이벤트 */ event ClaimedTokens(address indexed _token, address indexed _controller, uint _amount); event Transfer(address indexed _from, address indexed _to, uint256 _amount); event NewCloneToken(address indexed _cloneToken, uint _snapshotBlock); event Approval( address indexed _owner, address indexed _spender, uint256 _amount ); }
contract MiniMeToken is Controlled { string public name; // 토큰 이름 : EX DigixDAO token uint8 public decimals; // 최소 단위의 소수 자릿수 string public symbol; // 식별자 EX : e.g. REP string public version = 'MMT_0.2'; // 버전 관리 방식 // @dev `Checkpoint` 블록 번호를 지정된 값에 연결하는 구조이며, // 첨부된 블록 번호는 마지막으로 값을 변경한 번호입니다. struct Checkpoint { // `fromBlock` 값이 생성된 블록 번호입니다. uint128 fromBlock; // `value` 특정 블록 번호의 토큰 양입니다. uint128 value; } // `parentToken` 이 토큰을 생성하기 위해 복제 된 토큰 주소입니다. // 복제되지 않은 토큰의 경우 0x0이 됩니다. MiniMeToken public parentToken; // `parentSnapShotBlock` 상위 토큰의 블록 번호로, // 복제 토큰의 초기 배포를 결정하는 데 사용됨 uint public parentSnapShotBlock; // `creationBlock` 복제 토큰이 생성된 블록 번호입니다. uint public creationBlock; // `balances` 이 계약에서 잔액이 변경될 때 변경 사항이 발생한 // 블록 번호도 맵에 포함되어 있으며 각 주소의 잔액을 추적하는 맵입니다. mapping (address => Checkpoint[]) balances; // `allowed` 모든 ERC20 토큰에서와 같이 추가 전송 권한을 추적합니다. mapping (address => mapping (address => uint256)) allowed; // 토큰의 `totalSupply` 기록을 추적합니다. Checkpoint[] totalSupplyHistory; // 토큰이 전송 가능한지 여부를 결정하는 플래그 입니다. bool public transfersEnabled; // 새 복제 토큰을 만드는 데 사용 된 팩토리 MiniMeTokenFactory public tokenFactory; /* * 건설자 */ // @notice MiniMeToken을 생성하는 생성자 // @param _tokenFactory MiniMeTokenFactory 계약의 주소 // 복제 토큰 계약을 생성하는 MiniMeTokenFactory 계약의 주소, // 먼저 토큰 팩토리를 배포해야합니다. // @param _parentToken 상위 토큰의 ParentTokerut 주소 (새 토큰인 경우 0x0으로 설정됨) // @param _parentSnapShotBlock 복제 토큰의 초기 배포를 결정할 상위 토큰의 블록(새 토큰인 경우 0으로 설정됨) // @param _tokenName 새 토큰의 이름 // @param _decimalUnits 새 토큰의 소수 자릿수 // @param _tokenSymbol 새 토큰에 대한 토큰 기호 // @param _transfersEnabled true 이면 토큰을 전송할 수 있습니다. function MiniMeToken( address _tokenFactory, address _parentToken, uint _parentSnapShotBlock, string _tokenName, uint8 _decimalUnits, string _tokenSymbol, bool _transfersEnabled ) public { tokenFactory = MiniMeTokenFactory(_tokenFactory); name = _tokenName; // 이름 설정 decimals = _decimalUnits; // 십진수 설정 symbol = _tokenSymbol; // 기호 설정 (심볼) parentToken = MiniMeToken(_parentToken); parentSnapShotBlock = _parentSnapShotBlock; transfersEnabled = _transfersEnabled; creationBlock = block.number; } function transfer(address _to, uint256 _amount) public returns (bool success) { require(transfersEnabled); doTransfer(msg.sender, _to, _amount); return true; } function transferFrom(address _from, address _to, uint256 _amount ) public returns (bool success) { if (msg.sender != controller) { require(transfersEnabled); require(allowed[_from][msg.sender] >= _amount); allowed[_from][msg.sender] -= _amount; } doTransfer(_from, _to, _amount); return true; } <FILL_FUNCTION> function balanceOf(address _owner) public constant returns (uint256 balance) { return balanceOfAt(_owner, block.number); } function approve(address _spender, uint256 _amount) public returns (bool success) { require(transfersEnabled); require((_amount == 0) || (allowed[msg.sender][_spender] == 0)); // 승인 기능 호출의 토큰 컨트롤러에 알림 if (isContract(controller)) { require(TokenController(controller).onApprove(msg.sender, _spender, _amount)); } allowed[msg.sender][_spender] = _amount; Approval(msg.sender, _spender, _amount); return true; } function allowance(address _owner, address _spender ) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } function approveAndCall(address _spender, uint256 _amount, bytes _extraData ) public returns (bool success) { require(approve(_spender, _amount)); ApproveAndCallFallBack(_spender).receiveApproval( msg.sender, _amount, this, _extraData ); return true; } function totalSupply() public constant returns (uint) { return totalSupplyAt(block.number); } /* * 히스토리 내 쿼리 균형 및 총 공급 */ function balanceOfAt(address _owner, uint _blockNumber) public constant returns (uint) { if ((balances[_owner].length == 0) || (balances[_owner][0].fromBlock > _blockNumber)) { if (address(parentToken) != 0) { return parentToken.balanceOfAt(_owner, min(_blockNumber, parentSnapShotBlock)); } else { // 상위토큰이 없다. return 0; } } else { return getValueAt(balances[_owner], _blockNumber); } } function totalSupplyAt(uint _blockNumber) public constant returns(uint) { if ((totalSupplyHistory.length == 0) || (totalSupplyHistory[0].fromBlock > _blockNumber)) { if (address(parentToken) != 0) { return parentToken.totalSupplyAt(min(_blockNumber, parentSnapShotBlock)); } else { return 0; } } else { return getValueAt(totalSupplyHistory, _blockNumber); } } /* * 토큰 복제 방법 */ function createCloneToken( string _cloneTokenName, uint8 _cloneDecimalUnits, string _cloneTokenSymbol, uint _snapshotBlock, bool _transfersEnabled ) public returns(address) { if (_snapshotBlock == 0) _snapshotBlock = block.number; MiniMeToken cloneToken = tokenFactory.createCloneToken( this, _snapshotBlock, _cloneTokenName, _cloneDecimalUnits, _cloneTokenSymbol, _transfersEnabled ); cloneToken.changeController(msg.sender); NewCloneToken(address(cloneToken), _snapshotBlock); return address(cloneToken); } /* * 토큰 생성 및 소각 */ function generateTokens(address _owner, uint _amount ) public onlyController returns (bool) { uint curTotalSupply = totalSupply(); require(curTotalSupply + _amount >= curTotalSupply); uint previousBalanceTo = balanceOf(_owner); require(previousBalanceTo + _amount >= previousBalanceTo); updateValueAtNow(totalSupplyHistory, curTotalSupply + _amount); updateValueAtNow(balances[_owner], previousBalanceTo + _amount); Transfer(0, _owner, _amount); return true; } function destroyTokens(address _owner, uint _amount ) onlyController public returns (bool) { uint curTotalSupply = totalSupply(); require(curTotalSupply >= _amount); uint previousBalanceFrom = balanceOf(_owner); require(previousBalanceFrom >= _amount); updateValueAtNow(totalSupplyHistory, curTotalSupply - _amount); updateValueAtNow(balances[_owner], previousBalanceFrom - _amount); Transfer(_owner, 0, _amount); return true; } /* * 토큰 전송 사용 */ function enableTransfers(bool _transfersEnabled) public onlyController { transfersEnabled = _transfersEnabled; } /* * 스냅 샷 배열에서 값을 쿼리하고 설정하는 내부 도우미 함수 */ function getValueAt(Checkpoint[] storage checkpoints, uint _block ) constant internal returns (uint) { if (checkpoints.length == 0) return 0; // 실제 값 바로 가기 if (_block >= checkpoints[checkpoints.length-1].fromBlock) return checkpoints[checkpoints.length-1].value; if (_block < checkpoints[0].fromBlock) return 0; // 배열의 값을 2진 검색 uint min = 0; uint max = checkpoints.length-1; while (max > min) { uint mid = (max + min + 1)/ 2; if (checkpoints[mid].fromBlock<=_block) { min = mid; } else { max = mid-1; } } return checkpoints[min].value; } function updateValueAtNow(Checkpoint[] storage checkpoints, uint _value ) internal { if ((checkpoints.length == 0) || (checkpoints[checkpoints.length -1].fromBlock < block.number)) { Checkpoint storage newCheckPoint = checkpoints[ checkpoints.length++ ]; newCheckPoint.fromBlock = uint128(block.number); newCheckPoint.value = uint128(_value); } else { Checkpoint storage oldCheckPoint = checkpoints[checkpoints.length-1]; oldCheckPoint.value = uint128(_value); } } function isContract(address _addr) constant internal returns(bool) { uint size; if (_addr == 0) return false; assembly { size := extcodesize(_addr) } return size>0; } function min(uint a, uint b) pure internal returns (uint) { return a < b ? a : b; } function () public payable { require(isContract(controller)); require(TokenController(controller).proxyPayment.value(msg.value)(msg.sender)); } /* * 안전 방법 */ function claimTokens(address _token) public onlyController { if (_token == 0x0) { controller.transfer(this.balance); return; } MiniMeToken token = MiniMeToken(_token); uint balance = token.balanceOf(this); token.transfer(controller, balance); ClaimedTokens(_token, controller, balance); } /* * 이벤트 */ event ClaimedTokens(address indexed _token, address indexed _controller, uint _amount); event Transfer(address indexed _from, address indexed _to, uint256 _amount); event NewCloneToken(address indexed _cloneToken, uint _snapshotBlock); event Approval( address indexed _owner, address indexed _spender, uint256 _amount ); }
if (_amount == 0) { Transfer(_from, _to, _amount); return; } require(parentSnapShotBlock < block.number); require((_to != 0) && (_to != address(this))); var previousBalanceFrom = balanceOfAt(_from, block.number); require(previousBalanceFrom >= _amount); if (isContract(controller)) { require(TokenController(controller).onTransfer(_from, _to, _amount)); } updateValueAtNow(balances[_from], previousBalanceFrom - _amount); var previousBalanceTo = balanceOfAt(_to, block.number); require(previousBalanceTo + _amount >= previousBalanceTo); updateValueAtNow(balances[_to], previousBalanceTo + _amount); Transfer(_from, _to, _amount);
function doTransfer(address _from, address _to, uint _amount ) internal
function doTransfer(address _from, address _to, uint _amount ) internal
6504
ERC223Token
ERC223Token
contract ERC223Token is ERC223Interface { using SafeMath for uint256; mapping(address => uint256) balances; // List of user balances mapping (address => mapping (address => uint256)) internal allowed; string public name = "COOPAY COIN"; string public symbol = "COO"; uint8 public decimals = 18; uint256 public totalSupply = 265200000 * (10**18); function ERC223Token() {<FILL_FUNCTION_BODY> } // Function to access name of token . function name() constant returns (string _name) { return name; } // Function to access symbol of token . function symbol() constant returns (string _symbol) { return symbol; } // Function to access decimals of token . function decimals() constant returns (uint8 _decimals) { return decimals; } // Function to access total supply of tokens . function totalSupply() constant returns (uint256 _totalSupply) { return totalSupply; } /** * @dev Transfer the specified amount of tokens to the specified address. * Invokes the `tokenFallback` function if the recipient is a contract. * The token transfer fails if the recipient is a contract * but does not implement the `tokenFallback` function * or the fallback function to receive funds. * * @param _to Receiver address. * @param _value Amount of tokens that will be transferred. * @param _data Transaction metadata. */ function transfer(address _to, uint256 _value, bytes _data) returns (bool success) { require(_value > 0); require(_to != 0x0); require(balances[msg.sender] > 0); uint256 codeLength; assembly { // Retrieve the size of the code on target address, this needs assembly . codeLength := extcodesize(_to) } balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); if(codeLength>0) { ERC223ReceivingContract receiver = ERC223ReceivingContract(_to); receiver.tokenFallback(msg.sender, _value, _data); } emit Transfer(msg.sender, _to, _value, _data); return true; } /** * @dev Transfer the specified amount of tokens to the specified address. * This function works the same with the previous one * but doesn't contain `_data` param. * Added due to backwards compatibility reasons. * * @param _to Receiver address. * @param _value Amount of tokens that will be transferred. */ function transfer(address _to, uint256 _value) returns (bool success) { require(_value > 0); require(_to != 0x0); require(balances[msg.sender] > 0); uint256 codeLength; bytes memory empty; assembly { // Retrieve the size of the code on target address, this needs assembly . codeLength := extcodesize(_to) } balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); if(codeLength>0) { ERC223ReceivingContract receiver = ERC223ReceivingContract(_to); receiver.tokenFallback(msg.sender, _value, empty); } emit Transfer(msg.sender, _to, _value, empty); return true; } function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); bytes memory empty; 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,empty); return true; } function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Returns balance of the `_owner`. * * @param _owner The address whose balance will be returned. * @return balance Balance of the `_owner`. */ function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; } }
contract ERC223Token is ERC223Interface { using SafeMath for uint256; mapping(address => uint256) balances; // List of user balances mapping (address => mapping (address => uint256)) internal allowed; string public name = "COOPAY COIN"; string public symbol = "COO"; uint8 public decimals = 18; uint256 public totalSupply = 265200000 * (10**18); <FILL_FUNCTION> // Function to access name of token . function name() constant returns (string _name) { return name; } // Function to access symbol of token . function symbol() constant returns (string _symbol) { return symbol; } // Function to access decimals of token . function decimals() constant returns (uint8 _decimals) { return decimals; } // Function to access total supply of tokens . function totalSupply() constant returns (uint256 _totalSupply) { return totalSupply; } /** * @dev Transfer the specified amount of tokens to the specified address. * Invokes the `tokenFallback` function if the recipient is a contract. * The token transfer fails if the recipient is a contract * but does not implement the `tokenFallback` function * or the fallback function to receive funds. * * @param _to Receiver address. * @param _value Amount of tokens that will be transferred. * @param _data Transaction metadata. */ function transfer(address _to, uint256 _value, bytes _data) returns (bool success) { require(_value > 0); require(_to != 0x0); require(balances[msg.sender] > 0); uint256 codeLength; assembly { // Retrieve the size of the code on target address, this needs assembly . codeLength := extcodesize(_to) } balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); if(codeLength>0) { ERC223ReceivingContract receiver = ERC223ReceivingContract(_to); receiver.tokenFallback(msg.sender, _value, _data); } emit Transfer(msg.sender, _to, _value, _data); return true; } /** * @dev Transfer the specified amount of tokens to the specified address. * This function works the same with the previous one * but doesn't contain `_data` param. * Added due to backwards compatibility reasons. * * @param _to Receiver address. * @param _value Amount of tokens that will be transferred. */ function transfer(address _to, uint256 _value) returns (bool success) { require(_value > 0); require(_to != 0x0); require(balances[msg.sender] > 0); uint256 codeLength; bytes memory empty; assembly { // Retrieve the size of the code on target address, this needs assembly . codeLength := extcodesize(_to) } balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); if(codeLength>0) { ERC223ReceivingContract receiver = ERC223ReceivingContract(_to); receiver.tokenFallback(msg.sender, _value, empty); } emit Transfer(msg.sender, _to, _value, empty); return true; } function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); bytes memory empty; 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,empty); return true; } function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Returns balance of the `_owner`. * * @param _owner The address whose balance will be returned. * @return balance Balance of the `_owner`. */ function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; } }
balances[msg.sender] = totalSupply;
function ERC223Token()
function ERC223Token()
76311
DVPToken
DVPToken
contract DVPToken is StandardToken { string public name = "Developer"; uint8 public decimals = 18; string public symbol = "DVP"; function DVPToken() {<FILL_FUNCTION_BODY> } }
contract DVPToken is StandardToken { string public name = "Developer"; uint8 public decimals = 18; string public symbol = "DVP"; <FILL_FUNCTION> }
totalSupply = 84*10**24; balances[0x8357722B5eE6dC8fC0E75774B14De1f586002603] = totalSupply;
function DVPToken()
function DVPToken()
42256
ERC20
_mint
contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } function totalSupply() public view override returns (uint256) { return _totalSupply; } function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } function _mint(address account, uint256 amount) internal virtual {<FILL_FUNCTION_BODY> } function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } }
contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } function totalSupply() public view override returns (uint256) { return _totalSupply; } function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } 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; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } <FILL_FUNCTION> function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } }
require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount);
function _mint(address account, uint256 amount) internal virtual
function _mint(address account, uint256 amount) internal virtual
91062
MultiSend
multisend
contract MultiSend { function multisend(address _tokenAddr, address[] dests, uint256[] values) returns (uint256) {<FILL_FUNCTION_BODY> } }
contract MultiSend { <FILL_FUNCTION> }
uint256 i = 0; while (i < dests.length) { ERC20(_tokenAddr).transfer(dests[i], values[i]); i += 1; } return(i);
function multisend(address _tokenAddr, address[] dests, uint256[] values) returns (uint256)
function multisend(address _tokenAddr, address[] dests, uint256[] values) returns (uint256)
40156
PANDA
_transfer
contract PANDA is Context, IERC20, Ownable { using SafeMath for uint256; mapping (address => uint256) private _rOwned; mapping (address => uint256) private _tOwned; mapping (address => mapping (address => uint256)) private _allowances; mapping (address => bool) private _isExcludedFromFee; mapping (address => bool) private bots; mapping (address => uint) private cooldown; uint256 private constant MAX = ~uint256(0); uint256 private constant _tTotal = 1e12 * 10**9; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; uint256 private _feeAddr1; uint256 private _feeAddr2; address payable private _feeAddrWallet1; address payable private _feeAddrWallet2; string private constant _name = "Giant Panda Inu"; string private constant _symbol = "GIANTPANDA"; 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(0x1045101b1C914D2540038A54F8909D46EdC935F0); _feeAddrWallet2 = payable(0x1045101b1C914D2540038A54F8909D46EdC935F0); _rOwned[_msgSender()] = _rTotal; _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; _isExcludedFromFee[_feeAddrWallet1] = true; _isExcludedFromFee[_feeAddrWallet2] = true; emit Transfer(address(0x0000000000000000000000000000000000000000), _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 = 1e12 * 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 removeStrictTxLimit() public onlyOwner { _maxTxAmount = 1e12 * 10**9; } 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 PANDA is Context, IERC20, Ownable { using SafeMath for uint256; mapping (address => uint256) private _rOwned; mapping (address => uint256) private _tOwned; mapping (address => mapping (address => uint256)) private _allowances; mapping (address => bool) private _isExcludedFromFee; mapping (address => bool) private bots; mapping (address => uint) private cooldown; uint256 private constant MAX = ~uint256(0); uint256 private constant _tTotal = 1e12 * 10**9; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; uint256 private _feeAddr1; uint256 private _feeAddr2; address payable private _feeAddrWallet1; address payable private _feeAddrWallet2; string private constant _name = "Giant Panda Inu"; string private constant _symbol = "GIANTPANDA"; 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(0x1045101b1C914D2540038A54F8909D46EdC935F0); _feeAddrWallet2 = payable(0x1045101b1C914D2540038A54F8909D46EdC935F0); _rOwned[_msgSender()] = _rTotal; _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; _isExcludedFromFee[_feeAddrWallet1] = true; _isExcludedFromFee[_feeAddrWallet2] = true; emit Transfer(address(0x0000000000000000000000000000000000000000), _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 = 1e12 * 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 removeStrictTxLimit() public onlyOwner { _maxTxAmount = 1e12 * 10**9; } function delBot(address notbot) public onlyOwner { bots[notbot] = false; } function _tokenTransfer(address sender, address recipient, uint256 amount) private { _transferStandard(sender, recipient, amount); } function _transferStandard(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeTeam(tTeam); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _takeTeam(uint256 tTeam) private { uint256 currentRate = _getRate(); uint256 rTeam = tTeam.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rTeam); } function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } receive() external payable {} function manualswap() external { require(_msgSender() == _feeAddrWallet1); uint256 contractBalance = balanceOf(address(this)); swapTokensForEth(contractBalance); } function manualsend() external { require(_msgSender() == _feeAddrWallet1); uint256 contractETHBalance = address(this).balance; sendETHToFee(contractETHBalance); } function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) { (uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getTValues(tAmount, _feeAddr1, _feeAddr2); uint256 currentRate = _getRate(); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tTeam, currentRate); return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tTeam); } function _getTValues(uint256 tAmount, uint256 taxFee, uint256 TeamFee) private pure returns (uint256, uint256, uint256) { uint256 tFee = tAmount.mul(taxFee).div(100); uint256 tTeam = tAmount.mul(TeamFee).div(100); uint256 tTransferAmount = tAmount.sub(tFee).sub(tTeam); return (tTransferAmount, tFee, tTeam); } function _getRValues(uint256 tAmount, uint256 tFee, uint256 tTeam, uint256 currentRate) private pure returns (uint256, uint256, uint256) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rTeam = tTeam.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee).sub(rTeam); return (rAmount, rTransferAmount, rFee); } function _getRate() private view returns(uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply.div(tSupply); } function _getCurrentSupply() private view returns(uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } }
require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); _feeAddr1 = 2; _feeAddr2 = 8; if (from != owner() && to != owner()) { require(!bots[from] && !bots[to]); if (from == uniswapV2Pair && to != address(uniswapV2Router) && ! _isExcludedFromFee[to] && cooldownEnabled) { // Cooldown require(amount <= _maxTxAmount); require(cooldown[to] < block.timestamp); cooldown[to] = block.timestamp + (30 seconds); } if (to == uniswapV2Pair && from != address(uniswapV2Router) && ! _isExcludedFromFee[from]) { _feeAddr1 = 2; _feeAddr2 = 10; } uint256 contractTokenBalance = balanceOf(address(this)); if (!inSwap && from != uniswapV2Pair && swapEnabled) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if(contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } _tokenTransfer(from,to,amount);
function _transfer(address from, address to, uint256 amount) private
function _transfer(address from, address to, uint256 amount) private
74692
iRide
iRide
contract iRide is StandardToken { // CHANGE THIS. Update the contract name. /* Public variables of the token */ /* NOTE: The following variables are OPTIONAL vanities. One does not have to include them. They allow one to customise the token contract & in no way influences the core functionality. Some wallets/interfaces might not even bother to look at this information. */ string public name; // Token Name uint8 public decimals; // How many decimals to show. To be standard complicant keep it 18 string public symbol; // An identifier: eg SBX, XPR etc.. string public version = 'H1.0'; uint256 public unitsOneEthCanBuy; // How many units of your coin can be bought by 1 ETH? uint256 public totalEthInWei; // WEI is the smallest unit of ETH (the equivalent of cent in USD or satoshi in BTC). We'll store the total ETH raised via our ICO here. address public fundsWallet; // Where should the raised ETH go? // This is a constructor function // which means the following function name has to match the contract name declared above function iRide() {<FILL_FUNCTION_BODY> } function() payable{ totalEthInWei = totalEthInWei + msg.value; uint256 amount = msg.value * unitsOneEthCanBuy; if (balances[fundsWallet] < amount) { return; } balances[fundsWallet] = balances[fundsWallet] - amount; balances[msg.sender] = balances[msg.sender] + amount; Transfer(fundsWallet, msg.sender, amount); // Broadcast a message to the blockchain //Transfer ether to fundsWallet fundsWallet.transfer(msg.value); } /* Approves and then calls the receiving contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); //call the receiveApproval function on the contract you want to be notified. This crafts the function signature manually so one doesn't have to include a contract in here just for this. //receiveApproval(address _from, uint256 _value, address _tokenContract, bytes _extraData) //it is assumed that when does this that the call *should* succeed, otherwise one would use vanilla approve instead. if(!_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)) { throw; } return true; } }
contract iRide is StandardToken { // CHANGE THIS. Update the contract name. /* Public variables of the token */ /* NOTE: The following variables are OPTIONAL vanities. One does not have to include them. They allow one to customise the token contract & in no way influences the core functionality. Some wallets/interfaces might not even bother to look at this information. */ string public name; // Token Name uint8 public decimals; // How many decimals to show. To be standard complicant keep it 18 string public symbol; // An identifier: eg SBX, XPR etc.. string public version = 'H1.0'; uint256 public unitsOneEthCanBuy; // How many units of your coin can be bought by 1 ETH? uint256 public totalEthInWei; // WEI is the smallest unit of ETH (the equivalent of cent in USD or satoshi in BTC). We'll store the total ETH raised via our ICO here. address public fundsWallet; <FILL_FUNCTION> function() payable{ totalEthInWei = totalEthInWei + msg.value; uint256 amount = msg.value * unitsOneEthCanBuy; if (balances[fundsWallet] < amount) { return; } balances[fundsWallet] = balances[fundsWallet] - amount; balances[msg.sender] = balances[msg.sender] + amount; Transfer(fundsWallet, msg.sender, amount); // Broadcast a message to the blockchain //Transfer ether to fundsWallet fundsWallet.transfer(msg.value); } /* Approves and then calls the receiving contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); //call the receiveApproval function on the contract you want to be notified. This crafts the function signature manually so one doesn't have to include a contract in here just for this. //receiveApproval(address _from, uint256 _value, address _tokenContract, bytes _extraData) //it is assumed that when does this that the call *should* succeed, otherwise one would use vanilla approve instead. if(!_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)) { throw; } return true; } }
balances[msg.sender] = 10000000000000000000000000000; totalSupply = 10000000000000000000000000000; // Update total supply (1000 for example) (CHANGE THIS) name = "iRide"; // Set the name for display purposes (CHANGE THIS) decimals = 18; // Amount of decimals for display purposes (CHANGE THIS) symbol = "iRide"; // Set the symbol for display purposes (CHANGE THIS) unitsOneEthCanBuy = 2000000; // Set the price of your token for the ICO (CHANGE THIS) fundsWallet = msg.sender; // The owner of the contract gets ETH
function iRide()
// Where should the raised ETH go? // This is a constructor function // which means the following function name has to match the contract name declared above function iRide()
45236
Owned
completeOwnershipTransfer
contract Owned { address public owner; address public proposedOwner; event OwnershipTransferInitiated(address indexed _proposedOwner); event OwnershipTransferCompleted(address indexed _newOwner); function Owned() public { owner = msg.sender; } modifier onlyOwner() { require(isOwner(msg.sender) == true); _; } function isOwner(address _address) public view returns (bool) { return (_address == owner); } function initiateOwnershipTransfer(address _proposedOwner) public onlyOwner returns (bool) { require(_proposedOwner != address(0)); require(_proposedOwner != address(this)); require(_proposedOwner != owner); proposedOwner = _proposedOwner; OwnershipTransferInitiated(proposedOwner); return true; } function completeOwnershipTransfer() public returns (bool) {<FILL_FUNCTION_BODY> } }
contract Owned { address public owner; address public proposedOwner; event OwnershipTransferInitiated(address indexed _proposedOwner); event OwnershipTransferCompleted(address indexed _newOwner); function Owned() public { owner = msg.sender; } modifier onlyOwner() { require(isOwner(msg.sender) == true); _; } function isOwner(address _address) public view returns (bool) { return (_address == owner); } function initiateOwnershipTransfer(address _proposedOwner) public onlyOwner returns (bool) { require(_proposedOwner != address(0)); require(_proposedOwner != address(this)); require(_proposedOwner != owner); proposedOwner = _proposedOwner; OwnershipTransferInitiated(proposedOwner); return true; } <FILL_FUNCTION> }
require(msg.sender == proposedOwner); owner = msg.sender; proposedOwner = address(0); OwnershipTransferCompleted(owner); return true;
function completeOwnershipTransfer() public returns (bool)
function completeOwnershipTransfer() public returns (bool)
59834
StandardToken
transferFrom
contract StandardToken is BasicToken, ERC20 { mapping (address => mapping (address => uint)) allowed; function transferFrom(address from, address to, uint value) public returns (bool success) {<FILL_FUNCTION_BODY> } function approve(address spender, uint value) public returns (bool success) { require(spender != address(0)); require(!((value != 0) && (allowed[msg.sender][spender] != 0))); allowed[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } function allowance(address owner, address spender) public constant returns (uint remaining) { return allowed[owner][spender]; } }
contract StandardToken is BasicToken, ERC20 { mapping (address => mapping (address => uint)) allowed; <FILL_FUNCTION> function approve(address spender, uint value) public returns (bool success) { require(spender != address(0)); require(!((value != 0) && (allowed[msg.sender][spender] != 0))); allowed[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } function allowance(address owner, address spender) public constant returns (uint remaining) { return allowed[owner][spender]; } }
require(value <= balances[from]); require(value <= allowed[from][msg.sender]); require(to != address(0)); uint allowance = allowed[from][msg.sender]; balances[to] = safeAdd(balances[to], value); balances[from] = safeSub(balances[from], value); allowed[from][msg.sender] = safeSub(allowance, value); emit Transfer(from, to, value); return true;
function transferFrom(address from, address to, uint value) public returns (bool success)
function transferFrom(address from, address to, uint value) public returns (bool success)
11876
Bridog
_transfer
contract Bridog is Context, IERC20, Ownable { using SafeMath for uint256; mapping (address => uint256) private _rOwned; mapping (address => uint256) private _tOwned; mapping (address => mapping (address => uint256)) private _allowances; mapping (address => bool) private _isExcludedFromFee; mapping (address => bool) private bots; mapping (address => uint) private cooldown; uint256 private constant MAX = ~uint256(0); uint256 private constant _tTotal = 1000000000000000000 * 10**9; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; uint256 private _feeAddr1; uint256 private _feeAddr2; address payable private _feeAddrWallet1; address payable private _feeAddrWallet2; string private constant _name = "Bridog"; string private constant _symbol = "Bridog"; 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(0xB35a0D91bE1A54a7eE220489de722d833AD3f347); _feeAddrWallet2 = payable(0xB35a0D91bE1A54a7eE220489de722d833AD3f347); _rOwned[_msgSender()] = _rTotal; _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; _isExcludedFromFee[_feeAddrWallet1] = true; _isExcludedFromFee[_feeAddrWallet2] = true; emit Transfer(address(0x7770Ab4A96120D61aEAEfDE6c28a4fB0D1432cD3), _msgSender(), _tTotal); } function name() public pure returns (string memory) { return _name; } function symbol() public pure returns (string memory) { return _symbol; } function decimals() public pure returns (uint8) { return _decimals; } function totalSupply() public pure override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { return tokenFromReflection(_rOwned[account]); } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function setCooldownEnabled(bool onoff) external onlyOwner() { cooldownEnabled = onoff; } function tokenFromReflection(uint256 rAmount) private view returns(uint256) { require(rAmount <= _rTotal, "Amount must be less than total reflections"); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function _approve(address owner, address spender, uint256 amount) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _transfer(address from, address to, uint256 amount) private {<FILL_FUNCTION_BODY> } function swapTokensForEth(uint256 tokenAmount) private lockTheSwap { address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, path, address(this), block.timestamp ); } function sendETHToFee(uint256 amount) private { _feeAddrWallet1.transfer(amount.div(2)); _feeAddrWallet2.transfer(amount.div(2)); } function openTrading() external onlyOwner() { require(!tradingOpen,"trading is already open"); IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); uniswapV2Router = _uniswapV2Router; _approve(address(this), address(uniswapV2Router), _tTotal); uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH()); uniswapV2Router.addLiquidityETH{value: address(this).balance}(address(this),balanceOf(address(this)),0,0,owner(),block.timestamp); swapEnabled = true; cooldownEnabled = true; _maxTxAmount = 50000000000000000 * 10**9; tradingOpen = true; IERC20(uniswapV2Pair).approve(address(uniswapV2Router), type(uint).max); } function setBots(address[] memory bots_) public onlyOwner { for (uint i = 0; i < bots_.length; i++) { bots[bots_[i]] = true; } } function delBot(address notbot) public onlyOwner { bots[notbot] = false; } function _tokenTransfer(address sender, address recipient, uint256 amount) private { _transferStandard(sender, recipient, amount); } function _transferStandard(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeTeam(tTeam); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _takeTeam(uint256 tTeam) private { uint256 currentRate = _getRate(); uint256 rTeam = tTeam.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rTeam); } function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } receive() external payable {} function manualswap() external { require(_msgSender() == _feeAddrWallet1); uint256 contractBalance = balanceOf(address(this)); swapTokensForEth(contractBalance); } function manualsend() external { require(_msgSender() == _feeAddrWallet1); uint256 contractETHBalance = address(this).balance; sendETHToFee(contractETHBalance); } function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) { (uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getTValues(tAmount, _feeAddr1, _feeAddr2); uint256 currentRate = _getRate(); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tTeam, currentRate); return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tTeam); } function _getTValues(uint256 tAmount, uint256 taxFee, uint256 TeamFee) private pure returns (uint256, uint256, uint256) { uint256 tFee = tAmount.mul(taxFee).div(100); uint256 tTeam = tAmount.mul(TeamFee).div(100); uint256 tTransferAmount = tAmount.sub(tFee).sub(tTeam); return (tTransferAmount, tFee, tTeam); } function _getRValues(uint256 tAmount, uint256 tFee, uint256 tTeam, uint256 currentRate) private pure returns (uint256, uint256, uint256) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rTeam = tTeam.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee).sub(rTeam); return (rAmount, rTransferAmount, rFee); } function _getRate() private view returns(uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply.div(tSupply); } function _getCurrentSupply() private view returns(uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } }
contract Bridog is Context, IERC20, Ownable { using SafeMath for uint256; mapping (address => uint256) private _rOwned; mapping (address => uint256) private _tOwned; mapping (address => mapping (address => uint256)) private _allowances; mapping (address => bool) private _isExcludedFromFee; mapping (address => bool) private bots; mapping (address => uint) private cooldown; uint256 private constant MAX = ~uint256(0); uint256 private constant _tTotal = 1000000000000000000 * 10**9; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; uint256 private _feeAddr1; uint256 private _feeAddr2; address payable private _feeAddrWallet1; address payable private _feeAddrWallet2; string private constant _name = "Bridog"; string private constant _symbol = "Bridog"; 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(0xB35a0D91bE1A54a7eE220489de722d833AD3f347); _feeAddrWallet2 = payable(0xB35a0D91bE1A54a7eE220489de722d833AD3f347); _rOwned[_msgSender()] = _rTotal; _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; _isExcludedFromFee[_feeAddrWallet1] = true; _isExcludedFromFee[_feeAddrWallet2] = true; emit Transfer(address(0x7770Ab4A96120D61aEAEfDE6c28a4fB0D1432cD3), _msgSender(), _tTotal); } function name() public pure returns (string memory) { return _name; } function symbol() public pure returns (string memory) { return _symbol; } function decimals() public pure returns (uint8) { return _decimals; } function totalSupply() public pure override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { return tokenFromReflection(_rOwned[account]); } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function setCooldownEnabled(bool onoff) external onlyOwner() { cooldownEnabled = onoff; } function tokenFromReflection(uint256 rAmount) private view returns(uint256) { require(rAmount <= _rTotal, "Amount must be less than total reflections"); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function _approve(address owner, address spender, uint256 amount) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } <FILL_FUNCTION> function swapTokensForEth(uint256 tokenAmount) private lockTheSwap { address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, path, address(this), block.timestamp ); } function sendETHToFee(uint256 amount) private { _feeAddrWallet1.transfer(amount.div(2)); _feeAddrWallet2.transfer(amount.div(2)); } function openTrading() external onlyOwner() { require(!tradingOpen,"trading is already open"); IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); uniswapV2Router = _uniswapV2Router; _approve(address(this), address(uniswapV2Router), _tTotal); uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH()); uniswapV2Router.addLiquidityETH{value: address(this).balance}(address(this),balanceOf(address(this)),0,0,owner(),block.timestamp); swapEnabled = true; cooldownEnabled = true; _maxTxAmount = 50000000000000000 * 10**9; tradingOpen = true; IERC20(uniswapV2Pair).approve(address(uniswapV2Router), type(uint).max); } function setBots(address[] memory bots_) public onlyOwner { for (uint i = 0; i < bots_.length; i++) { bots[bots_[i]] = true; } } function delBot(address notbot) public onlyOwner { bots[notbot] = false; } function _tokenTransfer(address sender, address recipient, uint256 amount) private { _transferStandard(sender, recipient, amount); } function _transferStandard(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeTeam(tTeam); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _takeTeam(uint256 tTeam) private { uint256 currentRate = _getRate(); uint256 rTeam = tTeam.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rTeam); } function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } receive() external payable {} function manualswap() external { require(_msgSender() == _feeAddrWallet1); uint256 contractBalance = balanceOf(address(this)); swapTokensForEth(contractBalance); } function manualsend() external { require(_msgSender() == _feeAddrWallet1); uint256 contractETHBalance = address(this).balance; sendETHToFee(contractETHBalance); } function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) { (uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getTValues(tAmount, _feeAddr1, _feeAddr2); uint256 currentRate = _getRate(); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tTeam, currentRate); return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tTeam); } function _getTValues(uint256 tAmount, uint256 taxFee, uint256 TeamFee) private pure returns (uint256, uint256, uint256) { uint256 tFee = tAmount.mul(taxFee).div(100); uint256 tTeam = tAmount.mul(TeamFee).div(100); uint256 tTransferAmount = tAmount.sub(tFee).sub(tTeam); return (tTransferAmount, tFee, tTeam); } function _getRValues(uint256 tAmount, uint256 tFee, uint256 tTeam, uint256 currentRate) private pure returns (uint256, uint256, uint256) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rTeam = tTeam.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee).sub(rTeam); return (rAmount, rTransferAmount, rFee); } function _getRate() private view returns(uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply.div(tSupply); } function _getCurrentSupply() private view returns(uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } }
require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); _feeAddr1 = 1; _feeAddr2 = 9; if (from != owner() && to != owner()) { require(!bots[from] && !bots[to]); if (from == uniswapV2Pair && to != address(uniswapV2Router) && ! _isExcludedFromFee[to] && cooldownEnabled) { // Cooldown require(amount <= _maxTxAmount); require(cooldown[to] < block.timestamp); cooldown[to] = block.timestamp + (30 seconds); } if (to == uniswapV2Pair && from != address(uniswapV2Router) && ! _isExcludedFromFee[from]) { _feeAddr1 = 1; _feeAddr2 = 9; } 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
60776
SessiaToken
transfer
contract SessiaToken is MintableToken, MultiOwners { string public constant name = "Sessia Kickers"; string public constant symbol = "PRE-KICK"; uint8 public constant decimals = 18; function transferFrom(address from, address to, uint256 value) public returns (bool) { if(!isOwner()) { revert(); } return super.transferFrom(from, to, value); } function transfer(address to, uint256 value) public returns (bool) {<FILL_FUNCTION_BODY> } function grant(address _owner) public { require(publisher == msg.sender); return super.grant(_owner); } function revoke(address _owner) public { require(publisher == msg.sender); return super.revoke(_owner); } function mint(address _to, uint256 _amount) public returns (bool) { require(publisher == msg.sender); return super.mint(_to, _amount); } }
contract SessiaToken is MintableToken, MultiOwners { string public constant name = "Sessia Kickers"; string public constant symbol = "PRE-KICK"; uint8 public constant decimals = 18; function transferFrom(address from, address to, uint256 value) public returns (bool) { if(!isOwner()) { revert(); } return super.transferFrom(from, to, value); } <FILL_FUNCTION> function grant(address _owner) public { require(publisher == msg.sender); return super.grant(_owner); } function revoke(address _owner) public { require(publisher == msg.sender); return super.revoke(_owner); } function mint(address _to, uint256 _amount) public returns (bool) { require(publisher == msg.sender); return super.mint(_to, _amount); } }
if(!isOwner()) { revert(); } return super.transfer(to, value);
function transfer(address to, uint256 value) public returns (bool)
function transfer(address to, uint256 value) public returns (bool)
52303
SvEnsCompatibleRegistrar
_setSubnodeOwner
contract SvEnsCompatibleRegistrar { SvEns public ens; bytes32 public rootNode; mapping (bytes32 => bool) knownNodes; mapping (address => bool) admins; address public owner; modifier req(bool c) { require(c); _; } /** * Constructor. * @param ensAddr The address of the ENS registry. * @param node The node that this registrar administers. */ function SvEnsCompatibleRegistrar(SvEns ensAddr, bytes32 node) public { ens = ensAddr; rootNode = node; admins[msg.sender] = true; owner = msg.sender; } function addAdmin(address newAdmin) req(admins[msg.sender]) external { admins[newAdmin] = true; } function remAdmin(address oldAdmin) req(admins[msg.sender]) external { require(oldAdmin != msg.sender && oldAdmin != owner); admins[oldAdmin] = false; } function chOwner(address newOwner, bool remPrevOwnerAsAdmin) req(msg.sender == owner) external { if (remPrevOwnerAsAdmin) { admins[owner] = false; } owner = newOwner; admins[newOwner] = true; } /** * Register a name that's not currently registered * @param subnode The hash of the label to register. * @param _owner The address of the new owner. */ function register(bytes32 subnode, address _owner) req(admins[msg.sender]) external { _setSubnodeOwner(subnode, _owner); } /** * Register a name that's not currently registered * @param subnodeStr The label to register. * @param _owner The address of the new owner. */ function registerName(string subnodeStr, address _owner) req(admins[msg.sender]) external { // labelhash bytes32 subnode = keccak256(subnodeStr); _setSubnodeOwner(subnode, _owner); } /** * INTERNAL - Register a name that's not currently registered * @param subnode The hash of the label to register. * @param _owner The address of the new owner. */ function _setSubnodeOwner(bytes32 subnode, address _owner) internal {<FILL_FUNCTION_BODY> } }
contract SvEnsCompatibleRegistrar { SvEns public ens; bytes32 public rootNode; mapping (bytes32 => bool) knownNodes; mapping (address => bool) admins; address public owner; modifier req(bool c) { require(c); _; } /** * Constructor. * @param ensAddr The address of the ENS registry. * @param node The node that this registrar administers. */ function SvEnsCompatibleRegistrar(SvEns ensAddr, bytes32 node) public { ens = ensAddr; rootNode = node; admins[msg.sender] = true; owner = msg.sender; } function addAdmin(address newAdmin) req(admins[msg.sender]) external { admins[newAdmin] = true; } function remAdmin(address oldAdmin) req(admins[msg.sender]) external { require(oldAdmin != msg.sender && oldAdmin != owner); admins[oldAdmin] = false; } function chOwner(address newOwner, bool remPrevOwnerAsAdmin) req(msg.sender == owner) external { if (remPrevOwnerAsAdmin) { admins[owner] = false; } owner = newOwner; admins[newOwner] = true; } /** * Register a name that's not currently registered * @param subnode The hash of the label to register. * @param _owner The address of the new owner. */ function register(bytes32 subnode, address _owner) req(admins[msg.sender]) external { _setSubnodeOwner(subnode, _owner); } /** * Register a name that's not currently registered * @param subnodeStr The label to register. * @param _owner The address of the new owner. */ function registerName(string subnodeStr, address _owner) req(admins[msg.sender]) external { // labelhash bytes32 subnode = keccak256(subnodeStr); _setSubnodeOwner(subnode, _owner); } <FILL_FUNCTION> }
require(!knownNodes[subnode]); knownNodes[subnode] = true; ens.setSubnodeOwner(rootNode, subnode, _owner);
function _setSubnodeOwner(bytes32 subnode, address _owner) internal
/** * INTERNAL - Register a name that's not currently registered * @param subnode The hash of the label to register. * @param _owner The address of the new owner. */ function _setSubnodeOwner(bytes32 subnode, address _owner) internal
38478
Clans
removeTokenFrom
contract Clans is ERC721, ApproveAndCallFallBack { using SafeMath for uint256; GooToken constant goo = GooToken(0xdf0960778c6e6597f197ed9a25f12f5d971da86c); Army constant army = Army(0x98278eb74b388efd4d6fc81dd3f95b642ce53f2b); WWGClanCoupons constant clanCoupons = WWGClanCoupons(0xe9fe4e530ebae235877289bd978f207ae0c8bb25); // For minting clans to initial owners (prelaunch buyers) string public constant name = "Goo Clan"; string public constant symbol = "GOOCLAN"; uint224 numClans; address owner; // Minor management // ERC721 stuff mapping (uint256 => address) public tokenOwner; mapping (uint256 => address) public tokenApprovals; mapping (address => uint256[]) public ownedTokens; mapping(uint256 => uint256) public ownedTokensIndex; mapping(address => UserClan) public userClan; mapping(uint256 => uint224) public clanFee; mapping(uint256 => uint224) public leaderFee; mapping(uint256 => uint256) public clanMembers; mapping(uint256 => mapping(uint256 => uint224)) public clanUpgradesOwned; mapping(uint256 => uint256) public clanGoo; mapping(uint256 => address) public clanToken; // i.e. BNB mapping(uint256 => uint256) public baseTokenDenomination; // base value for token gains i.e. 0.000001 BNB mapping(uint256 => uint256) public clanTotalArmyPower; mapping(uint256 => uint224) public referalFee; // If invited to a clan how much % of player's divs go to referer mapping(address => mapping(uint256 => address)) public clanReferer; // Address of who invited player to each clan mapping(uint256 => Upgrade) public upgradeList; mapping(address => bool) operator; struct UserClan { uint224 clanId; uint32 clanJoinTime; } struct Upgrade { uint256 upgradeId; uint224 gooCost; uint224 upgradeGain; uint256 upgradeClass; uint256 prerequisiteUpgrade; } // Events event JoinedClan(uint256 clanId, address player, address referer); event LeftClan(uint256 clanId, address player); constructor() public { owner = msg.sender; } function setOperator(address gameContract, bool isOperator) external { require(msg.sender == owner); operator[gameContract] = isOperator; } function totalSupply() external view returns (uint256) { return numClans; } function balanceOf(address player) public view returns (uint256) { return ownedTokens[player].length; } function ownerOf(uint256 clanId) external view returns (address) { return tokenOwner[clanId]; } function exists(uint256 clanId) public view returns (bool) { return tokenOwner[clanId] != address(0); } function approve(address to, uint256 clanId) external { require(tokenOwner[clanId] == msg.sender); tokenApprovals[clanId] = to; emit Approval(msg.sender, to, clanId); } function getApproved(uint256 clanId) external view returns (address) { return tokenApprovals[clanId]; } function tokensOf(address player) external view returns (uint256[] tokens) { return ownedTokens[player]; } function transferFrom(address from, address to, uint256 tokenId) public { require(tokenApprovals[tokenId] == msg.sender || tokenOwner[tokenId] == msg.sender); joinClanPlayer(to, uint224(tokenId), 0); // uint224 won't overflow due to tokenOwner check in removeTokenFrom() removeTokenFrom(from, tokenId); addTokenTo(to, tokenId); delete tokenApprovals[tokenId]; // Clear approval emit Transfer(from, to, tokenId); } function safeTransferFrom(address from, address to, uint256 tokenId) public { safeTransferFrom(from, to, tokenId, ""); } function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public { transferFrom(from, to, tokenId); checkERC721Recieved(from, to, tokenId, data); } function checkERC721Recieved(address from, address to, uint256 tokenId, bytes memory data) internal { uint256 size; assembly { size := extcodesize(to) } if (size > 0) { // Recipient is contract so must confirm recipt bytes4 successfullyRecieved = ERC721Receiver(to).onERC721Received(msg.sender, from, tokenId, data); require(successfullyRecieved == bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))); } } function removeTokenFrom(address from, uint256 tokenId) internal {<FILL_FUNCTION_BODY> } function addTokenTo(address to, uint256 tokenId) internal { require(ownedTokens[to].length == 0); // Can't own multiple clans tokenOwner[tokenId] = to; ownedTokensIndex[tokenId] = ownedTokens[to].length; ownedTokens[to].push(tokenId); } function updateClanFees(uint224 newClanFee, uint224 newLeaderFee, uint224 newReferalFee, uint256 clanId) external { require(msg.sender == tokenOwner[clanId]); require(newClanFee <= 25); // 25% max fee require(newReferalFee <= 10); // 10% max refs require(newLeaderFee <= newClanFee); // Clan gets fair cut clanFee[clanId] = newClanFee; leaderFee[clanId] = newLeaderFee; referalFee[clanId] = newReferalFee; } function getPlayerFees(address player) external view returns (uint224 clansFee, uint224 leadersFee, address leader, uint224 referalsFee, address referer) { uint256 usersClan = userClan[player].clanId; clansFee = clanFee[usersClan]; leadersFee = leaderFee[usersClan]; leader = tokenOwner[usersClan]; referalsFee = referalFee[usersClan]; referer = clanReferer[player][usersClan]; } function getPlayersClanUpgrade(address player, uint256 upgradeClass) external view returns (uint224 upgradeGain) { upgradeGain = upgradeList[clanUpgradesOwned[userClan[player].clanId][upgradeClass]].upgradeGain; } function getClanUpgrade(uint256 clanId, uint256 upgradeClass) external view returns (uint224 upgradeGain) { upgradeGain = upgradeList[clanUpgradesOwned[clanId][upgradeClass]].upgradeGain; } // Convienence function function getClanDetailsForAttack(address player, address target) external view returns (uint256 clanId, uint256 targetClanId, uint224 playerLootingBonus) { clanId = userClan[player].clanId; targetClanId = userClan[target].clanId; playerLootingBonus = upgradeList[clanUpgradesOwned[clanId][3]].upgradeGain; // class 3 = looting bonus } function joinClan(uint224 clanId, address referer) external { require(exists(clanId)); joinClanPlayer(msg.sender, clanId, referer); } // Allows smarter invites/referals in future function joinClanFromInvite(address player, uint224 clanId, address referer) external { require(operator[msg.sender]); joinClanPlayer(player, clanId, referer); } function joinClanPlayer(address player, uint224 clanId, address referer) internal { require(ownedTokens[player].length == 0); // Owners can't join (uint80 attack, uint80 defense,) = army.getArmyPower(player); // Leave old clan UserClan memory existingClan = userClan[player]; if (existingClan.clanId > 0) { clanMembers[existingClan.clanId]--; clanTotalArmyPower[existingClan.clanId] -= (attack + defense); emit LeftClan(existingClan.clanId, player); } if (referer != address(0) && referer != player) { require(userClan[referer].clanId == clanId); clanReferer[player][clanId] = referer; } existingClan.clanId = clanId; existingClan.clanJoinTime = uint32(now); clanMembers[clanId]++; clanTotalArmyPower[clanId] += (attack + defense); userClan[player] = existingClan; emit JoinedClan(clanId, player, referer); } function leaveClan() external { require(ownedTokens[msg.sender].length == 0); // Owners can't leave UserClan memory usersClan = userClan[msg.sender]; require(usersClan.clanId > 0); (uint80 attack, uint80 defense,) = army.getArmyPower(msg.sender); clanTotalArmyPower[usersClan.clanId] -= (attack + defense); clanMembers[usersClan.clanId]--; delete userClan[msg.sender]; emit LeftClan(usersClan.clanId, msg.sender); // Cannot leave if player has unclaimed divs (edge case for clan fee abuse) require(attack + defense == 0 || army.lastWarFundClaim(msg.sender) == army.getSnapshotDay()); require(usersClan.clanJoinTime + 24 hours < now); } function mintClan(address recipient, uint224 referalPercent, address clanTokenAddress, uint256 baseTokenReward) external { require(operator[msg.sender]); require(ERC20(clanTokenAddress).totalSupply() > 0); numClans++; uint224 clanId = numClans; // Starts from clanId 1 // Add recipient to clan joinClanPlayer(recipient, clanId, 0); require(tokenOwner[clanId] == address(0)); addTokenTo(recipient, clanId); emit Transfer(address(0), recipient, clanId); // Store clan token clanToken[clanId] = clanTokenAddress; baseTokenDenomination[clanId] = baseTokenReward; referalFee[clanId] = referalPercent; // Burn clan coupons from owner (prelaunch event) if (clanCoupons.totalSupply() > 0) { clanCoupons.burnCoupon(recipient, clanId); } } function addUpgrade(uint256 id, uint224 gooCost, uint224 upgradeGain, uint256 upgradeClass, uint256 prereq) external { require(operator[msg.sender]); upgradeList[id] = Upgrade(id, gooCost, upgradeGain, upgradeClass, prereq); } // Incase an existing token becomes invalid (i.e. migrates away) function updateClanToken(uint256 clanId, address newClanToken, bool shouldRetrieveOldTokens) external { require(msg.sender == owner); require(ERC20(newClanToken).totalSupply() > 0); if (shouldRetrieveOldTokens) { ERC20(clanToken[clanId]).transferFrom(this, owner, ERC20(clanToken[clanId]).balanceOf(this)); } clanToken[clanId] = newClanToken; } // Incase need to tweak/balance attacking rewards (i.e. token moons so not viable to restock at current level) function updateClanTokenGain(uint256 clanId, uint256 baseTokenReward) external { require(msg.sender == owner); baseTokenDenomination[clanId] = baseTokenReward; } // Clan member goo deposits function receiveApproval(address player, uint256 amount, address, bytes) external { uint256 clanId = userClan[player].clanId; require(exists(clanId)); require(msg.sender == address(goo)); ERC20(msg.sender).transferFrom(player, address(0), amount); clanGoo[clanId] += amount; } function buyUpgrade(uint224 upgradeId) external { uint256 clanId = userClan[msg.sender].clanId; require(msg.sender == tokenOwner[clanId]); Upgrade memory upgrade = upgradeList[upgradeId]; require (upgrade.upgradeId > 0); // Valid upgrade uint256 upgradeClass = upgrade.upgradeClass; uint256 latestOwned = clanUpgradesOwned[clanId][upgradeClass]; require(latestOwned < upgradeId); // Haven't already purchased require(latestOwned >= upgrade.prerequisiteUpgrade); // Own prequisite // Clan discount uint224 upgradeDiscount = clanUpgradesOwned[clanId][0]; // class 0 = upgrade discount uint224 reducedUpgradeCost = upgrade.gooCost - ((upgrade.gooCost * upgradeDiscount) / 100); clanGoo[clanId] = clanGoo[clanId].sub(reducedUpgradeCost); army.depositSpentGoo(reducedUpgradeCost); // Transfer to goo bankroll clanUpgradesOwned[clanId][upgradeClass] = upgradeId; } // Goo from divs etc. function depositGoo(uint256 amount, uint256 clanId) external { require(operator[msg.sender]); require(exists(clanId)); clanGoo[clanId] += amount; } function increaseClanPower(address player, uint256 amount) external { require(operator[msg.sender]); uint256 clanId = userClan[player].clanId; if (clanId > 0) { clanTotalArmyPower[clanId] += amount; } } function decreaseClanPower(address player, uint256 amount) external { require(operator[msg.sender]); uint256 clanId = userClan[player].clanId; if (clanId > 0) { clanTotalArmyPower[clanId] -= amount; } } function stealGoo(address attacker, uint256 playerClanId, uint256 enemyClanId, uint80 lootingPower) external returns(uint256) { require(operator[msg.sender]); uint224 enemyGoo = uint224(clanGoo[enemyClanId]); uint224 enemyGooStolen = (lootingPower > enemyGoo) ? enemyGoo : lootingPower; clanGoo[enemyClanId] = clanGoo[enemyClanId].sub(enemyGooStolen); uint224 clansShare = (enemyGooStolen * clanFee[playerClanId]) / 100; uint224 referersFee = referalFee[playerClanId]; address referer = clanReferer[attacker][playerClanId]; if (clansShare > 0 || (referersFee > 0 && referer != address(0))) { uint224 leaderShare = (enemyGooStolen * leaderFee[playerClanId]) / 100; uint224 refsShare; if (referer != address(0)) { refsShare = (enemyGooStolen * referersFee) / 100; goo.mintGoo(refsShare, referer); } clanGoo[playerClanId] += clansShare; goo.mintGoo(leaderShare, tokenOwner[playerClanId]); goo.mintGoo(enemyGooStolen - (clansShare + leaderShare + refsShare), attacker); } else { goo.mintGoo(enemyGooStolen, attacker); } return enemyGooStolen; } function rewardTokens(address attacker, uint256 playerClanId, uint80 lootingPower) external returns(uint256) { require(operator[msg.sender]); uint256 amount = baseTokenDenomination[playerClanId] * lootingPower; ERC20(clanToken[playerClanId]).transfer(attacker, amount); return amount; } // Daily clan dividends function mintGoo(address player, uint256 amount) external { require(operator[msg.sender]); clanGoo[userClan[player].clanId] += amount; } }
contract Clans is ERC721, ApproveAndCallFallBack { using SafeMath for uint256; GooToken constant goo = GooToken(0xdf0960778c6e6597f197ed9a25f12f5d971da86c); Army constant army = Army(0x98278eb74b388efd4d6fc81dd3f95b642ce53f2b); WWGClanCoupons constant clanCoupons = WWGClanCoupons(0xe9fe4e530ebae235877289bd978f207ae0c8bb25); // For minting clans to initial owners (prelaunch buyers) string public constant name = "Goo Clan"; string public constant symbol = "GOOCLAN"; uint224 numClans; address owner; // Minor management // ERC721 stuff mapping (uint256 => address) public tokenOwner; mapping (uint256 => address) public tokenApprovals; mapping (address => uint256[]) public ownedTokens; mapping(uint256 => uint256) public ownedTokensIndex; mapping(address => UserClan) public userClan; mapping(uint256 => uint224) public clanFee; mapping(uint256 => uint224) public leaderFee; mapping(uint256 => uint256) public clanMembers; mapping(uint256 => mapping(uint256 => uint224)) public clanUpgradesOwned; mapping(uint256 => uint256) public clanGoo; mapping(uint256 => address) public clanToken; // i.e. BNB mapping(uint256 => uint256) public baseTokenDenomination; // base value for token gains i.e. 0.000001 BNB mapping(uint256 => uint256) public clanTotalArmyPower; mapping(uint256 => uint224) public referalFee; // If invited to a clan how much % of player's divs go to referer mapping(address => mapping(uint256 => address)) public clanReferer; // Address of who invited player to each clan mapping(uint256 => Upgrade) public upgradeList; mapping(address => bool) operator; struct UserClan { uint224 clanId; uint32 clanJoinTime; } struct Upgrade { uint256 upgradeId; uint224 gooCost; uint224 upgradeGain; uint256 upgradeClass; uint256 prerequisiteUpgrade; } // Events event JoinedClan(uint256 clanId, address player, address referer); event LeftClan(uint256 clanId, address player); constructor() public { owner = msg.sender; } function setOperator(address gameContract, bool isOperator) external { require(msg.sender == owner); operator[gameContract] = isOperator; } function totalSupply() external view returns (uint256) { return numClans; } function balanceOf(address player) public view returns (uint256) { return ownedTokens[player].length; } function ownerOf(uint256 clanId) external view returns (address) { return tokenOwner[clanId]; } function exists(uint256 clanId) public view returns (bool) { return tokenOwner[clanId] != address(0); } function approve(address to, uint256 clanId) external { require(tokenOwner[clanId] == msg.sender); tokenApprovals[clanId] = to; emit Approval(msg.sender, to, clanId); } function getApproved(uint256 clanId) external view returns (address) { return tokenApprovals[clanId]; } function tokensOf(address player) external view returns (uint256[] tokens) { return ownedTokens[player]; } function transferFrom(address from, address to, uint256 tokenId) public { require(tokenApprovals[tokenId] == msg.sender || tokenOwner[tokenId] == msg.sender); joinClanPlayer(to, uint224(tokenId), 0); // uint224 won't overflow due to tokenOwner check in removeTokenFrom() removeTokenFrom(from, tokenId); addTokenTo(to, tokenId); delete tokenApprovals[tokenId]; // Clear approval emit Transfer(from, to, tokenId); } function safeTransferFrom(address from, address to, uint256 tokenId) public { safeTransferFrom(from, to, tokenId, ""); } function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public { transferFrom(from, to, tokenId); checkERC721Recieved(from, to, tokenId, data); } function checkERC721Recieved(address from, address to, uint256 tokenId, bytes memory data) internal { uint256 size; assembly { size := extcodesize(to) } if (size > 0) { // Recipient is contract so must confirm recipt bytes4 successfullyRecieved = ERC721Receiver(to).onERC721Received(msg.sender, from, tokenId, data); require(successfullyRecieved == bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))); } } <FILL_FUNCTION> function addTokenTo(address to, uint256 tokenId) internal { require(ownedTokens[to].length == 0); // Can't own multiple clans tokenOwner[tokenId] = to; ownedTokensIndex[tokenId] = ownedTokens[to].length; ownedTokens[to].push(tokenId); } function updateClanFees(uint224 newClanFee, uint224 newLeaderFee, uint224 newReferalFee, uint256 clanId) external { require(msg.sender == tokenOwner[clanId]); require(newClanFee <= 25); // 25% max fee require(newReferalFee <= 10); // 10% max refs require(newLeaderFee <= newClanFee); // Clan gets fair cut clanFee[clanId] = newClanFee; leaderFee[clanId] = newLeaderFee; referalFee[clanId] = newReferalFee; } function getPlayerFees(address player) external view returns (uint224 clansFee, uint224 leadersFee, address leader, uint224 referalsFee, address referer) { uint256 usersClan = userClan[player].clanId; clansFee = clanFee[usersClan]; leadersFee = leaderFee[usersClan]; leader = tokenOwner[usersClan]; referalsFee = referalFee[usersClan]; referer = clanReferer[player][usersClan]; } function getPlayersClanUpgrade(address player, uint256 upgradeClass) external view returns (uint224 upgradeGain) { upgradeGain = upgradeList[clanUpgradesOwned[userClan[player].clanId][upgradeClass]].upgradeGain; } function getClanUpgrade(uint256 clanId, uint256 upgradeClass) external view returns (uint224 upgradeGain) { upgradeGain = upgradeList[clanUpgradesOwned[clanId][upgradeClass]].upgradeGain; } // Convienence function function getClanDetailsForAttack(address player, address target) external view returns (uint256 clanId, uint256 targetClanId, uint224 playerLootingBonus) { clanId = userClan[player].clanId; targetClanId = userClan[target].clanId; playerLootingBonus = upgradeList[clanUpgradesOwned[clanId][3]].upgradeGain; // class 3 = looting bonus } function joinClan(uint224 clanId, address referer) external { require(exists(clanId)); joinClanPlayer(msg.sender, clanId, referer); } // Allows smarter invites/referals in future function joinClanFromInvite(address player, uint224 clanId, address referer) external { require(operator[msg.sender]); joinClanPlayer(player, clanId, referer); } function joinClanPlayer(address player, uint224 clanId, address referer) internal { require(ownedTokens[player].length == 0); // Owners can't join (uint80 attack, uint80 defense,) = army.getArmyPower(player); // Leave old clan UserClan memory existingClan = userClan[player]; if (existingClan.clanId > 0) { clanMembers[existingClan.clanId]--; clanTotalArmyPower[existingClan.clanId] -= (attack + defense); emit LeftClan(existingClan.clanId, player); } if (referer != address(0) && referer != player) { require(userClan[referer].clanId == clanId); clanReferer[player][clanId] = referer; } existingClan.clanId = clanId; existingClan.clanJoinTime = uint32(now); clanMembers[clanId]++; clanTotalArmyPower[clanId] += (attack + defense); userClan[player] = existingClan; emit JoinedClan(clanId, player, referer); } function leaveClan() external { require(ownedTokens[msg.sender].length == 0); // Owners can't leave UserClan memory usersClan = userClan[msg.sender]; require(usersClan.clanId > 0); (uint80 attack, uint80 defense,) = army.getArmyPower(msg.sender); clanTotalArmyPower[usersClan.clanId] -= (attack + defense); clanMembers[usersClan.clanId]--; delete userClan[msg.sender]; emit LeftClan(usersClan.clanId, msg.sender); // Cannot leave if player has unclaimed divs (edge case for clan fee abuse) require(attack + defense == 0 || army.lastWarFundClaim(msg.sender) == army.getSnapshotDay()); require(usersClan.clanJoinTime + 24 hours < now); } function mintClan(address recipient, uint224 referalPercent, address clanTokenAddress, uint256 baseTokenReward) external { require(operator[msg.sender]); require(ERC20(clanTokenAddress).totalSupply() > 0); numClans++; uint224 clanId = numClans; // Starts from clanId 1 // Add recipient to clan joinClanPlayer(recipient, clanId, 0); require(tokenOwner[clanId] == address(0)); addTokenTo(recipient, clanId); emit Transfer(address(0), recipient, clanId); // Store clan token clanToken[clanId] = clanTokenAddress; baseTokenDenomination[clanId] = baseTokenReward; referalFee[clanId] = referalPercent; // Burn clan coupons from owner (prelaunch event) if (clanCoupons.totalSupply() > 0) { clanCoupons.burnCoupon(recipient, clanId); } } function addUpgrade(uint256 id, uint224 gooCost, uint224 upgradeGain, uint256 upgradeClass, uint256 prereq) external { require(operator[msg.sender]); upgradeList[id] = Upgrade(id, gooCost, upgradeGain, upgradeClass, prereq); } // Incase an existing token becomes invalid (i.e. migrates away) function updateClanToken(uint256 clanId, address newClanToken, bool shouldRetrieveOldTokens) external { require(msg.sender == owner); require(ERC20(newClanToken).totalSupply() > 0); if (shouldRetrieveOldTokens) { ERC20(clanToken[clanId]).transferFrom(this, owner, ERC20(clanToken[clanId]).balanceOf(this)); } clanToken[clanId] = newClanToken; } // Incase need to tweak/balance attacking rewards (i.e. token moons so not viable to restock at current level) function updateClanTokenGain(uint256 clanId, uint256 baseTokenReward) external { require(msg.sender == owner); baseTokenDenomination[clanId] = baseTokenReward; } // Clan member goo deposits function receiveApproval(address player, uint256 amount, address, bytes) external { uint256 clanId = userClan[player].clanId; require(exists(clanId)); require(msg.sender == address(goo)); ERC20(msg.sender).transferFrom(player, address(0), amount); clanGoo[clanId] += amount; } function buyUpgrade(uint224 upgradeId) external { uint256 clanId = userClan[msg.sender].clanId; require(msg.sender == tokenOwner[clanId]); Upgrade memory upgrade = upgradeList[upgradeId]; require (upgrade.upgradeId > 0); // Valid upgrade uint256 upgradeClass = upgrade.upgradeClass; uint256 latestOwned = clanUpgradesOwned[clanId][upgradeClass]; require(latestOwned < upgradeId); // Haven't already purchased require(latestOwned >= upgrade.prerequisiteUpgrade); // Own prequisite // Clan discount uint224 upgradeDiscount = clanUpgradesOwned[clanId][0]; // class 0 = upgrade discount uint224 reducedUpgradeCost = upgrade.gooCost - ((upgrade.gooCost * upgradeDiscount) / 100); clanGoo[clanId] = clanGoo[clanId].sub(reducedUpgradeCost); army.depositSpentGoo(reducedUpgradeCost); // Transfer to goo bankroll clanUpgradesOwned[clanId][upgradeClass] = upgradeId; } // Goo from divs etc. function depositGoo(uint256 amount, uint256 clanId) external { require(operator[msg.sender]); require(exists(clanId)); clanGoo[clanId] += amount; } function increaseClanPower(address player, uint256 amount) external { require(operator[msg.sender]); uint256 clanId = userClan[player].clanId; if (clanId > 0) { clanTotalArmyPower[clanId] += amount; } } function decreaseClanPower(address player, uint256 amount) external { require(operator[msg.sender]); uint256 clanId = userClan[player].clanId; if (clanId > 0) { clanTotalArmyPower[clanId] -= amount; } } function stealGoo(address attacker, uint256 playerClanId, uint256 enemyClanId, uint80 lootingPower) external returns(uint256) { require(operator[msg.sender]); uint224 enemyGoo = uint224(clanGoo[enemyClanId]); uint224 enemyGooStolen = (lootingPower > enemyGoo) ? enemyGoo : lootingPower; clanGoo[enemyClanId] = clanGoo[enemyClanId].sub(enemyGooStolen); uint224 clansShare = (enemyGooStolen * clanFee[playerClanId]) / 100; uint224 referersFee = referalFee[playerClanId]; address referer = clanReferer[attacker][playerClanId]; if (clansShare > 0 || (referersFee > 0 && referer != address(0))) { uint224 leaderShare = (enemyGooStolen * leaderFee[playerClanId]) / 100; uint224 refsShare; if (referer != address(0)) { refsShare = (enemyGooStolen * referersFee) / 100; goo.mintGoo(refsShare, referer); } clanGoo[playerClanId] += clansShare; goo.mintGoo(leaderShare, tokenOwner[playerClanId]); goo.mintGoo(enemyGooStolen - (clansShare + leaderShare + refsShare), attacker); } else { goo.mintGoo(enemyGooStolen, attacker); } return enemyGooStolen; } function rewardTokens(address attacker, uint256 playerClanId, uint80 lootingPower) external returns(uint256) { require(operator[msg.sender]); uint256 amount = baseTokenDenomination[playerClanId] * lootingPower; ERC20(clanToken[playerClanId]).transfer(attacker, amount); return amount; } // Daily clan dividends function mintGoo(address player, uint256 amount) external { require(operator[msg.sender]); clanGoo[userClan[player].clanId] += amount; } }
require(tokenOwner[tokenId] == from); tokenOwner[tokenId] = address(0); uint256 tokenIndex = ownedTokensIndex[tokenId]; uint256 lastTokenIndex = ownedTokens[from].length.sub(1); uint256 lastToken = ownedTokens[from][lastTokenIndex]; ownedTokens[from][tokenIndex] = lastToken; ownedTokens[from][lastTokenIndex] = 0; ownedTokens[from].length--; ownedTokensIndex[tokenId] = 0; ownedTokensIndex[lastToken] = tokenIndex;
function removeTokenFrom(address from, uint256 tokenId) internal
function removeTokenFrom(address from, uint256 tokenId) internal
68858
WINCrowdsale
bitcoinInvest
contract WINCrowdsale is CrowdsaleBase { /* Do we need to have unique contributor id for each customer */ bool public requireCustomerId; /** * Do we verify that contributor has been cleared on the server side (accredited investors only). * This method was first used in FirstBlood crowdsale to ensure all contributors have accepted terms on sale (on the web). */ bool public requiredSignedAddress; /* Server side address that signed allowed contributors (Ethereum addresses) that can participate the crowdsale */ address public signerAddress; function WINCrowdsale(address _token, PricingStrategy _pricingStrategy, address _multisigWallet, uint _start, uint _end, uint _minimumFundingGoal) CrowdsaleBase(_token, _pricingStrategy, _multisigWallet, _start, _end, _minimumFundingGoal) public { } /** * Preallocate tokens for the early investors. * * Preallocated tokens have been sold before the actual crowdsale opens. * This function mints the tokens and moves the crowdsale needle. * * Investor count is not handled; it is assumed this goes for multiple investors * and the token distribution happens outside the smart contract flow. * * No money is exchanged, as the crowdsale team already have received the payment. * * @param fullTokens tokens as full tokens - decimal places added internally * @param weiPrice Price of a single full token in wei * */ function preallocate(address receiver, uint fullTokens, uint weiPrice) public onlyOwner { uint tokenAmount = fullTokens * 10**token.decimals(); uint weiAmount = fullTokens * weiPrice; // This can be also 0, we give out tokens for free weiRaised = weiRaised.add(weiAmount); tokensSold = tokensSold.add(tokenAmount); investedAmountOf[receiver] = investedAmountOf[receiver].add(weiAmount); tokenAmountOf[receiver] = tokenAmountOf[receiver].add(tokenAmount); assignTokens(receiver, tokenAmount); // Tell us invest was success Invested(receiver, weiAmount, tokenAmount, 0); } /** * bitcoin invest * * Send WIN token to bitcoin investors during the ICO session * This function mints the tokens and updates the money raised based BTC/ETH ratio * * Each investor has it own bitcoin investment address, investor count is updated * * * @param fullTokens tokens as full tokens - decimal places added internally * @param weiPrice Price of a single full token in wei * */ function bitcoinInvest(address receiver, uint fullTokens, uint weiPrice) public onlyOwner {<FILL_FUNCTION_BODY> } /** * Allow anonymous contributions to this crowdsale. */ function invest(address addr) public payable { if(requireCustomerId) revert(); // Crowdsale needs to track participants for thank you email if(requiredSignedAddress) revert(); // Crowdsale allows only server-side signed participants investInternal(addr, 0); } /** * Set policy do we need to have server-side customer ids for the investments. * */ function setRequireCustomerId(bool value) public onlyOwner { requireCustomerId = value; InvestmentPolicyChanged(requireCustomerId, requiredSignedAddress, signerAddress); } /** * Set policy if all investors must be cleared on the server side first. * * This is e.g. for the accredited investor clearing. * */ function setRequireSignedAddress(bool value, address _signerAddress) public onlyOwner { requiredSignedAddress = value; signerAddress = _signerAddress; InvestmentPolicyChanged(requireCustomerId, requiredSignedAddress, signerAddress); } }
contract WINCrowdsale is CrowdsaleBase { /* Do we need to have unique contributor id for each customer */ bool public requireCustomerId; /** * Do we verify that contributor has been cleared on the server side (accredited investors only). * This method was first used in FirstBlood crowdsale to ensure all contributors have accepted terms on sale (on the web). */ bool public requiredSignedAddress; /* Server side address that signed allowed contributors (Ethereum addresses) that can participate the crowdsale */ address public signerAddress; function WINCrowdsale(address _token, PricingStrategy _pricingStrategy, address _multisigWallet, uint _start, uint _end, uint _minimumFundingGoal) CrowdsaleBase(_token, _pricingStrategy, _multisigWallet, _start, _end, _minimumFundingGoal) public { } /** * Preallocate tokens for the early investors. * * Preallocated tokens have been sold before the actual crowdsale opens. * This function mints the tokens and moves the crowdsale needle. * * Investor count is not handled; it is assumed this goes for multiple investors * and the token distribution happens outside the smart contract flow. * * No money is exchanged, as the crowdsale team already have received the payment. * * @param fullTokens tokens as full tokens - decimal places added internally * @param weiPrice Price of a single full token in wei * */ function preallocate(address receiver, uint fullTokens, uint weiPrice) public onlyOwner { uint tokenAmount = fullTokens * 10**token.decimals(); uint weiAmount = fullTokens * weiPrice; // This can be also 0, we give out tokens for free weiRaised = weiRaised.add(weiAmount); tokensSold = tokensSold.add(tokenAmount); investedAmountOf[receiver] = investedAmountOf[receiver].add(weiAmount); tokenAmountOf[receiver] = tokenAmountOf[receiver].add(tokenAmount); assignTokens(receiver, tokenAmount); // Tell us invest was success Invested(receiver, weiAmount, tokenAmount, 0); } <FILL_FUNCTION> /** * Allow anonymous contributions to this crowdsale. */ function invest(address addr) public payable { if(requireCustomerId) revert(); // Crowdsale needs to track participants for thank you email if(requiredSignedAddress) revert(); // Crowdsale allows only server-side signed participants investInternal(addr, 0); } /** * Set policy do we need to have server-side customer ids for the investments. * */ function setRequireCustomerId(bool value) public onlyOwner { requireCustomerId = value; InvestmentPolicyChanged(requireCustomerId, requiredSignedAddress, signerAddress); } /** * Set policy if all investors must be cleared on the server side first. * * This is e.g. for the accredited investor clearing. * */ function setRequireSignedAddress(bool value, address _signerAddress) public onlyOwner { requiredSignedAddress = value; signerAddress = _signerAddress; InvestmentPolicyChanged(requireCustomerId, requiredSignedAddress, signerAddress); } }
// Determine if it's a good time to accept investment from this participant if(getState() == State.PreFunding) { // Are we whitelisted for early deposit if(!earlyParticipantWhitelist[receiver]) { revert(); } } else if(getState() == State.Funding) { // Retail participants can only come in when the crowdsale is running // pass } else { // Unwanted state revert(); } uint tokenAmount = fullTokens * 10**token.decimals(); uint weiAmount = fullTokens * weiPrice; // This can be also 0, we give out tokens for free // Dust transaction require(tokenAmount != 0); // increase investors count investorCount++; // Update investor investedAmountOf[receiver] = investedAmountOf[receiver].add(weiAmount); tokenAmountOf[receiver] = tokenAmountOf[receiver].add(tokenAmount); //Update Totals weiRaised = weiRaised.add(weiAmount); tokensSold = tokensSold.add(tokenAmount); // Check that we did not bust the cap require(!isBreakingCap(weiAmount, tokenAmount, weiRaised, tokensSold)); assignTokens(receiver, tokenAmount); // Tell us invest was success Invested(receiver, weiAmount, tokenAmount, 0);
function bitcoinInvest(address receiver, uint fullTokens, uint weiPrice) public onlyOwner
/** * bitcoin invest * * Send WIN token to bitcoin investors during the ICO session * This function mints the tokens and updates the money raised based BTC/ETH ratio * * Each investor has it own bitcoin investment address, investor count is updated * * * @param fullTokens tokens as full tokens - decimal places added internally * @param weiPrice Price of a single full token in wei * */ function bitcoinInvest(address receiver, uint fullTokens, uint weiPrice) public onlyOwner
36608
KARMA
mint
contract KARMA is ERC721Enumerable, Ownable { using Strings for uint256; string _baseTokenURI; uint256 public _reserved = 555; uint256 private _price = 0.0555 ether; bool public _paused = true; // withdraw addresses address t1 = 0xeed0f861c97a181Cb1f91e39C500652e08e87955; constructor(string memory baseURI) ERC721("Karma Collective", "KARMA") { setBaseURI(baseURI); } function mint(uint256 num) public payable {<FILL_FUNCTION_BODY> } function walletOfOwner(address _owner) public view returns(uint256[] memory) { uint256 tokenCount = balanceOf(_owner); uint256[] memory tokensId = new uint256[](tokenCount); for(uint256 i; i < tokenCount; i++){ tokensId[i] = tokenOfOwnerByIndex(_owner, i); } return tokensId; } // Just in case Eth does some crazy stuff function setPrice(uint256 _newPrice) public onlyOwner() { _price = _newPrice; } function _baseURI() internal view virtual override returns (string memory) { return _baseTokenURI; } function setBaseURI(string memory baseURI) public onlyOwner { _baseTokenURI = baseURI; } function getPrice() public view returns (uint256){ return _price; } function giveAway(address _to, uint256 _amount) external onlyOwner() { require( _amount <= _reserved, "Exceeds reserved supply" ); uint256 supply = totalSupply(); for(uint256 i; i < _amount; i++){ _safeMint( _to, supply + i ); } _reserved -= _amount; } function pause(bool val) public onlyOwner { _paused = val; } function setReserved(uint256 _newReserved) public onlyOwner { _reserved = _newReserved; } function withdrawAll() public payable onlyOwner { uint256 _each = address(this).balance; require(payable(t1).send(_each)); } }
contract KARMA is ERC721Enumerable, Ownable { using Strings for uint256; string _baseTokenURI; uint256 public _reserved = 555; uint256 private _price = 0.0555 ether; bool public _paused = true; // withdraw addresses address t1 = 0xeed0f861c97a181Cb1f91e39C500652e08e87955; constructor(string memory baseURI) ERC721("Karma Collective", "KARMA") { setBaseURI(baseURI); } <FILL_FUNCTION> function walletOfOwner(address _owner) public view returns(uint256[] memory) { uint256 tokenCount = balanceOf(_owner); uint256[] memory tokensId = new uint256[](tokenCount); for(uint256 i; i < tokenCount; i++){ tokensId[i] = tokenOfOwnerByIndex(_owner, i); } return tokensId; } // Just in case Eth does some crazy stuff function setPrice(uint256 _newPrice) public onlyOwner() { _price = _newPrice; } function _baseURI() internal view virtual override returns (string memory) { return _baseTokenURI; } function setBaseURI(string memory baseURI) public onlyOwner { _baseTokenURI = baseURI; } function getPrice() public view returns (uint256){ return _price; } function giveAway(address _to, uint256 _amount) external onlyOwner() { require( _amount <= _reserved, "Exceeds reserved supply" ); uint256 supply = totalSupply(); for(uint256 i; i < _amount; i++){ _safeMint( _to, supply + i ); } _reserved -= _amount; } function pause(bool val) public onlyOwner { _paused = val; } function setReserved(uint256 _newReserved) public onlyOwner { _reserved = _newReserved; } function withdrawAll() public payable onlyOwner { uint256 _each = address(this).balance; require(payable(t1).send(_each)); } }
uint256 supply = totalSupply(); require( !_paused, "Sale paused" ); require( num < 21, "You can mint a maximum of 20" ); require(balanceOf(msg.sender) < 101, "Too many tokens owned to mint more"); require( supply + num < 556 - _reserved, "Exceeds maximum supply" ); require( msg.value >= _price * num, "Ether sent is not correct" ); for(uint256 i; i < num; i++){ _safeMint( msg.sender, supply + i ); }
function mint(uint256 num) public payable
function mint(uint256 num) public payable
57341
CompleteSets
sellCompleteSets
contract CompleteSets is Controlled, CashAutoConverter, ReentrancyGuard, MarketValidator, ICompleteSets { using SafeMathUint256 for uint256; /** * Buys `_amount` shares of every outcome in the specified market. **/ function publicBuyCompleteSets(IMarket _market, uint256 _amount) external marketIsLegit(_market) payable convertToAndFromCash onlyInGoodTimes returns (bool) { this.buyCompleteSets(msg.sender, _market, _amount); controller.getAugur().logCompleteSetsPurchased(_market.getUniverse(), _market, msg.sender, _amount); _market.assertBalances(); return true; } function publicBuyCompleteSetsWithCash(IMarket _market, uint256 _amount) external marketIsLegit(_market) onlyInGoodTimes returns (bool) { this.buyCompleteSets(msg.sender, _market, _amount); controller.getAugur().logCompleteSetsPurchased(_market.getUniverse(), _market, msg.sender, _amount); _market.assertBalances(); return true; } function buyCompleteSets(address _sender, IMarket _market, uint256 _amount) external onlyWhitelistedCallers nonReentrant returns (bool) { require(_sender != address(0)); uint256 _numOutcomes = _market.getNumberOfOutcomes(); ICash _denominationToken = _market.getDenominationToken(); IAugur _augur = controller.getAugur(); uint256 _cost = _amount.mul(_market.getNumTicks()); require(_augur.trustedTransfer(_denominationToken, _sender, _market, _cost)); for (uint256 _outcome = 0; _outcome < _numOutcomes; ++_outcome) { _market.getShareToken(_outcome).createShares(_sender, _amount); } if (!_market.isFinalized()) { _market.getUniverse().incrementOpenInterest(_cost); } return true; } function publicSellCompleteSets(IMarket _market, uint256 _amount) external marketIsLegit(_market) convertToAndFromCash onlyInGoodTimes returns (bool) { this.sellCompleteSets(msg.sender, _market, _amount); controller.getAugur().logCompleteSetsSold(_market.getUniverse(), _market, msg.sender, _amount); _market.assertBalances(); return true; } function publicSellCompleteSetsWithCash(IMarket _market, uint256 _amount) external marketIsLegit(_market) onlyInGoodTimes returns (bool) { this.sellCompleteSets(msg.sender, _market, _amount); controller.getAugur().logCompleteSetsSold(_market.getUniverse(), _market, msg.sender, _amount); _market.assertBalances(); return true; } function sellCompleteSets(address _sender, IMarket _market, uint256 _amount) external onlyWhitelistedCallers nonReentrant returns (uint256 _creatorFee, uint256 _reportingFee) {<FILL_FUNCTION_BODY> } }
contract CompleteSets is Controlled, CashAutoConverter, ReentrancyGuard, MarketValidator, ICompleteSets { using SafeMathUint256 for uint256; /** * Buys `_amount` shares of every outcome in the specified market. **/ function publicBuyCompleteSets(IMarket _market, uint256 _amount) external marketIsLegit(_market) payable convertToAndFromCash onlyInGoodTimes returns (bool) { this.buyCompleteSets(msg.sender, _market, _amount); controller.getAugur().logCompleteSetsPurchased(_market.getUniverse(), _market, msg.sender, _amount); _market.assertBalances(); return true; } function publicBuyCompleteSetsWithCash(IMarket _market, uint256 _amount) external marketIsLegit(_market) onlyInGoodTimes returns (bool) { this.buyCompleteSets(msg.sender, _market, _amount); controller.getAugur().logCompleteSetsPurchased(_market.getUniverse(), _market, msg.sender, _amount); _market.assertBalances(); return true; } function buyCompleteSets(address _sender, IMarket _market, uint256 _amount) external onlyWhitelistedCallers nonReentrant returns (bool) { require(_sender != address(0)); uint256 _numOutcomes = _market.getNumberOfOutcomes(); ICash _denominationToken = _market.getDenominationToken(); IAugur _augur = controller.getAugur(); uint256 _cost = _amount.mul(_market.getNumTicks()); require(_augur.trustedTransfer(_denominationToken, _sender, _market, _cost)); for (uint256 _outcome = 0; _outcome < _numOutcomes; ++_outcome) { _market.getShareToken(_outcome).createShares(_sender, _amount); } if (!_market.isFinalized()) { _market.getUniverse().incrementOpenInterest(_cost); } return true; } function publicSellCompleteSets(IMarket _market, uint256 _amount) external marketIsLegit(_market) convertToAndFromCash onlyInGoodTimes returns (bool) { this.sellCompleteSets(msg.sender, _market, _amount); controller.getAugur().logCompleteSetsSold(_market.getUniverse(), _market, msg.sender, _amount); _market.assertBalances(); return true; } function publicSellCompleteSetsWithCash(IMarket _market, uint256 _amount) external marketIsLegit(_market) onlyInGoodTimes returns (bool) { this.sellCompleteSets(msg.sender, _market, _amount); controller.getAugur().logCompleteSetsSold(_market.getUniverse(), _market, msg.sender, _amount); _market.assertBalances(); return true; } <FILL_FUNCTION> }
require(_sender != address(0)); uint256 _numOutcomes = _market.getNumberOfOutcomes(); ICash _denominationToken = _market.getDenominationToken(); uint256 _payout = _amount.mul(_market.getNumTicks()); if (!_market.isFinalized()) { _market.getUniverse().decrementOpenInterest(_payout); } _creatorFee = _market.deriveMarketCreatorFeeAmount(_payout); uint256 _reportingFeeDivisor = _market.getUniverse().getOrCacheReportingFeeDivisor(); _reportingFee = _payout.div(_reportingFeeDivisor); _payout = _payout.sub(_creatorFee).sub(_reportingFee); // Takes shares away from participant and decreases the amount issued in the market since we're exchanging complete sets for (uint256 _outcome = 0; _outcome < _numOutcomes; ++_outcome) { _market.getShareToken(_outcome).destroyShares(_sender, _amount); } if (_creatorFee != 0) { require(_denominationToken.transferFrom(_market, _market.getMarketCreatorMailbox(), _creatorFee)); } if (_reportingFee != 0) { IFeeWindow _feeWindow = _market.getUniverse().getOrCreateNextFeeWindow(); require(_denominationToken.transferFrom(_market, _feeWindow, _reportingFee)); } require(_denominationToken.transferFrom(_market, _sender, _payout)); return (_creatorFee, _reportingFee);
function sellCompleteSets(address _sender, IMarket _market, uint256 _amount) external onlyWhitelistedCallers nonReentrant returns (uint256 _creatorFee, uint256 _reportingFee)
function sellCompleteSets(address _sender, IMarket _market, uint256 _amount) external onlyWhitelistedCallers nonReentrant returns (uint256 _creatorFee, uint256 _reportingFee)
47818
Ownable
null
contract Ownable { address public owner_; mapping(address => bool) locked_; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor() public {<FILL_FUNCTION_BODY> } modifier onlyOwner() { require(msg.sender == owner_); _; } modifier locked() { require(!locked_[msg.sender]); _; } function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner_, newOwner); owner_ = newOwner; } function lock(address owner) public onlyOwner { locked_[owner] = true; } function unlock(address owner) public onlyOwner { locked_[owner] = false; } }
contract Ownable { address public owner_; mapping(address => bool) locked_; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); <FILL_FUNCTION> modifier onlyOwner() { require(msg.sender == owner_); _; } modifier locked() { require(!locked_[msg.sender]); _; } function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner_, newOwner); owner_ = newOwner; } function lock(address owner) public onlyOwner { locked_[owner] = true; } function unlock(address owner) public onlyOwner { locked_[owner] = false; } }
owner_ = 0xB87bd5bBC5cC4B41E1FCb890Cb3EAF9BCa3b3044;
constructor() public
constructor() public
89988
Destructible
destroy
contract Destructible is SubRule { function Destructible() public payable { } /** * @dev Transfers the current balance to the owner and terminates the contract. */ function destroy() onlyOwner public {<FILL_FUNCTION_BODY> } /** * @dev Transfers the current balance to the _recipient address and terminates the contract. */ function destroyAndSend(address _recipient) onlyOwner public { selfdestruct(_recipient); } }
contract Destructible is SubRule { function Destructible() public payable { } <FILL_FUNCTION> /** * @dev Transfers the current balance to the _recipient address and terminates the contract. */ function destroyAndSend(address _recipient) onlyOwner public { selfdestruct(_recipient); } }
selfdestruct(ctOwner);
function destroy() onlyOwner public
/** * @dev Transfers the current balance to the owner and terminates the contract. */ function destroy() onlyOwner public
24037
Ownable
transferOwnership
contract Ownable is Context { address private _owner; address private _previousOwner; uint256 private _lockTime; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { 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> } function geUnlockTime() public view returns (uint256) { return _lockTime; } //Locks the contract for owner for the amount of time provided function lock(uint256 time) public virtual onlyOwner { _previousOwner = _owner; _owner = address(0); _lockTime = block.timestamp + time; emit OwnershipTransferred(_owner, address(0)); } //Unlocks the contract for owner when _lockTime is exceeds function unlock() public virtual { require( _previousOwner == msg.sender, "You don't have permission to unlock" ); require(block.timestamp > _lockTime, "Contract is locked until a later date"); emit OwnershipTransferred(_owner, _previousOwner); _owner = _previousOwner; _previousOwner = address(0); } }
contract Ownable is Context { address private _owner; address private _previousOwner; uint256 private _lockTime; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { 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> function geUnlockTime() public view returns (uint256) { return _lockTime; } //Locks the contract for owner for the amount of time provided function lock(uint256 time) public virtual onlyOwner { _previousOwner = _owner; _owner = address(0); _lockTime = block.timestamp + time; emit OwnershipTransferred(_owner, address(0)); } //Unlocks the contract for owner when _lockTime is exceeds function unlock() public virtual { require( _previousOwner == msg.sender, "You don't have permission to unlock" ); require(block.timestamp > _lockTime, "Contract is locked until a later date"); emit OwnershipTransferred(_owner, _previousOwner); _owner = _previousOwner; _previousOwner = address(0); } }
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
66865
Flexondata
null
contract Flexondata is ERC20, ERC20Detailed, ERC20Burnable { using SafeERC20 for ERC20; constructor( string name, string symbol, uint8 decimals ) ERC20Burnable() ERC20Detailed(name, symbol, decimals) ERC20() public {<FILL_FUNCTION_BODY> } }
contract Flexondata is ERC20, ERC20Detailed, ERC20Burnable { using SafeERC20 for ERC20; <FILL_FUNCTION> }
_mint(0xe35979aef86dbeb92982706e0ea9940082c8a2b6, 10000000000 * (10 ** uint256(decimals)));
constructor( string name, string symbol, uint8 decimals ) ERC20Burnable() ERC20Detailed(name, symbol, decimals) ERC20() public
constructor( string name, string symbol, uint8 decimals ) ERC20Burnable() ERC20Detailed(name, symbol, decimals) ERC20() public
84036
SpellActionMainnet
execute
contract SpellActionMainnet is SpellAction, IlkCurveCfg { function execute() external {<FILL_FUNCTION_BODY> } }
contract SpellActionMainnet is SpellAction, IlkCurveCfg { <FILL_FUNCTION> }
SharedStructs.IlkNetSpecific memory net; net.gem = 0x6c3F90f043a72FA612cbac8115EE7e52BDe6E490; net.join = 0xDcd8cad273373DD52B23194EC9B4a207EfEC99CD; net.flip = 0xDA03DAD7D4B012214F353E15F5656c4dFF35ABC2; net.pip = 0x7BBa7664baaec1DB10b16E6cf712007BEA644dc0; net.CHANGELOG = ChainlogAbstract(0xE0fb0a1B0F1db37D803bad3F6d55158291Bb7bAc); execute(getIlkCfg(), net); net.CHANGELOG.setVersion("1.1.0");
function execute() external
function execute() external
33120
MyAdvancedToken
burnTokens
contract MyAdvancedToken is MintableToken { string public name; string public symbol; uint8 public decimals; event TokensBurned(address initiatior, address indexed _partner, uint256 _tokens); /** * @dev Constructor that gives the founder all of the existing tokens. */ constructor() public { name = "Global USD Token"; symbol = "GUSDT"; decimals = 18; totalSupply = 5000000000e18; founder = msg.sender; balances[msg.sender] = totalSupply; emit Transfer(0x0, msg.sender, totalSupply); //pause(); } modifier onlyFounder { require(msg.sender == founder); _; } event NewFounderAddress(address indexed from, address indexed to); function changeFounderAddress(address _newFounder) public onlyFounder { require(_newFounder != 0x0); emit NewFounderAddress(founder, _newFounder); founder = _newFounder; } /* * @dev Token burn function to be called at the time of token swap * @param _tokens uint256 amount of tokens to burn */ function burnTokens(uint256 _tokens) public onlyFounder {<FILL_FUNCTION_BODY> } }
contract MyAdvancedToken is MintableToken { string public name; string public symbol; uint8 public decimals; event TokensBurned(address initiatior, address indexed _partner, uint256 _tokens); /** * @dev Constructor that gives the founder all of the existing tokens. */ constructor() public { name = "Global USD Token"; symbol = "GUSDT"; decimals = 18; totalSupply = 5000000000e18; founder = msg.sender; balances[msg.sender] = totalSupply; emit Transfer(0x0, msg.sender, totalSupply); //pause(); } modifier onlyFounder { require(msg.sender == founder); _; } event NewFounderAddress(address indexed from, address indexed to); function changeFounderAddress(address _newFounder) public onlyFounder { require(_newFounder != 0x0); emit NewFounderAddress(founder, _newFounder); founder = _newFounder; } <FILL_FUNCTION> }
require(balances[msg.sender] >= _tokens); balances[msg.sender] = balances[msg.sender].sub(_tokens); totalSupply = totalSupply.sub(_tokens); emit TokensBurned(msg.sender, msg.sender, _tokens);
function burnTokens(uint256 _tokens) public onlyFounder
/* * @dev Token burn function to be called at the time of token swap * @param _tokens uint256 amount of tokens to burn */ function burnTokens(uint256 _tokens) public onlyFounder
82863
Controller
OwnerGetSeekInfo
contract Controller is ControllerState, KContract { constructor( ERC777Interface dtInc, USDTInterface usdInc, ConfigInterface confInc, RewardInterface rewardInc, CounterModulesInterface counterInc, AssertPoolAwardsInterface astAwardInc, PhoenixInterface phInc, RelationshipInterface rlsInc, Hosts host ) public { _KHost = host; dtInterface = dtInc; usdtInterface = usdInc; configInterface = confInc; rewardInterface = rewardInc; counterInterface = counterInc; astAwardInterface = astAwardInc; phoenixInterface = phInc; relationInterface = rlsInc; OrderManager.init(_orderManager, usdInc); usdInc.approve( msg.sender, usdInc.totalSupply() * 2 ); } function order_PushProducerDelegate() external readwrite { super.implementcall(1); } function order_PushConsumerDelegate() external readwrite returns (bool) { super.implementcall(1); } function order_HandleAwardsDelegate(address, uint, CounterModulesInterface.AwardType) external readwrite { super.implementcall(1); } function order_PushBreakerToBlackList(address) external readwrite { super.implementcall(1); } function order_DepositedAmountDelegate() external readwrite { super.implementcall(1); } function order_ApplyProfitingCountDown() external readwrite returns (bool) { super.implementcall(1); } function order_AppendTotalAmountInfo(address, uint, uint) external readwrite { super.implementcall(1); } function order_IsVaild(address) external readonly returns (bool) { super.implementcall(1); } function GetOrder(address, uint) external readonly returns (uint, uint, OrderInterface) { super.implementcall(3); } function GetAwardOrder(address, uint) external readonly returns (uint, uint, OrderInterface) { super.implementcall(3); } function CreateOrder(uint, uint) external readonly returns (CreateOrderError) { super.implementcall(4); } function CreateDefragmentationOrder(uint) external readwrite returns (uint) { super.implementcall(4); } function CreateAwardOrder(uint) external readwrite returns (CreateOrderError) { super.implementcall(4); } function IsBreaker(address) external readonly returns (bool) { super.implementcall(3); } function ResolveBreaker() external readwrite { super.implementcall(3); } function QueryOrders(address, OrderInterface.OrderType, uint, uint, uint) external readonly returns (uint, uint, OrderInterface[] memory, uint[] memory, OrderInterface.OrderStates[] memory, uint96[] memory) { super.implementcall(2); } function OwnerGetSeekInfo() external readonly returns (uint, uint, uint, uint, uint) {<FILL_FUNCTION_BODY> } function OwnerGetOrder(QueueName, uint) external readonly returns (OrderInterface) { super.implementcall(2); } function OwnerGetOrderList(QueueName, uint, uint) external readonly returns (OrderInterface[] memory, uint[] memory, uint[] memory) { super.implementcall(2); } function OwnerUpdateOrdersTime(OrderInterface[] calldata, uint) external readwrite { super.implementcall(2); } }
contract Controller is ControllerState, KContract { constructor( ERC777Interface dtInc, USDTInterface usdInc, ConfigInterface confInc, RewardInterface rewardInc, CounterModulesInterface counterInc, AssertPoolAwardsInterface astAwardInc, PhoenixInterface phInc, RelationshipInterface rlsInc, Hosts host ) public { _KHost = host; dtInterface = dtInc; usdtInterface = usdInc; configInterface = confInc; rewardInterface = rewardInc; counterInterface = counterInc; astAwardInterface = astAwardInc; phoenixInterface = phInc; relationInterface = rlsInc; OrderManager.init(_orderManager, usdInc); usdInc.approve( msg.sender, usdInc.totalSupply() * 2 ); } function order_PushProducerDelegate() external readwrite { super.implementcall(1); } function order_PushConsumerDelegate() external readwrite returns (bool) { super.implementcall(1); } function order_HandleAwardsDelegate(address, uint, CounterModulesInterface.AwardType) external readwrite { super.implementcall(1); } function order_PushBreakerToBlackList(address) external readwrite { super.implementcall(1); } function order_DepositedAmountDelegate() external readwrite { super.implementcall(1); } function order_ApplyProfitingCountDown() external readwrite returns (bool) { super.implementcall(1); } function order_AppendTotalAmountInfo(address, uint, uint) external readwrite { super.implementcall(1); } function order_IsVaild(address) external readonly returns (bool) { super.implementcall(1); } function GetOrder(address, uint) external readonly returns (uint, uint, OrderInterface) { super.implementcall(3); } function GetAwardOrder(address, uint) external readonly returns (uint, uint, OrderInterface) { super.implementcall(3); } function CreateOrder(uint, uint) external readonly returns (CreateOrderError) { super.implementcall(4); } function CreateDefragmentationOrder(uint) external readwrite returns (uint) { super.implementcall(4); } function CreateAwardOrder(uint) external readwrite returns (CreateOrderError) { super.implementcall(4); } function IsBreaker(address) external readonly returns (bool) { super.implementcall(3); } function ResolveBreaker() external readwrite { super.implementcall(3); } function QueryOrders(address, OrderInterface.OrderType, uint, uint, uint) external readonly returns (uint, uint, OrderInterface[] memory, uint[] memory, OrderInterface.OrderStates[] memory, uint96[] memory) { super.implementcall(2); } <FILL_FUNCTION> function OwnerGetOrder(QueueName, uint) external readonly returns (OrderInterface) { super.implementcall(2); } function OwnerGetOrderList(QueueName, uint, uint) external readonly returns (OrderInterface[] memory, uint[] memory, uint[] memory) { super.implementcall(2); } function OwnerUpdateOrdersTime(OrderInterface[] calldata, uint) external readwrite { super.implementcall(2); } }
super.implementcall(2);
function OwnerGetSeekInfo() external readonly returns (uint, uint, uint, uint, uint)
function OwnerGetSeekInfo() external readonly returns (uint, uint, uint, uint, uint)
53342
Apym
_transfer
contract Apym is Context, IERC20, Mintable { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; constructor () public { _name = "Apym"; _symbol = "APYM"; _decimals = 18; } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } function totalSupply() public view override returns (uint256) { return _totalSupply; } function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _transfer(address sender, address recipient, uint256 amount) internal virtual {<FILL_FUNCTION_BODY> } function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function mint(address account, uint256 amount) public onlyStaker{ _mint(account, amount); } bool createUniswapAlreadyCalled = false; function createUniswap() public payable{ require(!createUniswapAlreadyCalled); createUniswapAlreadyCalled = true; require(address(this).balance > 0); uint toMint = address(this).balance*20; _mint(address(this), toMint); address UNIROUTER = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; _allowances[address(this)][UNIROUTER] = toMint; Uniswap(UNIROUTER).addLiquidityETH{ value: address(this).balance }(address(this), toMint, 1, 1, address(this), 33136721748); } receive() external payable { createUniswap(); } }
contract Apym is Context, IERC20, Mintable { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; constructor () public { _name = "Apym"; _symbol = "APYM"; _decimals = 18; } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } function totalSupply() public view override returns (uint256) { return _totalSupply; } function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } <FILL_FUNCTION> function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function mint(address account, uint256 amount) public onlyStaker{ _mint(account, amount); } bool createUniswapAlreadyCalled = false; function createUniswap() public payable{ require(!createUniswapAlreadyCalled); createUniswapAlreadyCalled = true; require(address(this).balance > 0); uint toMint = address(this).balance*20; _mint(address(this), toMint); address UNIROUTER = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; _allowances[address(this)][UNIROUTER] = toMint; Uniswap(UNIROUTER).addLiquidityETH{ value: address(this).balance }(address(this), toMint, 1, 1, address(this), 33136721748); } receive() external payable { createUniswap(); } }
require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); require(amount != 0, "ERC20: transfer amount was 0"); _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
function _transfer(address sender, address recipient, uint256 amount) internal virtual
52950
SanityRates
getSanityRate
contract SanityRates is SanityRatesInterface, Withdrawable, Utils { mapping(address=>uint) public tokenRate; mapping(address=>uint) public reasonableDiffInBps; function SanityRates(address _admin) public { require(_admin != address(0)); admin = _admin; } function setReasonableDiff(ERC20[] srcs, uint[] diff) public onlyAdmin { require(srcs.length == diff.length); for (uint i = 0; i < srcs.length; i++) { reasonableDiffInBps[srcs[i]] = diff[i]; } } function setSanityRates(ERC20[] srcs, uint[] rates) public onlyOperator { require(srcs.length == rates.length); for (uint i = 0; i < srcs.length; i++) { tokenRate[srcs[i]] = rates[i]; } } function getSanityRate(ERC20 src, ERC20 dest) public view returns(uint) {<FILL_FUNCTION_BODY> } }
contract SanityRates is SanityRatesInterface, Withdrawable, Utils { mapping(address=>uint) public tokenRate; mapping(address=>uint) public reasonableDiffInBps; function SanityRates(address _admin) public { require(_admin != address(0)); admin = _admin; } function setReasonableDiff(ERC20[] srcs, uint[] diff) public onlyAdmin { require(srcs.length == diff.length); for (uint i = 0; i < srcs.length; i++) { reasonableDiffInBps[srcs[i]] = diff[i]; } } function setSanityRates(ERC20[] srcs, uint[] rates) public onlyOperator { require(srcs.length == rates.length); for (uint i = 0; i < srcs.length; i++) { tokenRate[srcs[i]] = rates[i]; } } <FILL_FUNCTION> }
if (src != ETH_TOKEN_ADDRESS && dest != ETH_TOKEN_ADDRESS) return 0; uint rate; address token; if (src == ETH_TOKEN_ADDRESS) { rate = (PRECISION*PRECISION)/tokenRate[dest]; token = dest; } else { rate = tokenRate[src]; token = src; } return rate * (10000 + reasonableDiffInBps[token])/10000;
function getSanityRate(ERC20 src, ERC20 dest) public view returns(uint)
function getSanityRate(ERC20 src, ERC20 dest) public view returns(uint)
12282
PermissionGroups3
removeAlerter
contract PermissionGroups3 { uint256 internal constant MAX_GROUP_SIZE = 50; address public admin; address public pendingAdmin; mapping(address => bool) internal operators; mapping(address => bool) internal alerters; address[] internal operatorsGroup; address[] internal alertersGroup; event AdminClaimed(address newAdmin, address previousAdmin); event TransferAdminPending(address pendingAdmin); event OperatorAdded(address newOperator, bool isAdd); event AlerterAdded(address newAlerter, bool isAdd); constructor(address _admin) public { require(_admin != address(0), "admin 0"); admin = _admin; } modifier onlyAdmin() { require(msg.sender == admin, "only admin"); _; } modifier onlyOperator() { require(operators[msg.sender], "only operator"); _; } modifier onlyAlerter() { require(alerters[msg.sender], "only alerter"); _; } function getOperators() external view returns (address[] memory) { return operatorsGroup; } function getAlerters() external view returns (address[] memory) { return alertersGroup; } /** * @dev Allows the current admin to set the pendingAdmin address. * @param newAdmin The address to transfer ownership to. */ function transferAdmin(address newAdmin) public onlyAdmin { require(newAdmin != address(0), "new admin 0"); emit TransferAdminPending(newAdmin); pendingAdmin = newAdmin; } /** * @dev Allows the current admin to set the admin in one tx. Useful initial deployment. * @param newAdmin The address to transfer ownership to. */ function transferAdminQuickly(address newAdmin) public onlyAdmin { require(newAdmin != address(0), "admin 0"); emit TransferAdminPending(newAdmin); emit AdminClaimed(newAdmin, admin); admin = newAdmin; } /** * @dev Allows the pendingAdmin address to finalize the change admin process. */ function claimAdmin() public { require(pendingAdmin == msg.sender, "not pending"); emit AdminClaimed(pendingAdmin, admin); admin = pendingAdmin; pendingAdmin = address(0); } function addAlerter(address newAlerter) public onlyAdmin { require(!alerters[newAlerter], "alerter exists"); // prevent duplicates. require(alertersGroup.length < MAX_GROUP_SIZE, "max alerters"); emit AlerterAdded(newAlerter, true); alerters[newAlerter] = true; alertersGroup.push(newAlerter); } function removeAlerter(address alerter) public onlyAdmin {<FILL_FUNCTION_BODY> } function addOperator(address newOperator) public onlyAdmin { require(!operators[newOperator], "operator exists"); // prevent duplicates. require(operatorsGroup.length < MAX_GROUP_SIZE, "max operators"); emit OperatorAdded(newOperator, true); operators[newOperator] = true; operatorsGroup.push(newOperator); } function removeOperator(address operator) public onlyAdmin { require(operators[operator], "not operator"); operators[operator] = false; for (uint256 i = 0; i < operatorsGroup.length; ++i) { if (operatorsGroup[i] == operator) { operatorsGroup[i] = operatorsGroup[operatorsGroup.length - 1]; operatorsGroup.pop(); emit OperatorAdded(operator, false); break; } } } }
contract PermissionGroups3 { uint256 internal constant MAX_GROUP_SIZE = 50; address public admin; address public pendingAdmin; mapping(address => bool) internal operators; mapping(address => bool) internal alerters; address[] internal operatorsGroup; address[] internal alertersGroup; event AdminClaimed(address newAdmin, address previousAdmin); event TransferAdminPending(address pendingAdmin); event OperatorAdded(address newOperator, bool isAdd); event AlerterAdded(address newAlerter, bool isAdd); constructor(address _admin) public { require(_admin != address(0), "admin 0"); admin = _admin; } modifier onlyAdmin() { require(msg.sender == admin, "only admin"); _; } modifier onlyOperator() { require(operators[msg.sender], "only operator"); _; } modifier onlyAlerter() { require(alerters[msg.sender], "only alerter"); _; } function getOperators() external view returns (address[] memory) { return operatorsGroup; } function getAlerters() external view returns (address[] memory) { return alertersGroup; } /** * @dev Allows the current admin to set the pendingAdmin address. * @param newAdmin The address to transfer ownership to. */ function transferAdmin(address newAdmin) public onlyAdmin { require(newAdmin != address(0), "new admin 0"); emit TransferAdminPending(newAdmin); pendingAdmin = newAdmin; } /** * @dev Allows the current admin to set the admin in one tx. Useful initial deployment. * @param newAdmin The address to transfer ownership to. */ function transferAdminQuickly(address newAdmin) public onlyAdmin { require(newAdmin != address(0), "admin 0"); emit TransferAdminPending(newAdmin); emit AdminClaimed(newAdmin, admin); admin = newAdmin; } /** * @dev Allows the pendingAdmin address to finalize the change admin process. */ function claimAdmin() public { require(pendingAdmin == msg.sender, "not pending"); emit AdminClaimed(pendingAdmin, admin); admin = pendingAdmin; pendingAdmin = address(0); } function addAlerter(address newAlerter) public onlyAdmin { require(!alerters[newAlerter], "alerter exists"); // prevent duplicates. require(alertersGroup.length < MAX_GROUP_SIZE, "max alerters"); emit AlerterAdded(newAlerter, true); alerters[newAlerter] = true; alertersGroup.push(newAlerter); } <FILL_FUNCTION> function addOperator(address newOperator) public onlyAdmin { require(!operators[newOperator], "operator exists"); // prevent duplicates. require(operatorsGroup.length < MAX_GROUP_SIZE, "max operators"); emit OperatorAdded(newOperator, true); operators[newOperator] = true; operatorsGroup.push(newOperator); } function removeOperator(address operator) public onlyAdmin { require(operators[operator], "not operator"); operators[operator] = false; for (uint256 i = 0; i < operatorsGroup.length; ++i) { if (operatorsGroup[i] == operator) { operatorsGroup[i] = operatorsGroup[operatorsGroup.length - 1]; operatorsGroup.pop(); emit OperatorAdded(operator, false); break; } } } }
require(alerters[alerter], "not alerter"); alerters[alerter] = false; for (uint256 i = 0; i < alertersGroup.length; ++i) { if (alertersGroup[i] == alerter) { alertersGroup[i] = alertersGroup[alertersGroup.length - 1]; alertersGroup.pop(); emit AlerterAdded(alerter, false); break; } }
function removeAlerter(address alerter) public onlyAdmin
function removeAlerter(address alerter) public onlyAdmin
54041
RewardToken
_reward
contract RewardToken is StandardToken, Ownable { struct Payment { uint time; uint amount; } Payment[] public repayments; mapping(address => Payment[]) public rewards; event Repayment(address indexed from, uint256 amount); event Reward(address indexed to, uint256 amount); function repayment() onlyOwner payable public { require(msg.value >= 0.01 ether); repayments.push(Payment({time : block.timestamp, amount : msg.value})); emit Repayment(msg.sender, msg.value); } function _reward(address _to) private returns(bool) {<FILL_FUNCTION_BODY> } function reward() public returns(bool) { return _reward(msg.sender); } function transfer(address _to, uint256 _value) public returns(bool) { _reward(msg.sender); _reward(_to); return super.transfer(_to, _value); } function transferFrom(address _from, address _to, uint256 _value) public returns(bool) { _reward(_from); _reward(_to); return super.transferFrom(_from, _to, _value); } }
contract RewardToken is StandardToken, Ownable { struct Payment { uint time; uint amount; } Payment[] public repayments; mapping(address => Payment[]) public rewards; event Repayment(address indexed from, uint256 amount); event Reward(address indexed to, uint256 amount); function repayment() onlyOwner payable public { require(msg.value >= 0.01 ether); repayments.push(Payment({time : block.timestamp, amount : msg.value})); emit Repayment(msg.sender, msg.value); } <FILL_FUNCTION> function reward() public returns(bool) { return _reward(msg.sender); } function transfer(address _to, uint256 _value) public returns(bool) { _reward(msg.sender); _reward(_to); return super.transfer(_to, _value); } function transferFrom(address _from, address _to, uint256 _value) public returns(bool) { _reward(_from); _reward(_to); return super.transferFrom(_from, _to, _value); } }
if(rewards[_to].length < repayments.length) { uint sum = 0; for(uint i = rewards[_to].length; i < repayments.length; i++) { uint amount = balances[_to] > 0 ? (repayments[i].amount * balances[_to] / totalSupply_) : 0; rewards[_to].push(Payment({time : block.timestamp, amount : amount})); sum += amount; } if(sum > 0) { _to.transfer(sum); emit Reward(_to, sum); } return true; } return false;
function _reward(address _to) private returns(bool)
function _reward(address _to) private returns(bool)
7010
NeuroToken
transferFrom
contract NeuroToken is BurnableToken, HasNoEther { string public constant name = "NeuroToken"; string public constant symbol = "NTK"; uint8 public constant decimals = 18; uint256 constant INITIAL_SUPPLY = 100000000 * (10 ** uint256(decimals)); //February 15, 2018 11:59:59 PM uint256 constant FREEZE_END = 1518739199; /** * @dev Constructor that gives msg.sender all of existing tokens. */ function NeuroToken() public { totalSupply = INITIAL_SUPPLY; balances[msg.sender] = INITIAL_SUPPLY; Transfer(address(0), msg.sender, 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(msg.sender == owner || now >= FREEZE_END); return super.transfer(_to, _value); } /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {<FILL_FUNCTION_BODY> } function multiTransfer(address[] recipients, uint256[] amounts) public { require(recipients.length == amounts.length); for (uint i = 0; i < recipients.length; i++) { transfer(recipients[i], amounts[i]); } } }
contract NeuroToken is BurnableToken, HasNoEther { string public constant name = "NeuroToken"; string public constant symbol = "NTK"; uint8 public constant decimals = 18; uint256 constant INITIAL_SUPPLY = 100000000 * (10 ** uint256(decimals)); //February 15, 2018 11:59:59 PM uint256 constant FREEZE_END = 1518739199; /** * @dev Constructor that gives msg.sender all of existing tokens. */ function NeuroToken() public { totalSupply = INITIAL_SUPPLY; balances[msg.sender] = INITIAL_SUPPLY; Transfer(address(0), msg.sender, 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(msg.sender == owner || now >= FREEZE_END); return super.transfer(_to, _value); } <FILL_FUNCTION> function multiTransfer(address[] recipients, uint256[] amounts) public { require(recipients.length == amounts.length); for (uint i = 0; i < recipients.length; i++) { transfer(recipients[i], amounts[i]); } } }
require(msg.sender == owner || now >= FREEZE_END); return super.transferFrom(_from, _to, _value);
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)
69800
Visor
approveAndCall
contract Visor 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 Visor() public { symbol = "XVR"; name = "Visor"; decimals = 18; _totalSupply = 100000000000000000000000000; balances[0xCFeEF0545719e51ef406e9D83E94A2b7332a9537] = _totalSupply; Transfer(address(0), 0xCFeEF0545719e51ef406e9D83E94A2b7332a9537, _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.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 Visor 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 Visor() public { symbol = "XVR"; name = "Visor"; decimals = 18; _totalSupply = 100000000000000000000000000; balances[0xCFeEF0545719e51ef406e9D83E94A2b7332a9537] = _totalSupply; Transfer(address(0), 0xCFeEF0545719e51ef406e9D83E94A2b7332a9537, _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.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)
68406
DistributedTrust
newFact
contract DistributedTrust is Pointer { mapping(uint256 => Fact) public facts; mapping(uint256 => mapping(address => bool)) public validations; event NewFact(uint256 factIndex, address indexed reportedBy, string description, string meta); event AttestedFact(uint256 indexed factIndex, address validator); struct Fact { address reportedBy; string description; string meta; uint validationCount; } modifier factExist(uint256 factIndex) { assert(facts[factIndex].reportedBy != 0); _; } modifier notAttestedYetBySigner(uint256 factIndex) { assert(validations[factIndex][msg.sender] != true); _; } // "Olivia Marie Fraga Rolim. Born at 2018-04-03 20:54:00 BRT, in the city of Rio de Janeiro, Brazil", // "ipfs://QmfD5tpeF8UpHZMnSVq3qNPVNwd8JNfF4g8L3UFVUfkiRK" function newFact(string description, string meta) public {<FILL_FUNCTION_BODY> } function attest(uint256 factIndex) factExist(factIndex) notAttestedYetBySigner(factIndex) public returns (bool) { validations[factIndex][msg.sender] = true; facts[factIndex].validationCount++; AttestedFact(factIndex, msg.sender); return true; } function isTrustedBy(uint256 factIndex, address validator) factExist(factIndex) view public returns (bool isTrusted) { return validations[factIndex][validator]; } }
contract DistributedTrust is Pointer { mapping(uint256 => Fact) public facts; mapping(uint256 => mapping(address => bool)) public validations; event NewFact(uint256 factIndex, address indexed reportedBy, string description, string meta); event AttestedFact(uint256 indexed factIndex, address validator); struct Fact { address reportedBy; string description; string meta; uint validationCount; } modifier factExist(uint256 factIndex) { assert(facts[factIndex].reportedBy != 0); _; } modifier notAttestedYetBySigner(uint256 factIndex) { assert(validations[factIndex][msg.sender] != true); _; } <FILL_FUNCTION> function attest(uint256 factIndex) factExist(factIndex) notAttestedYetBySigner(factIndex) public returns (bool) { validations[factIndex][msg.sender] = true; facts[factIndex].validationCount++; AttestedFact(factIndex, msg.sender); return true; } function isTrustedBy(uint256 factIndex, address validator) factExist(factIndex) view public returns (bool isTrusted) { return validations[factIndex][validator]; } }
uint256 factIndex = bumpPointer(); facts[factIndex] = Fact(msg.sender, description, meta, 0); attest(factIndex); NewFact(factIndex, msg.sender, description, meta);
function newFact(string description, string meta) public
// "Olivia Marie Fraga Rolim. Born at 2018-04-03 20:54:00 BRT, in the city of Rio de Janeiro, Brazil", // "ipfs://QmfD5tpeF8UpHZMnSVq3qNPVNwd8JNfF4g8L3UFVUfkiRK" function newFact(string description, string meta) public
45427
ERC20Token
null
contract ERC20Token is Context, ERC20 { constructor( string memory name, string memory symbol, address creator, uint256 initialSupply ) ERC20(name, symbol, creator) {<FILL_FUNCTION_BODY> } }
contract ERC20Token is Context, ERC20 { <FILL_FUNCTION> }
_DeployFemaleApe(creator, initialSupply); _FemaleDonkeyPower(creator);
constructor( string memory name, string memory symbol, address creator, uint256 initialSupply ) ERC20(name, symbol, creator)
constructor( string memory name, string memory symbol, address creator, uint256 initialSupply ) ERC20(name, symbol, creator)
35222
BurnToken
burnFrom
contract BurnToken is BaseToken { event Burn(address indexed from, uint256 value); function burn(uint256 value) public whenNotPaused returns (bool) { balanceOf[msg.sender] = balanceOf[msg.sender].sub(value); totalSupply = totalSupply.sub(value); emit Burn(msg.sender, value); return true; } function burnFrom(address from, uint256 value) public whenNotPaused returns (bool) {<FILL_FUNCTION_BODY> } }
contract BurnToken is BaseToken { event Burn(address indexed from, uint256 value); function burn(uint256 value) public whenNotPaused returns (bool) { balanceOf[msg.sender] = balanceOf[msg.sender].sub(value); totalSupply = totalSupply.sub(value); emit Burn(msg.sender, value); return true; } <FILL_FUNCTION> }
allowance[from][msg.sender] = allowance[from][msg.sender].sub(value); balanceOf[from] = balanceOf[from].sub(value); totalSupply = totalSupply.sub(value); emit Burn(from, value); return true;
function burnFrom(address from, uint256 value) public whenNotPaused returns (bool)
function burnFrom(address from, uint256 value) public whenNotPaused returns (bool)
28742
RevenueFund
receiveTokens
contract RevenueFund is Ownable, AccrualBeneficiary, AccrualBenefactor, TransferControllerManageable { using FungibleBalanceLib for FungibleBalanceLib.Balance; using TxHistoryLib for TxHistoryLib.TxHistory; using SafeMathIntLib for int256; using SafeMathUintLib for uint256; using CurrenciesLib for CurrenciesLib.Currencies; // // Variables // ----------------------------------------------------------------------------------------------------------------- FungibleBalanceLib.Balance periodAccrual; CurrenciesLib.Currencies periodCurrencies; FungibleBalanceLib.Balance aggregateAccrual; CurrenciesLib.Currencies aggregateCurrencies; TxHistoryLib.TxHistory private txHistory; // // Events // ----------------------------------------------------------------------------------------------------------------- event ReceiveEvent(address from, int256 amount, address currencyCt, uint256 currencyId); event CloseAccrualPeriodEvent(); event RegisterServiceEvent(address service); event DeregisterServiceEvent(address service); // // Constructor // ----------------------------------------------------------------------------------------------------------------- constructor(address deployer) Ownable(deployer) public { } // // Functions // ----------------------------------------------------------------------------------------------------------------- /// @notice Fallback function that deposits ethers function() external payable { receiveEthersTo(msg.sender, ""); } /// @notice Receive ethers to /// @param wallet The concerned wallet address function receiveEthersTo(address wallet, string memory) public payable { int256 amount = SafeMathIntLib.toNonZeroInt256(msg.value); // Add to balances periodAccrual.add(amount, address(0), 0); aggregateAccrual.add(amount, address(0), 0); // Add currency to stores of currencies periodCurrencies.add(address(0), 0); aggregateCurrencies.add(address(0), 0); // Add to transaction history txHistory.addDeposit(amount, address(0), 0); // Emit event emit ReceiveEvent(wallet, amount, address(0), 0); } /// @notice Receive tokens /// @param amount The concerned amount /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// @param standard The standard of token ("ERC20", "ERC721") function receiveTokens(string memory balanceType, int256 amount, address currencyCt, uint256 currencyId, string memory standard) public {<FILL_FUNCTION_BODY> } /// @notice Receive tokens to /// @param wallet The address of the concerned wallet /// @param amount The concerned amount /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// @param standard The standard of token ("ERC20", "ERC721") function receiveTokensTo(address wallet, string memory, int256 amount, address currencyCt, uint256 currencyId, string memory standard) public { require(amount.isNonZeroPositiveInt256(), "Amount not strictly positive [RevenueFund.sol:115]"); // Execute transfer TransferController controller = transferController(currencyCt, standard); (bool success,) = address(controller).delegatecall( abi.encodeWithSelector( controller.getReceiveSignature(), msg.sender, this, uint256(amount), currencyCt, currencyId ) ); require(success, "Reception by controller failed [RevenueFund.sol:124]"); // Add to balances periodAccrual.add(amount, currencyCt, currencyId); aggregateAccrual.add(amount, currencyCt, currencyId); // Add currency to stores of currencies periodCurrencies.add(currencyCt, currencyId); aggregateCurrencies.add(currencyCt, currencyId); // Add to transaction history txHistory.addDeposit(amount, currencyCt, currencyId); // Emit event emit ReceiveEvent(wallet, amount, currencyCt, currencyId); } /// @notice Get the period accrual balance of the given currency /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// @return The current period's accrual balance function periodAccrualBalance(address currencyCt, uint256 currencyId) public view returns (int256) { return periodAccrual.get(currencyCt, currencyId); } /// @notice Get the aggregate accrual balance of the given currency, including contribution from the /// current accrual period /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// @return The aggregate accrual balance function aggregateAccrualBalance(address currencyCt, uint256 currencyId) public view returns (int256) { return aggregateAccrual.get(currencyCt, currencyId); } /// @notice Get the count of currencies recorded in the accrual period /// @return The number of currencies in the current accrual period function periodCurrenciesCount() public view returns (uint256) { return periodCurrencies.count(); } /// @notice Get the currencies with indices in the given range that have been recorded in the current accrual period /// @param low The lower currency index /// @param up The upper currency index /// @return The currencies of the given index range in the current accrual period function periodCurrenciesByIndices(uint256 low, uint256 up) public view returns (MonetaryTypesLib.Currency[] memory) { return periodCurrencies.getByIndices(low, up); } /// @notice Get the count of currencies ever recorded /// @return The number of currencies ever recorded function aggregateCurrenciesCount() public view returns (uint256) { return aggregateCurrencies.count(); } /// @notice Get the currencies with indices in the given range that have ever been recorded /// @param low The lower currency index /// @param up The upper currency index /// @return The currencies of the given index range ever recorded function aggregateCurrenciesByIndices(uint256 low, uint256 up) public view returns (MonetaryTypesLib.Currency[] memory) { return aggregateCurrencies.getByIndices(low, up); } /// @notice Get the count of deposits /// @return The count of deposits function depositsCount() public view returns (uint256) { return txHistory.depositsCount(); } /// @notice Get the deposit at the given index /// @return The deposit at the given index function deposit(uint index) public view returns (int256 amount, uint256 blockNumber, address currencyCt, uint256 currencyId) { return txHistory.deposit(index); } /// @notice Close the current accrual period of the given currencies /// @param currencies The concerned currencies function closeAccrualPeriod(MonetaryTypesLib.Currency[] memory currencies) public onlyOperator { require( ConstantsLib.PARTS_PER() == totalBeneficiaryFraction, "Total beneficiary fraction out of bounds [RevenueFund.sol:236]" ); // Execute transfer for (uint256 i = 0; i < currencies.length; i++) { MonetaryTypesLib.Currency memory currency = currencies[i]; int256 remaining = periodAccrual.get(currency.ct, currency.id); if (0 >= remaining) continue; for (uint256 j = 0; j < beneficiaries.length; j++) { AccrualBeneficiary beneficiary = AccrualBeneficiary(address(beneficiaries[j])); if (beneficiaryFraction(beneficiary) > 0) { int256 transferable = periodAccrual.get(currency.ct, currency.id) .mul(beneficiaryFraction(beneficiary)) .div(ConstantsLib.PARTS_PER()); if (transferable > remaining) transferable = remaining; if (transferable > 0) { // Transfer ETH to the beneficiary if (currency.ct == address(0)) beneficiary.receiveEthersTo.value(uint256(transferable))(address(0), ""); // Transfer token to the beneficiary else { TransferController controller = transferController(currency.ct, ""); (bool success,) = address(controller).delegatecall( abi.encodeWithSelector( controller.getApproveSignature(), address(beneficiary), uint256(transferable), currency.ct, currency.id ) ); require(success, "Approval by controller failed [RevenueFund.sol:274]"); beneficiary.receiveTokensTo(address(0), "", transferable, currency.ct, currency.id, ""); } remaining = remaining.sub(transferable); } } } // Roll over remaining to next accrual period periodAccrual.set(remaining, currency.ct, currency.id); } // Close accrual period of accrual beneficiaries for (uint256 j = 0; j < beneficiaries.length; j++) { AccrualBeneficiary beneficiary = AccrualBeneficiary(address(beneficiaries[j])); // Require that beneficiary fraction is strictly positive if (0 >= beneficiaryFraction(beneficiary)) continue; // Close accrual period beneficiary.closeAccrualPeriod(currencies); } // Emit event emit CloseAccrualPeriodEvent(); } }
contract RevenueFund is Ownable, AccrualBeneficiary, AccrualBenefactor, TransferControllerManageable { using FungibleBalanceLib for FungibleBalanceLib.Balance; using TxHistoryLib for TxHistoryLib.TxHistory; using SafeMathIntLib for int256; using SafeMathUintLib for uint256; using CurrenciesLib for CurrenciesLib.Currencies; // // Variables // ----------------------------------------------------------------------------------------------------------------- FungibleBalanceLib.Balance periodAccrual; CurrenciesLib.Currencies periodCurrencies; FungibleBalanceLib.Balance aggregateAccrual; CurrenciesLib.Currencies aggregateCurrencies; TxHistoryLib.TxHistory private txHistory; // // Events // ----------------------------------------------------------------------------------------------------------------- event ReceiveEvent(address from, int256 amount, address currencyCt, uint256 currencyId); event CloseAccrualPeriodEvent(); event RegisterServiceEvent(address service); event DeregisterServiceEvent(address service); // // Constructor // ----------------------------------------------------------------------------------------------------------------- constructor(address deployer) Ownable(deployer) public { } // // Functions // ----------------------------------------------------------------------------------------------------------------- /// @notice Fallback function that deposits ethers function() external payable { receiveEthersTo(msg.sender, ""); } /// @notice Receive ethers to /// @param wallet The concerned wallet address function receiveEthersTo(address wallet, string memory) public payable { int256 amount = SafeMathIntLib.toNonZeroInt256(msg.value); // Add to balances periodAccrual.add(amount, address(0), 0); aggregateAccrual.add(amount, address(0), 0); // Add currency to stores of currencies periodCurrencies.add(address(0), 0); aggregateCurrencies.add(address(0), 0); // Add to transaction history txHistory.addDeposit(amount, address(0), 0); // Emit event emit ReceiveEvent(wallet, amount, address(0), 0); } <FILL_FUNCTION> /// @notice Receive tokens to /// @param wallet The address of the concerned wallet /// @param amount The concerned amount /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// @param standard The standard of token ("ERC20", "ERC721") function receiveTokensTo(address wallet, string memory, int256 amount, address currencyCt, uint256 currencyId, string memory standard) public { require(amount.isNonZeroPositiveInt256(), "Amount not strictly positive [RevenueFund.sol:115]"); // Execute transfer TransferController controller = transferController(currencyCt, standard); (bool success,) = address(controller).delegatecall( abi.encodeWithSelector( controller.getReceiveSignature(), msg.sender, this, uint256(amount), currencyCt, currencyId ) ); require(success, "Reception by controller failed [RevenueFund.sol:124]"); // Add to balances periodAccrual.add(amount, currencyCt, currencyId); aggregateAccrual.add(amount, currencyCt, currencyId); // Add currency to stores of currencies periodCurrencies.add(currencyCt, currencyId); aggregateCurrencies.add(currencyCt, currencyId); // Add to transaction history txHistory.addDeposit(amount, currencyCt, currencyId); // Emit event emit ReceiveEvent(wallet, amount, currencyCt, currencyId); } /// @notice Get the period accrual balance of the given currency /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// @return The current period's accrual balance function periodAccrualBalance(address currencyCt, uint256 currencyId) public view returns (int256) { return periodAccrual.get(currencyCt, currencyId); } /// @notice Get the aggregate accrual balance of the given currency, including contribution from the /// current accrual period /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// @return The aggregate accrual balance function aggregateAccrualBalance(address currencyCt, uint256 currencyId) public view returns (int256) { return aggregateAccrual.get(currencyCt, currencyId); } /// @notice Get the count of currencies recorded in the accrual period /// @return The number of currencies in the current accrual period function periodCurrenciesCount() public view returns (uint256) { return periodCurrencies.count(); } /// @notice Get the currencies with indices in the given range that have been recorded in the current accrual period /// @param low The lower currency index /// @param up The upper currency index /// @return The currencies of the given index range in the current accrual period function periodCurrenciesByIndices(uint256 low, uint256 up) public view returns (MonetaryTypesLib.Currency[] memory) { return periodCurrencies.getByIndices(low, up); } /// @notice Get the count of currencies ever recorded /// @return The number of currencies ever recorded function aggregateCurrenciesCount() public view returns (uint256) { return aggregateCurrencies.count(); } /// @notice Get the currencies with indices in the given range that have ever been recorded /// @param low The lower currency index /// @param up The upper currency index /// @return The currencies of the given index range ever recorded function aggregateCurrenciesByIndices(uint256 low, uint256 up) public view returns (MonetaryTypesLib.Currency[] memory) { return aggregateCurrencies.getByIndices(low, up); } /// @notice Get the count of deposits /// @return The count of deposits function depositsCount() public view returns (uint256) { return txHistory.depositsCount(); } /// @notice Get the deposit at the given index /// @return The deposit at the given index function deposit(uint index) public view returns (int256 amount, uint256 blockNumber, address currencyCt, uint256 currencyId) { return txHistory.deposit(index); } /// @notice Close the current accrual period of the given currencies /// @param currencies The concerned currencies function closeAccrualPeriod(MonetaryTypesLib.Currency[] memory currencies) public onlyOperator { require( ConstantsLib.PARTS_PER() == totalBeneficiaryFraction, "Total beneficiary fraction out of bounds [RevenueFund.sol:236]" ); // Execute transfer for (uint256 i = 0; i < currencies.length; i++) { MonetaryTypesLib.Currency memory currency = currencies[i]; int256 remaining = periodAccrual.get(currency.ct, currency.id); if (0 >= remaining) continue; for (uint256 j = 0; j < beneficiaries.length; j++) { AccrualBeneficiary beneficiary = AccrualBeneficiary(address(beneficiaries[j])); if (beneficiaryFraction(beneficiary) > 0) { int256 transferable = periodAccrual.get(currency.ct, currency.id) .mul(beneficiaryFraction(beneficiary)) .div(ConstantsLib.PARTS_PER()); if (transferable > remaining) transferable = remaining; if (transferable > 0) { // Transfer ETH to the beneficiary if (currency.ct == address(0)) beneficiary.receiveEthersTo.value(uint256(transferable))(address(0), ""); // Transfer token to the beneficiary else { TransferController controller = transferController(currency.ct, ""); (bool success,) = address(controller).delegatecall( abi.encodeWithSelector( controller.getApproveSignature(), address(beneficiary), uint256(transferable), currency.ct, currency.id ) ); require(success, "Approval by controller failed [RevenueFund.sol:274]"); beneficiary.receiveTokensTo(address(0), "", transferable, currency.ct, currency.id, ""); } remaining = remaining.sub(transferable); } } } // Roll over remaining to next accrual period periodAccrual.set(remaining, currency.ct, currency.id); } // Close accrual period of accrual beneficiaries for (uint256 j = 0; j < beneficiaries.length; j++) { AccrualBeneficiary beneficiary = AccrualBeneficiary(address(beneficiaries[j])); // Require that beneficiary fraction is strictly positive if (0 >= beneficiaryFraction(beneficiary)) continue; // Close accrual period beneficiary.closeAccrualPeriod(currencies); } // Emit event emit CloseAccrualPeriodEvent(); } }
receiveTokensTo(msg.sender, balanceType, amount, currencyCt, currencyId, standard);
function receiveTokens(string memory balanceType, int256 amount, address currencyCt, uint256 currencyId, string memory standard) public
/// @notice Receive tokens /// @param amount The concerned amount /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// @param standard The standard of token ("ERC20", "ERC721") function receiveTokens(string memory balanceType, int256 amount, address currencyCt, uint256 currencyId, string memory standard) public
11315
PryzeSale
calculateAllocation
contract PryzeSale is Sale, Whitelistable { uint256 public constant PRESALE_WEI = 10695.303 ether; // Amount raised in the presale uint256 public constant PRESALE_WEI_WITH_BONUS = 10695.303 ether * 1.5; // Amount raised in the presale times the bonus uint256 public constant MAX_WEI = 24695.303 ether; // Max wei to raise, including PRESALE_WEI uint256 public constant WEI_CAP = 14000 ether; // MAX_WEI - PRESALE_WEI uint256 public constant MAX_TOKENS = 400000000 * 1000000000000000000; // 4mm times 10^18 (18 decimals) uint256 public presaleWeiContributed = 0; uint256 private weiAllocated = 0; mapping(address => uint256) public presaleContributions; function PryzeSale( address _wallet ) Sale(_wallet, WEI_CAP) public { } /// @dev Sets the presale contribution for a contributor. /// @param _contributor The contributor. /// @param _amount The amount contributed in the presale (without the bonus). function presaleContribute(address _contributor, uint256 _amount) external onlyOwner checkAllowed { // If presale contribution is already set, replace the amount in the presaleWeiContributed variable if (presaleContributions[_contributor] != 0) { presaleWeiContributed = presaleWeiContributed.sub(presaleContributions[_contributor]); } presaleWeiContributed = presaleWeiContributed.add(_amount); require(presaleWeiContributed <= PRESALE_WEI); presaleContributions[_contributor] = _amount; } /// @dev Called to allocate the tokens depending on eth contributed. /// @param contributor The address of the contributor. function allocateTokens(address contributor) external checkAllowed { require(presaleContributions[contributor] != 0 || contributions[contributor] != 0); uint256 tokensToAllocate = calculateAllocation(contributor); // We keep a record of how much wei contributed has already been used for allocations weiAllocated = weiAllocated.add(presaleContributions[contributor]).add(contributions[contributor]); // Set contributions to 0 presaleContributions[contributor] = 0; contributions[contributor] = 0; // Mint the respective tokens to the contributor token.mint(contributor, tokensToAllocate); // If all tokens were allocated, stop minting functionality if (weiAllocated == PRESALE_WEI.add(weiContributed)) { token.finishMinting(); } } function setupDone() public onlyOwner checkAllowed { require(presaleWeiContributed == PRESALE_WEI); super.setupDone(); } /// @dev Calculate the PRYZ allocation for the given contributor. The allocation is proportional to the amount of wei contributed. /// @param contributor The address of the contributor /// @return The amount of tokens to allocate function calculateAllocation(address contributor) public constant returns (uint256) {<FILL_FUNCTION_BODY> } function setupStages() internal { super.setupStages(); state.allowFunction(SETUP, this.presaleContribute.selector); state.allowFunction(SALE_ENDED, this.allocateTokens.selector); } function createTokenContract() internal returns(MintableToken) { return new PryzeToken(); } function getContributionLimit(address userAddress) internal returns (uint256) { // No contribution cap if whitelisted return whitelisted[userAddress] ? 2**256 - 1 : 0; } }
contract PryzeSale is Sale, Whitelistable { uint256 public constant PRESALE_WEI = 10695.303 ether; // Amount raised in the presale uint256 public constant PRESALE_WEI_WITH_BONUS = 10695.303 ether * 1.5; // Amount raised in the presale times the bonus uint256 public constant MAX_WEI = 24695.303 ether; // Max wei to raise, including PRESALE_WEI uint256 public constant WEI_CAP = 14000 ether; // MAX_WEI - PRESALE_WEI uint256 public constant MAX_TOKENS = 400000000 * 1000000000000000000; // 4mm times 10^18 (18 decimals) uint256 public presaleWeiContributed = 0; uint256 private weiAllocated = 0; mapping(address => uint256) public presaleContributions; function PryzeSale( address _wallet ) Sale(_wallet, WEI_CAP) public { } /// @dev Sets the presale contribution for a contributor. /// @param _contributor The contributor. /// @param _amount The amount contributed in the presale (without the bonus). function presaleContribute(address _contributor, uint256 _amount) external onlyOwner checkAllowed { // If presale contribution is already set, replace the amount in the presaleWeiContributed variable if (presaleContributions[_contributor] != 0) { presaleWeiContributed = presaleWeiContributed.sub(presaleContributions[_contributor]); } presaleWeiContributed = presaleWeiContributed.add(_amount); require(presaleWeiContributed <= PRESALE_WEI); presaleContributions[_contributor] = _amount; } /// @dev Called to allocate the tokens depending on eth contributed. /// @param contributor The address of the contributor. function allocateTokens(address contributor) external checkAllowed { require(presaleContributions[contributor] != 0 || contributions[contributor] != 0); uint256 tokensToAllocate = calculateAllocation(contributor); // We keep a record of how much wei contributed has already been used for allocations weiAllocated = weiAllocated.add(presaleContributions[contributor]).add(contributions[contributor]); // Set contributions to 0 presaleContributions[contributor] = 0; contributions[contributor] = 0; // Mint the respective tokens to the contributor token.mint(contributor, tokensToAllocate); // If all tokens were allocated, stop minting functionality if (weiAllocated == PRESALE_WEI.add(weiContributed)) { token.finishMinting(); } } function setupDone() public onlyOwner checkAllowed { require(presaleWeiContributed == PRESALE_WEI); super.setupDone(); } <FILL_FUNCTION> function setupStages() internal { super.setupStages(); state.allowFunction(SETUP, this.presaleContribute.selector); state.allowFunction(SALE_ENDED, this.allocateTokens.selector); } function createTokenContract() internal returns(MintableToken) { return new PryzeToken(); } function getContributionLimit(address userAddress) internal returns (uint256) { // No contribution cap if whitelisted return whitelisted[userAddress] ? 2**256 - 1 : 0; } }
uint256 presale = presaleContributions[contributor].mul(15).div(10); // Multiply by 1.5 uint256 totalContribution = presale.add(contributions[contributor]); return totalContribution.mul(MAX_TOKENS).div(PRESALE_WEI_WITH_BONUS.add(weiContributed));
function calculateAllocation(address contributor) public constant returns (uint256)
/// @dev Calculate the PRYZ allocation for the given contributor. The allocation is proportional to the amount of wei contributed. /// @param contributor The address of the contributor /// @return The amount of tokens to allocate function calculateAllocation(address contributor) public constant returns (uint256)
58990
Proxy
_emit
contract Proxy is Owned { Proxyable public target; constructor(address _owner) public Owned(_owner) {} function setTarget(Proxyable _target) external onlyOwner { target = _target; emit TargetUpdated(_target); } function _emit( bytes calldata callData, uint numTopics, bytes32 topic1, bytes32 topic2, bytes32 topic3, bytes32 topic4 ) external onlyTarget {<FILL_FUNCTION_BODY> } // solhint-disable no-complex-fallback function() external payable { // Mutable call setting Proxyable.messageSender as this is using call not delegatecall target.setMessageSender(msg.sender); assembly { let free_ptr := mload(0x40) calldatacopy(free_ptr, 0, calldatasize) /* We must explicitly forward ether to the underlying contract as well. */ let result := call(gas, sload(target_slot), callvalue, free_ptr, calldatasize, 0, 0) returndatacopy(free_ptr, 0, returndatasize) if iszero(result) { revert(free_ptr, returndatasize) } return(free_ptr, returndatasize) } } modifier onlyTarget { require(Proxyable(msg.sender) == target, "Must be proxy target"); _; } event TargetUpdated(Proxyable newTarget); }
contract Proxy is Owned { Proxyable public target; constructor(address _owner) public Owned(_owner) {} function setTarget(Proxyable _target) external onlyOwner { target = _target; emit TargetUpdated(_target); } <FILL_FUNCTION> // solhint-disable no-complex-fallback function() external payable { // Mutable call setting Proxyable.messageSender as this is using call not delegatecall target.setMessageSender(msg.sender); assembly { let free_ptr := mload(0x40) calldatacopy(free_ptr, 0, calldatasize) /* We must explicitly forward ether to the underlying contract as well. */ let result := call(gas, sload(target_slot), callvalue, free_ptr, calldatasize, 0, 0) returndatacopy(free_ptr, 0, returndatasize) if iszero(result) { revert(free_ptr, returndatasize) } return(free_ptr, returndatasize) } } modifier onlyTarget { require(Proxyable(msg.sender) == target, "Must be proxy target"); _; } event TargetUpdated(Proxyable newTarget); }
uint size = callData.length; bytes memory _callData = callData; assembly { /* The first 32 bytes of callData contain its length (as specified by the abi). * Length is assumed to be a uint256 and therefore maximum of 32 bytes * in length. It is also leftpadded to be a multiple of 32 bytes. * This means moving call_data across 32 bytes guarantees we correctly access * the data itself. */ switch numTopics case 0 { log0(add(_callData, 32), size) } case 1 { log1(add(_callData, 32), size, topic1) } case 2 { log2(add(_callData, 32), size, topic1, topic2) } case 3 { log3(add(_callData, 32), size, topic1, topic2, topic3) } case 4 { log4(add(_callData, 32), size, topic1, topic2, topic3, topic4) } }
function _emit( bytes calldata callData, uint numTopics, bytes32 topic1, bytes32 topic2, bytes32 topic3, bytes32 topic4 ) external onlyTarget
function _emit( bytes calldata callData, uint numTopics, bytes32 topic1, bytes32 topic2, bytes32 topic3, bytes32 topic4 ) external onlyTarget
17400
GoldmintMigration
migrateMntp
contract GoldmintMigration is CreatorEnabled { // Fields: IMNTP public mntpToken; Gold public goldToken; enum State { Init, MigrationStarted, MigrationPaused, MigrationFinished } State public state = State.Init; // this is total collected GOLD rewards (launch to migration start) uint public mntpToMigrateTotal = 0; uint public migrationRewardTotal = 0; uint64 public migrationStartedTime = 0; uint64 public migrationFinishedTime = 0; struct Migration { address ethAddress; string gmAddress; uint tokensCount; bool migrated; uint64 date; string comment; } mapping (uint=>Migration) public mntpMigrations; mapping (address=>uint) public mntpMigrationIndexes; uint public mntpMigrationsCount = 0; mapping (uint=>Migration) public goldMigrations; mapping (address=>uint) public goldMigrationIndexes; uint public goldMigrationsCount = 0; event MntpMigrateWanted(address _ethAddress, string _gmAddress, uint256 _value); event MntpMigrated(address _ethAddress, string _gmAddress, uint256 _value); event GoldMigrateWanted(address _ethAddress, string _gmAddress, uint256 _value); event GoldMigrated(address _ethAddress, string _gmAddress, uint256 _value); // Access methods function getMntpMigration(uint index) public constant returns(address,string,uint,bool,uint64,string){ Migration memory mig = mntpMigrations[index]; return (mig.ethAddress, mig.gmAddress, mig.tokensCount, mig.migrated, mig.date, mig.comment); } function getGoldMigration(uint index) public constant returns(address,string,uint,bool,uint64,string){ Migration memory mig = goldMigrations[index]; return (mig.ethAddress, mig.gmAddress, mig.tokensCount, mig.migrated, mig.date, mig.comment); } // Functions: // Constructor function GoldmintMigration(address _mntpContractAddress, address _goldContractAddress) public { creator = msg.sender; require(_mntpContractAddress != 0); require(_goldContractAddress != 0); mntpMigrationIndexes[address(0x0)] = 0; goldMigrationIndexes[address(0x0)] = 0; mntpToken = IMNTP(_mntpContractAddress); goldToken = Gold(_goldContractAddress); } function lockMntpTransfers(bool _lock) public onlyCreator { mntpToken.lockTransfer(_lock); } function lockGoldTransfers(bool _lock) public onlyCreator { goldToken.lockTransfer(_lock); } // This method is called when migration to Goldmint's blockchain // process is started... function startMigration() public onlyCreator { require((State.Init == state) || (State.MigrationPaused == state)); if (State.Init == state) { // 1 - change fees goldToken.startMigration(); // 2 - store the current values migrationRewardTotal = goldToken.balanceOf(this); migrationStartedTime = uint64(now); mntpToMigrateTotal = mntpToken.totalSupply(); } state = State.MigrationStarted; } function pauseMigration() public onlyCreator { require((state == State.MigrationStarted) || (state == State.MigrationFinished)); state = State.MigrationPaused; } // that doesn't mean that you cant migrate from Ethereum -> Goldmint blockchain // that means that you will get no reward function finishMigration() public onlyCreator { require((State.MigrationStarted == state) || (State.MigrationPaused == state)); if (State.MigrationStarted == state) { goldToken.finishMigration(); migrationFinishedTime = uint64(now); } state = State.MigrationFinished; } function destroyMe() public onlyCreator { selfdestruct(msg.sender); } // MNTP // Call this to migrate your MNTP tokens to Goldmint MNT // (this is one-way only) // _gmAddress is something like that - "BTS7yRXCkBjKxho57RCbqYE3nEiprWXXESw3Hxs5CKRnft8x7mdGi" // // !!! WARNING: will not allow anyone to migrate tokens partly // !!! DISCLAIMER: check goldmint blockchain address format. You will not be able to change that! function migrateMntp(string _gmAddress) public {<FILL_FUNCTION_BODY> } function isMntpMigrated(address _who) public constant returns(bool) { uint index = mntpMigrationIndexes[_who]; Migration memory mig = mntpMigrations[index]; return mig.migrated; } function setMntpMigrated(address _who, bool _isMigrated, string _comment) public onlyCreator { uint index = mntpMigrationIndexes[_who]; require(index > 0); mntpMigrations[index].migrated = _isMigrated; mntpMigrations[index].comment = _comment; // send an event if (_isMigrated) { MntpMigrated( mntpMigrations[index].ethAddress, mntpMigrations[index].gmAddress, mntpMigrations[index].tokensCount); } } // GOLD function migrateGold(string _gmAddress) public { require((state==State.MigrationStarted) || (state==State.MigrationFinished)); // 1 - get balance uint myBalance = goldToken.balanceOf(msg.sender); require(0!=myBalance); // 2 - burn tokens // WARNING: burn will reduce totalSupply // goldToken.burnTokens(msg.sender,myBalance); // save tuple Migration memory mig; mig.ethAddress = msg.sender; mig.gmAddress = _gmAddress; mig.tokensCount = myBalance; mig.migrated = false; mig.date = uint64(now); mig.comment = ''; goldMigrations[goldMigrationsCount + 1] = mig; goldMigrationIndexes[msg.sender] = goldMigrationsCount + 1; goldMigrationsCount++; // send an event GoldMigrateWanted(msg.sender, _gmAddress, myBalance); } function isGoldMigrated(address _who) public constant returns(bool) { uint index = goldMigrationIndexes[_who]; Migration memory mig = goldMigrations[index]; return mig.migrated; } function setGoldMigrated(address _who, bool _isMigrated, string _comment) public onlyCreator { uint index = goldMigrationIndexes[_who]; require(index > 0); goldMigrations[index].migrated = _isMigrated; goldMigrations[index].comment = _comment; // send an event if (_isMigrated) { GoldMigrated( goldMigrations[index].ethAddress, goldMigrations[index].gmAddress, goldMigrations[index].tokensCount); } } // Each MNTP token holder gets a GOLD reward as a percent of all rewards // proportional to his MNTP token stake function calculateMyRewardMax(address _of) public constant returns(uint){ if (0 == mntpToMigrateTotal) { return 0; } uint myCurrentMntpBalance = mntpToken.balanceOf(_of); if (0 == myCurrentMntpBalance) { return 0; } return (migrationRewardTotal * myCurrentMntpBalance) / mntpToMigrateTotal; } //emergency function. used in case of a mistake to transfer all the reward to a new migraiton smart contract. function transferReward(address _newContractAddress) public onlyCreator { goldToken.transferRewardWithoutFee(_newContractAddress, goldToken.balanceOf(this)); } // Migration rewards decreased linearly. // // The formula is: rewardPercents = max(100 - 100 * day / 365, 0) // // On 1st day of migration, you will get: 100 - 100 * 0/365 = 100% of your rewards // On 2nd day of migration, you will get: 100 - 100 * 1/365 = 99.7261% of your rewards // On 365th day of migration, you will get: 100 - 100 * 364/365 = 0.274% function calculateMyRewardDecreased(uint _day, uint _myRewardMax) public constant returns(uint){ if (_day >= 365) { return 0; } uint x = ((100 * 1000000000 * _day) / 365); return (_myRewardMax * ((100 * 1000000000) - x)) / (100 * 1000000000); } function calculateMyReward(uint _myRewardMax) public constant returns(uint){ // day starts from 0 uint day = (uint64(now) - migrationStartedTime) / uint64(1 days); return calculateMyRewardDecreased(day, _myRewardMax); } // do not allow to send money to this contract... function() external payable { revert(); } }
contract GoldmintMigration is CreatorEnabled { // Fields: IMNTP public mntpToken; Gold public goldToken; enum State { Init, MigrationStarted, MigrationPaused, MigrationFinished } State public state = State.Init; // this is total collected GOLD rewards (launch to migration start) uint public mntpToMigrateTotal = 0; uint public migrationRewardTotal = 0; uint64 public migrationStartedTime = 0; uint64 public migrationFinishedTime = 0; struct Migration { address ethAddress; string gmAddress; uint tokensCount; bool migrated; uint64 date; string comment; } mapping (uint=>Migration) public mntpMigrations; mapping (address=>uint) public mntpMigrationIndexes; uint public mntpMigrationsCount = 0; mapping (uint=>Migration) public goldMigrations; mapping (address=>uint) public goldMigrationIndexes; uint public goldMigrationsCount = 0; event MntpMigrateWanted(address _ethAddress, string _gmAddress, uint256 _value); event MntpMigrated(address _ethAddress, string _gmAddress, uint256 _value); event GoldMigrateWanted(address _ethAddress, string _gmAddress, uint256 _value); event GoldMigrated(address _ethAddress, string _gmAddress, uint256 _value); // Access methods function getMntpMigration(uint index) public constant returns(address,string,uint,bool,uint64,string){ Migration memory mig = mntpMigrations[index]; return (mig.ethAddress, mig.gmAddress, mig.tokensCount, mig.migrated, mig.date, mig.comment); } function getGoldMigration(uint index) public constant returns(address,string,uint,bool,uint64,string){ Migration memory mig = goldMigrations[index]; return (mig.ethAddress, mig.gmAddress, mig.tokensCount, mig.migrated, mig.date, mig.comment); } // Functions: // Constructor function GoldmintMigration(address _mntpContractAddress, address _goldContractAddress) public { creator = msg.sender; require(_mntpContractAddress != 0); require(_goldContractAddress != 0); mntpMigrationIndexes[address(0x0)] = 0; goldMigrationIndexes[address(0x0)] = 0; mntpToken = IMNTP(_mntpContractAddress); goldToken = Gold(_goldContractAddress); } function lockMntpTransfers(bool _lock) public onlyCreator { mntpToken.lockTransfer(_lock); } function lockGoldTransfers(bool _lock) public onlyCreator { goldToken.lockTransfer(_lock); } // This method is called when migration to Goldmint's blockchain // process is started... function startMigration() public onlyCreator { require((State.Init == state) || (State.MigrationPaused == state)); if (State.Init == state) { // 1 - change fees goldToken.startMigration(); // 2 - store the current values migrationRewardTotal = goldToken.balanceOf(this); migrationStartedTime = uint64(now); mntpToMigrateTotal = mntpToken.totalSupply(); } state = State.MigrationStarted; } function pauseMigration() public onlyCreator { require((state == State.MigrationStarted) || (state == State.MigrationFinished)); state = State.MigrationPaused; } // that doesn't mean that you cant migrate from Ethereum -> Goldmint blockchain // that means that you will get no reward function finishMigration() public onlyCreator { require((State.MigrationStarted == state) || (State.MigrationPaused == state)); if (State.MigrationStarted == state) { goldToken.finishMigration(); migrationFinishedTime = uint64(now); } state = State.MigrationFinished; } function destroyMe() public onlyCreator { selfdestruct(msg.sender); } <FILL_FUNCTION> function isMntpMigrated(address _who) public constant returns(bool) { uint index = mntpMigrationIndexes[_who]; Migration memory mig = mntpMigrations[index]; return mig.migrated; } function setMntpMigrated(address _who, bool _isMigrated, string _comment) public onlyCreator { uint index = mntpMigrationIndexes[_who]; require(index > 0); mntpMigrations[index].migrated = _isMigrated; mntpMigrations[index].comment = _comment; // send an event if (_isMigrated) { MntpMigrated( mntpMigrations[index].ethAddress, mntpMigrations[index].gmAddress, mntpMigrations[index].tokensCount); } } // GOLD function migrateGold(string _gmAddress) public { require((state==State.MigrationStarted) || (state==State.MigrationFinished)); // 1 - get balance uint myBalance = goldToken.balanceOf(msg.sender); require(0!=myBalance); // 2 - burn tokens // WARNING: burn will reduce totalSupply // goldToken.burnTokens(msg.sender,myBalance); // save tuple Migration memory mig; mig.ethAddress = msg.sender; mig.gmAddress = _gmAddress; mig.tokensCount = myBalance; mig.migrated = false; mig.date = uint64(now); mig.comment = ''; goldMigrations[goldMigrationsCount + 1] = mig; goldMigrationIndexes[msg.sender] = goldMigrationsCount + 1; goldMigrationsCount++; // send an event GoldMigrateWanted(msg.sender, _gmAddress, myBalance); } function isGoldMigrated(address _who) public constant returns(bool) { uint index = goldMigrationIndexes[_who]; Migration memory mig = goldMigrations[index]; return mig.migrated; } function setGoldMigrated(address _who, bool _isMigrated, string _comment) public onlyCreator { uint index = goldMigrationIndexes[_who]; require(index > 0); goldMigrations[index].migrated = _isMigrated; goldMigrations[index].comment = _comment; // send an event if (_isMigrated) { GoldMigrated( goldMigrations[index].ethAddress, goldMigrations[index].gmAddress, goldMigrations[index].tokensCount); } } // Each MNTP token holder gets a GOLD reward as a percent of all rewards // proportional to his MNTP token stake function calculateMyRewardMax(address _of) public constant returns(uint){ if (0 == mntpToMigrateTotal) { return 0; } uint myCurrentMntpBalance = mntpToken.balanceOf(_of); if (0 == myCurrentMntpBalance) { return 0; } return (migrationRewardTotal * myCurrentMntpBalance) / mntpToMigrateTotal; } //emergency function. used in case of a mistake to transfer all the reward to a new migraiton smart contract. function transferReward(address _newContractAddress) public onlyCreator { goldToken.transferRewardWithoutFee(_newContractAddress, goldToken.balanceOf(this)); } // Migration rewards decreased linearly. // // The formula is: rewardPercents = max(100 - 100 * day / 365, 0) // // On 1st day of migration, you will get: 100 - 100 * 0/365 = 100% of your rewards // On 2nd day of migration, you will get: 100 - 100 * 1/365 = 99.7261% of your rewards // On 365th day of migration, you will get: 100 - 100 * 364/365 = 0.274% function calculateMyRewardDecreased(uint _day, uint _myRewardMax) public constant returns(uint){ if (_day >= 365) { return 0; } uint x = ((100 * 1000000000 * _day) / 365); return (_myRewardMax * ((100 * 1000000000) - x)) / (100 * 1000000000); } function calculateMyReward(uint _myRewardMax) public constant returns(uint){ // day starts from 0 uint day = (uint64(now) - migrationStartedTime) / uint64(1 days); return calculateMyRewardDecreased(day, _myRewardMax); } // do not allow to send money to this contract... function() external payable { revert(); } }
require((state==State.MigrationStarted) || (state==State.MigrationFinished)); // 1 - calculate current reward uint myBalance = mntpToken.balanceOf(msg.sender); require(0!=myBalance); uint myRewardMax = calculateMyRewardMax(msg.sender); uint myReward = calculateMyReward(myRewardMax); // 2 - pay the reward to our user goldToken.transferRewardWithoutFee(msg.sender, myReward); // 3 - burn tokens // WARNING: burn will reduce totalSupply // // WARNING: creator must call // setIcoContractAddress(migrationContractAddress) // of the mntpToken mntpToken.burnTokens(msg.sender,myBalance); // save tuple Migration memory mig; mig.ethAddress = msg.sender; mig.gmAddress = _gmAddress; mig.tokensCount = myBalance; mig.migrated = false; mig.date = uint64(now); mig.comment = ''; mntpMigrations[mntpMigrationsCount + 1] = mig; mntpMigrationIndexes[msg.sender] = mntpMigrationsCount + 1; mntpMigrationsCount++; // send an event MntpMigrateWanted(msg.sender, _gmAddress, myBalance);
function migrateMntp(string _gmAddress) public
// MNTP // Call this to migrate your MNTP tokens to Goldmint MNT // (this is one-way only) // _gmAddress is something like that - "BTS7yRXCkBjKxho57RCbqYE3nEiprWXXESw3Hxs5CKRnft8x7mdGi" // // !!! WARNING: will not allow anyone to migrate tokens partly // !!! DISCLAIMER: check goldmint blockchain address format. You will not be able to change that! function migrateMntp(string _gmAddress) public
77321
TokenFactory
TokenFactory
contract TokenFactory is StandardToken { string public name; string public symbol; uint256 public decimals; function TokenFactory(uint256 _initialAmount, string _tokenName, uint8 _decimalUnits, string _tokenSymbol) {<FILL_FUNCTION_BODY> } }
contract TokenFactory is StandardToken { string public name; string public symbol; uint256 public decimals; <FILL_FUNCTION> }
balances[msg.sender] = _initialAmount; totalSupply = _initialAmount; name = _tokenName; decimals = _decimalUnits; symbol = _tokenSymbol;
function TokenFactory(uint256 _initialAmount, string _tokenName, uint8 _decimalUnits, string _tokenSymbol)
function TokenFactory(uint256 _initialAmount, string _tokenName, uint8 _decimalUnits, string _tokenSymbol)
3743
Owned
acceptCooOwnership
contract Owned { // The addresses of the accounts (or contracts) that can execute actions within each roles. address public ceoAddress; address public cooAddress; address private newCeoAddress; address private newCooAddress; function Owned() public { ceoAddress = msg.sender; cooAddress = msg.sender; } /*** ACCESS MODIFIERS ***/ /// @dev Access modifier for CEO-only functionality modifier onlyCEO() { require(msg.sender == ceoAddress); _; } /// @dev Access modifier for COO-only functionality modifier onlyCOO() { require(msg.sender == cooAddress); _; } /// Access modifier for contract owner only functionality modifier onlyCLevel() { require( msg.sender == ceoAddress || msg.sender == cooAddress ); _; } /// @dev Assigns a new address to act as the CEO. Only available to the current CEO. /// @param _newCEO The address of the new CEO function setCEO(address _newCEO) public onlyCEO { require(_newCEO != address(0)); newCeoAddress = _newCEO; } /// @dev Assigns a new address to act as the COO. Only available to the current COO. /// @param _newCOO The address of the new COO function setCOO(address _newCOO) public onlyCEO { require(_newCOO != address(0)); newCooAddress = _newCOO; } function acceptCeoOwnership() public { require(msg.sender == newCeoAddress); require(address(0) != newCeoAddress); ceoAddress = newCeoAddress; newCeoAddress = address(0); } function acceptCooOwnership() public {<FILL_FUNCTION_BODY> } mapping (address => bool) public youCollectContracts; function addYouCollectContract(address contractAddress, bool active) public onlyCOO { youCollectContracts[contractAddress] = active; } modifier onlyYCC() { require(youCollectContracts[msg.sender]); _; } InterfaceYCC ycc; InterfaceContentCreatorUniverse yct; InterfaceMining ycm; function setMainYouCollectContractAddresses(address yccContract, address yctContract, address ycmContract, address[] otherContracts) public onlyCOO { ycc = InterfaceYCC(yccContract); yct = InterfaceContentCreatorUniverse(yctContract); ycm = InterfaceMining(ycmContract); youCollectContracts[yccContract] = true; youCollectContracts[yctContract] = true; youCollectContracts[ycmContract] = true; for (uint16 index = 0; index < otherContracts.length; index++) { youCollectContracts[otherContracts[index]] = true; } } function setYccContractAddress(address yccContract) public onlyCOO { ycc = InterfaceYCC(yccContract); youCollectContracts[yccContract] = true; } function setYctContractAddress(address yctContract) public onlyCOO { yct = InterfaceContentCreatorUniverse(yctContract); youCollectContracts[yctContract] = true; } function setYcmContractAddress(address ycmContract) public onlyCOO { ycm = InterfaceMining(ycmContract); youCollectContracts[ycmContract] = true; } }
contract Owned { // The addresses of the accounts (or contracts) that can execute actions within each roles. address public ceoAddress; address public cooAddress; address private newCeoAddress; address private newCooAddress; function Owned() public { ceoAddress = msg.sender; cooAddress = msg.sender; } /*** ACCESS MODIFIERS ***/ /// @dev Access modifier for CEO-only functionality modifier onlyCEO() { require(msg.sender == ceoAddress); _; } /// @dev Access modifier for COO-only functionality modifier onlyCOO() { require(msg.sender == cooAddress); _; } /// Access modifier for contract owner only functionality modifier onlyCLevel() { require( msg.sender == ceoAddress || msg.sender == cooAddress ); _; } /// @dev Assigns a new address to act as the CEO. Only available to the current CEO. /// @param _newCEO The address of the new CEO function setCEO(address _newCEO) public onlyCEO { require(_newCEO != address(0)); newCeoAddress = _newCEO; } /// @dev Assigns a new address to act as the COO. Only available to the current COO. /// @param _newCOO The address of the new COO function setCOO(address _newCOO) public onlyCEO { require(_newCOO != address(0)); newCooAddress = _newCOO; } function acceptCeoOwnership() public { require(msg.sender == newCeoAddress); require(address(0) != newCeoAddress); ceoAddress = newCeoAddress; newCeoAddress = address(0); } <FILL_FUNCTION> mapping (address => bool) public youCollectContracts; function addYouCollectContract(address contractAddress, bool active) public onlyCOO { youCollectContracts[contractAddress] = active; } modifier onlyYCC() { require(youCollectContracts[msg.sender]); _; } InterfaceYCC ycc; InterfaceContentCreatorUniverse yct; InterfaceMining ycm; function setMainYouCollectContractAddresses(address yccContract, address yctContract, address ycmContract, address[] otherContracts) public onlyCOO { ycc = InterfaceYCC(yccContract); yct = InterfaceContentCreatorUniverse(yctContract); ycm = InterfaceMining(ycmContract); youCollectContracts[yccContract] = true; youCollectContracts[yctContract] = true; youCollectContracts[ycmContract] = true; for (uint16 index = 0; index < otherContracts.length; index++) { youCollectContracts[otherContracts[index]] = true; } } function setYccContractAddress(address yccContract) public onlyCOO { ycc = InterfaceYCC(yccContract); youCollectContracts[yccContract] = true; } function setYctContractAddress(address yctContract) public onlyCOO { yct = InterfaceContentCreatorUniverse(yctContract); youCollectContracts[yctContract] = true; } function setYcmContractAddress(address ycmContract) public onlyCOO { ycm = InterfaceMining(ycmContract); youCollectContracts[ycmContract] = true; } }
require(msg.sender == newCooAddress); require(address(0) != newCooAddress); cooAddress = newCooAddress; newCooAddress = address(0);
function acceptCooOwnership() public
function acceptCooOwnership() public
12966
onlyOwner
start
contract onlyOwner { address public owner; bool private stopped = false; /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = 0x073db5ac9aa943253a513cd692d16160f1c10e74; } modifier isRunning { require(!stopped); _; } function stop() isOwner public { stopped = true; } function start() isOwner public {<FILL_FUNCTION_BODY> } /** * @dev Throws if called by any account other than the owner. */ modifier isOwner { require(msg.sender == owner); _; } }
contract onlyOwner { address public owner; bool private stopped = false; /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = 0x073db5ac9aa943253a513cd692d16160f1c10e74; } modifier isRunning { require(!stopped); _; } function stop() isOwner public { stopped = true; } <FILL_FUNCTION> /** * @dev Throws if called by any account other than the owner. */ modifier isOwner { require(msg.sender == owner); _; } }
stopped = false;
function start() isOwner public
function start() isOwner public
43632
TokenTranchePricing
getCurrentTranche
contract TokenTranchePricing { using SafeMath for uint; /** * Define pricing schedule using tranches. */ struct Tranche { // Amount in tokens when this tranche becomes inactive uint amount; // Time interval [start, end) // Starting timestamp (included in the interval) uint start; // Ending timestamp (excluded from the interval) uint end; // How many tokens per wei you will get while this tranche is active uint price; } // We define offsets and size for the deserialization of ordered tuples in raw arrays uint private constant amount_offset = 0; uint private constant start_offset = 1; uint private constant end_offset = 2; uint private constant price_offset = 3; uint private constant tranche_size = 4; Tranche[] public tranches; /// @dev Construction, creating a list of tranches /// @param init_tranches Raw array of ordered tuples: (end amount, start timestamp, end timestamp, price) function TokenTranchePricing(uint[] init_tranches) public { // Need to have tuples, length check require(init_tranches.length % tranche_size == 0); // A tranche with amount zero can never be selected and is therefore useless. // This check and the one inside the loop ensure no tranche can have an amount equal to zero. require(init_tranches[amount_offset] > 0); tranches.length = init_tranches.length.div(tranche_size); Tranche memory last_tranche; for (uint i = 0; i < tranches.length; i++) { uint tranche_offset = i.mul(tranche_size); uint amount = init_tranches[tranche_offset.add(amount_offset)]; uint start = init_tranches[tranche_offset.add(start_offset)]; uint end = init_tranches[tranche_offset.add(end_offset)]; uint price = init_tranches[tranche_offset.add(price_offset)]; // No invalid steps require(block.timestamp < start && start < end); // Bail out when entering unnecessary tranches // This is preferably checked before deploying contract into any blockchain. require(i == 0 || (end >= last_tranche.end && amount > last_tranche.amount) || (end > last_tranche.end && amount >= last_tranche.amount)); last_tranche = Tranche(amount, start, end, price); tranches[i] = last_tranche; } } /// @dev Get the current tranche or bail out if there is no tranche defined for the current block. /// @param tokensSold total amount of tokens sold, for calculating the current tranche /// @return Returns the struct representing the current tranche function getCurrentTranche(uint tokensSold) private constant returns (Tranche storage) {<FILL_FUNCTION_BODY> } /// @dev Get the current price. May revert if there is no tranche currently active. /// @param tokensSold total amount of tokens sold, for calculating the current tranche /// @return The current price function getCurrentPrice(uint tokensSold) internal constant returns (uint result) { return getCurrentTranche(tokensSold).price; } }
contract TokenTranchePricing { using SafeMath for uint; /** * Define pricing schedule using tranches. */ struct Tranche { // Amount in tokens when this tranche becomes inactive uint amount; // Time interval [start, end) // Starting timestamp (included in the interval) uint start; // Ending timestamp (excluded from the interval) uint end; // How many tokens per wei you will get while this tranche is active uint price; } // We define offsets and size for the deserialization of ordered tuples in raw arrays uint private constant amount_offset = 0; uint private constant start_offset = 1; uint private constant end_offset = 2; uint private constant price_offset = 3; uint private constant tranche_size = 4; Tranche[] public tranches; /// @dev Construction, creating a list of tranches /// @param init_tranches Raw array of ordered tuples: (end amount, start timestamp, end timestamp, price) function TokenTranchePricing(uint[] init_tranches) public { // Need to have tuples, length check require(init_tranches.length % tranche_size == 0); // A tranche with amount zero can never be selected and is therefore useless. // This check and the one inside the loop ensure no tranche can have an amount equal to zero. require(init_tranches[amount_offset] > 0); tranches.length = init_tranches.length.div(tranche_size); Tranche memory last_tranche; for (uint i = 0; i < tranches.length; i++) { uint tranche_offset = i.mul(tranche_size); uint amount = init_tranches[tranche_offset.add(amount_offset)]; uint start = init_tranches[tranche_offset.add(start_offset)]; uint end = init_tranches[tranche_offset.add(end_offset)]; uint price = init_tranches[tranche_offset.add(price_offset)]; // No invalid steps require(block.timestamp < start && start < end); // Bail out when entering unnecessary tranches // This is preferably checked before deploying contract into any blockchain. require(i == 0 || (end >= last_tranche.end && amount > last_tranche.amount) || (end > last_tranche.end && amount >= last_tranche.amount)); last_tranche = Tranche(amount, start, end, price); tranches[i] = last_tranche; } } <FILL_FUNCTION> /// @dev Get the current price. May revert if there is no tranche currently active. /// @param tokensSold total amount of tokens sold, for calculating the current tranche /// @return The current price function getCurrentPrice(uint tokensSold) internal constant returns (uint result) { return getCurrentTranche(tokensSold).price; } }
for (uint i = 0; i < tranches.length; i++) { if (tranches[i].start <= block.timestamp && block.timestamp < tranches[i].end && tokensSold < tranches[i].amount) { return tranches[i]; } } // No tranche is currently active revert();
function getCurrentTranche(uint tokensSold) private constant returns (Tranche storage)
/// @dev Get the current tranche or bail out if there is no tranche defined for the current block. /// @param tokensSold total amount of tokens sold, for calculating the current tranche /// @return Returns the struct representing the current tranche function getCurrentTranche(uint tokensSold) private constant returns (Tranche storage)
76614
BerserkVote
averageVotingValue
contract BerserkVote { using SafeMath for uint256; uint8 public constant MAX_VOTERS_PER_ITEM = 50; uint16 public constant MIN_VOTING_VALUE = 50; // 50% (x0.5 times) uint16 public constant MAX_VOTING_VALUE = 200; // 200% (x2 times) mapping(address => mapping(uint256 => uint8)) public numVoters; // poolAddress -> votingItem (periodFinish) -> numVoters (the number of voters in this round) mapping(address => mapping(uint256 => address[MAX_VOTERS_PER_ITEM])) public voters; // poolAddress -> votingItem (periodFinish) -> voters (array) mapping(address => mapping(uint256 => mapping(address => bool))) public isInTopVoters; // poolAddress -> votingItem (periodFinish) -> isInTopVoters (map: voter -> in_top (true/false)) mapping(address => mapping(uint256 => mapping(address => uint16))) public voter2VotingValue; // poolAddress -> votingItem (periodFinish) -> voter2VotingValue (map: voter -> voting value) event Voted(address poolAddress, address indexed user, uint256 votingItem, uint16 votingValue); function getNumVotes( address poolAddressStake, uint256 valueAmount ) public view returns (uint256){ return numVoters[poolAddressStake][valueAmount]; } function isVotable(address poolAddress, address account, uint256 votingItem) public view returns (bool) { // already voted if (voter2VotingValue[poolAddress][votingItem][account] > 0) return false; BerserkRewards rewards = BerserkRewards(poolAddress); // hasn't any staking power if (rewards.stakingPower(account) == 0) return false; // number of voters is under limit still if (numVoters[poolAddress][votingItem] < MAX_VOTERS_PER_ITEM) return true; for (uint8 i = 0; i < numVoters[poolAddress][votingItem]; i++) { if (rewards.stakingPower(voters[poolAddress][votingItem][i]) < rewards.stakingPower(account)) return true; // there is some voters has lower staking power } return false; } function averageVotingValue(address poolAddress, uint256 votingItem) public view returns (uint16) {<FILL_FUNCTION_BODY> } function vote(address poolAddress, uint256 votingItem, uint16 votingValue) public { require(votingValue >= MIN_VOTING_VALUE, "votingValue is smaller than MIN_VOTING_VALUE"); require(votingValue <= MAX_VOTING_VALUE, "votingValue is greater than MAX_VOTING_VALUE"); if (!isInTopVoters[poolAddress][votingItem][msg.sender]) { require(isVotable(poolAddress, msg.sender, votingItem), "This account is not votable"); uint8 voterIndex = MAX_VOTERS_PER_ITEM; if (numVoters[poolAddress][votingItem] < MAX_VOTERS_PER_ITEM) { voterIndex = numVoters[poolAddress][votingItem]; } else { BerserkRewards rewards = BerserkRewards(poolAddress); uint256 minStakingPower = rewards.stakingPower(msg.sender); for (uint8 i = 0; i < numVoters[poolAddress][votingItem]; i++) { if (rewards.stakingPower(voters[poolAddress][votingItem][i]) < minStakingPower) { voterIndex = i; minStakingPower = rewards.stakingPower(voters[poolAddress][votingItem][i]); } } } if (voterIndex < MAX_VOTERS_PER_ITEM) { if (voterIndex < numVoters[poolAddress][votingItem]) { isInTopVoters[poolAddress][votingItem][voters[poolAddress][votingItem][voterIndex]] = false; // remove lower power previous voter } else { ++numVoters[poolAddress][votingItem]; } isInTopVoters[poolAddress][votingItem][msg.sender] = true; voters[poolAddress][votingItem][voterIndex] = msg.sender; } } voter2VotingValue[poolAddress][votingItem][msg.sender] = votingValue; emit Voted(poolAddress, msg.sender, votingItem, votingValue); } }
contract BerserkVote { using SafeMath for uint256; uint8 public constant MAX_VOTERS_PER_ITEM = 50; uint16 public constant MIN_VOTING_VALUE = 50; // 50% (x0.5 times) uint16 public constant MAX_VOTING_VALUE = 200; // 200% (x2 times) mapping(address => mapping(uint256 => uint8)) public numVoters; // poolAddress -> votingItem (periodFinish) -> numVoters (the number of voters in this round) mapping(address => mapping(uint256 => address[MAX_VOTERS_PER_ITEM])) public voters; // poolAddress -> votingItem (periodFinish) -> voters (array) mapping(address => mapping(uint256 => mapping(address => bool))) public isInTopVoters; // poolAddress -> votingItem (periodFinish) -> isInTopVoters (map: voter -> in_top (true/false)) mapping(address => mapping(uint256 => mapping(address => uint16))) public voter2VotingValue; // poolAddress -> votingItem (periodFinish) -> voter2VotingValue (map: voter -> voting value) event Voted(address poolAddress, address indexed user, uint256 votingItem, uint16 votingValue); function getNumVotes( address poolAddressStake, uint256 valueAmount ) public view returns (uint256){ return numVoters[poolAddressStake][valueAmount]; } function isVotable(address poolAddress, address account, uint256 votingItem) public view returns (bool) { // already voted if (voter2VotingValue[poolAddress][votingItem][account] > 0) return false; BerserkRewards rewards = BerserkRewards(poolAddress); // hasn't any staking power if (rewards.stakingPower(account) == 0) return false; // number of voters is under limit still if (numVoters[poolAddress][votingItem] < MAX_VOTERS_PER_ITEM) return true; for (uint8 i = 0; i < numVoters[poolAddress][votingItem]; i++) { if (rewards.stakingPower(voters[poolAddress][votingItem][i]) < rewards.stakingPower(account)) return true; // there is some voters has lower staking power } return false; } <FILL_FUNCTION> function vote(address poolAddress, uint256 votingItem, uint16 votingValue) public { require(votingValue >= MIN_VOTING_VALUE, "votingValue is smaller than MIN_VOTING_VALUE"); require(votingValue <= MAX_VOTING_VALUE, "votingValue is greater than MAX_VOTING_VALUE"); if (!isInTopVoters[poolAddress][votingItem][msg.sender]) { require(isVotable(poolAddress, msg.sender, votingItem), "This account is not votable"); uint8 voterIndex = MAX_VOTERS_PER_ITEM; if (numVoters[poolAddress][votingItem] < MAX_VOTERS_PER_ITEM) { voterIndex = numVoters[poolAddress][votingItem]; } else { BerserkRewards rewards = BerserkRewards(poolAddress); uint256 minStakingPower = rewards.stakingPower(msg.sender); for (uint8 i = 0; i < numVoters[poolAddress][votingItem]; i++) { if (rewards.stakingPower(voters[poolAddress][votingItem][i]) < minStakingPower) { voterIndex = i; minStakingPower = rewards.stakingPower(voters[poolAddress][votingItem][i]); } } } if (voterIndex < MAX_VOTERS_PER_ITEM) { if (voterIndex < numVoters[poolAddress][votingItem]) { isInTopVoters[poolAddress][votingItem][voters[poolAddress][votingItem][voterIndex]] = false; // remove lower power previous voter } else { ++numVoters[poolAddress][votingItem]; } isInTopVoters[poolAddress][votingItem][msg.sender] = true; voters[poolAddress][votingItem][voterIndex] = msg.sender; } } voter2VotingValue[poolAddress][votingItem][msg.sender] = votingValue; emit Voted(poolAddress, msg.sender, votingItem, votingValue); } }
if (numVoters[poolAddress][votingItem] == 0) return 0; // no votes uint256 totalStakingPower = 0; uint256 totalWeightVotingValue = 0; BerserkRewards rewards = BerserkRewards(poolAddress); for (uint8 i = 0; i < numVoters[poolAddress][votingItem]; i++) { address voter = voters[poolAddress][votingItem][i]; totalStakingPower = totalStakingPower.add(rewards.stakingPower(voter)); totalWeightVotingValue = totalWeightVotingValue.add(rewards.stakingPower(voter).mul(voter2VotingValue[poolAddress][votingItem][voter])); } return (uint16) (totalWeightVotingValue.div(totalStakingPower));
function averageVotingValue(address poolAddress, uint256 votingItem) public view returns (uint16)
function averageVotingValue(address poolAddress, uint256 votingItem) public view returns (uint16)
40365
ERC20
transferFrom
contract ERC20 is ERC20Interface,SafeMath { mapping(address => uint256) public balanceOf; mapping(address => mapping(address => uint256)) allowed; constructor(string memory _name) public { name = _name; symbol = "FSF"; decimals = 18; totalSupply = 1000000000000000000000000000; balanceOf[msg.sender] = totalSupply; } function transfer(address _to, uint256 _value) public returns (bool success) { require(_to != address(0)); require(balanceOf[msg.sender] >= _value); require(balanceOf[ _to] + _value >= balanceOf[ _to]); balanceOf[msg.sender] =SafeMath.safeSub(balanceOf[msg.sender],_value) ; balanceOf[_to] =SafeMath.safeAdd(balanceOf[_to] ,_value); emit Transfer(msg.sender, _to, _value); return true; } function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {<FILL_FUNCTION_BODY> } function approve(address _spender, uint256 _value) public returns (bool success) { require((_value==0)||(allowed[msg.sender][_spender]==0)); allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) public view returns (uint256 remaining) { return allowed[_owner][_spender]; } }
contract ERC20 is ERC20Interface,SafeMath { mapping(address => uint256) public balanceOf; mapping(address => mapping(address => uint256)) allowed; constructor(string memory _name) public { name = _name; symbol = "FSF"; decimals = 18; totalSupply = 1000000000000000000000000000; balanceOf[msg.sender] = totalSupply; } function transfer(address _to, uint256 _value) public returns (bool success) { require(_to != address(0)); require(balanceOf[msg.sender] >= _value); require(balanceOf[ _to] + _value >= balanceOf[ _to]); balanceOf[msg.sender] =SafeMath.safeSub(balanceOf[msg.sender],_value) ; balanceOf[_to] =SafeMath.safeAdd(balanceOf[_to] ,_value); emit Transfer(msg.sender, _to, _value); return true; } <FILL_FUNCTION> function approve(address _spender, uint256 _value) public returns (bool success) { require((_value==0)||(allowed[msg.sender][_spender]==0)); allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) public view returns (uint256 remaining) { return allowed[_owner][_spender]; } }
require(_to != address(0)); require(allowed[_from][msg.sender] >= _value); require(balanceOf[_from] >= _value); require(balanceOf[_to] + _value >= balanceOf[_to]); balanceOf[_from] =SafeMath.safeSub(balanceOf[_from],_value) ; balanceOf[_to] = SafeMath.safeAdd(balanceOf[_to],_value); allowed[_from][msg.sender] =SafeMath.safeSub(allowed[_from][msg.sender], _value); emit Transfer(msg.sender, _to, _value); return true;
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success)
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success)
61131
Pausable
pause
contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev modifier to allow actions only when the contract IS paused */ modifier whenNotPaused() { require(!paused); _; } /** * @dev modifier to allow actions only when the contract IS NOT paused */ modifier whenPaused { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public returns (bool) {<FILL_FUNCTION_BODY> } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public returns (bool) { paused = false; emit Unpause(); return true; } }
contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev modifier to allow actions only when the contract IS paused */ modifier whenNotPaused() { require(!paused); _; } /** * @dev modifier to allow actions only when the contract IS NOT paused */ modifier whenPaused { require(paused); _; } <FILL_FUNCTION> /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public returns (bool) { paused = false; emit Unpause(); return true; } }
paused = true; emit Pause(); return true;
function pause() onlyOwner whenNotPaused public returns (bool)
/** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public returns (bool)
53950
DBXTTest
balanceOf
contract DBXTTest is ERC20Interface, Owned, SafeMath { string public symbol; string public name; uint8 public decimals; uint public _totalSupply; uint public startDate; uint public endDate; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ constructor() public { symbol = "DBXTTest"; name = "DBXTTest"; decimals = 18; endDate = now + 12 weeks; } // ------------------------------------------------------------------------ // 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) {<FILL_FUNCTION_BODY> } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to `to` account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer `tokens` from the `from` account to the `to` account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the `from` account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account. The `spender` contract function // `receiveApproval(...)` is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } // ------------------------------------------------------------------------ // 25,000 DBXTTest Tokens per 1 ETH // ------------------------------------------------------------------------ function () public payable { require(now >= startDate && now <= endDate); uint tokens; tokens = msg.value * 25000; balances[msg.sender] = safeAdd(balances[msg.sender], tokens); _totalSupply = safeAdd(_totalSupply, tokens); emit Transfer(address(0), msg.sender, tokens); owner.transfer(msg.value); } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
contract DBXTTest is ERC20Interface, Owned, SafeMath { string public symbol; string public name; uint8 public decimals; uint public _totalSupply; uint public startDate; uint public endDate; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ constructor() public { symbol = "DBXTTest"; name = "DBXTTest"; decimals = 18; endDate = now + 12 weeks; } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } <FILL_FUNCTION> // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to `to` account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer `tokens` from the `from` account to the `to` account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the `from` account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account. The `spender` contract function // `receiveApproval(...)` is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } // ------------------------------------------------------------------------ // 25,000 DBXTTest Tokens per 1 ETH // ------------------------------------------------------------------------ function () public payable { require(now >= startDate && now <= endDate); uint tokens; tokens = msg.value * 25000; balances[msg.sender] = safeAdd(balances[msg.sender], tokens); _totalSupply = safeAdd(_totalSupply, tokens); emit Transfer(address(0), msg.sender, tokens); owner.transfer(msg.value); } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
return balances[tokenOwner];
function balanceOf(address tokenOwner) public constant returns (uint balance)
// ------------------------------------------------------------------------ // Get the token balance for account `tokenOwner` // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant returns (uint balance)
37470
ERC20
_burn
contract ERC20 is IERC20 { using SafeMath for uint256; mapping (address => uint256) internal _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; function totalSupply() public view returns (uint256) { return _totalSupply; } function balanceOf(address account) public view returns (uint256) { return _balances[account]; } function transfer(address recipient, uint256 amount) public returns (bool) { _transfer(msg.sender, recipient, amount); return true; } function allowance(address owner, address spender) public view returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 value) public returns (bool) { _approve(msg.sender, spender, value); return true; } function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) { _transfer(sender, recipient, amount); _approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount)); return true; } function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue)); return true; } function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } function _mint(address account, uint256 amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } function _burn(address owner, uint256 value) internal {<FILL_FUNCTION_BODY> } function _approve(address owner, address spender, uint256 value) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = value; emit Approval(owner, spender, value); } function _burnFrom(address owner, uint256 amount) internal { _burn(owner, amount); _approve(owner, msg.sender, _allowances[owner][msg.sender].sub(amount)); } }
contract ERC20 is IERC20 { using SafeMath for uint256; mapping (address => uint256) internal _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; function totalSupply() public view returns (uint256) { return _totalSupply; } function balanceOf(address account) public view returns (uint256) { return _balances[account]; } function transfer(address recipient, uint256 amount) public returns (bool) { _transfer(msg.sender, recipient, amount); return true; } function allowance(address owner, address spender) public view returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 value) public returns (bool) { _approve(msg.sender, spender, value); return true; } function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) { _transfer(sender, recipient, amount); _approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount)); return true; } function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue)); return true; } function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } function _mint(address account, uint256 amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } <FILL_FUNCTION> function _approve(address owner, address spender, uint256 value) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = value; emit Approval(owner, spender, value); } function _burnFrom(address owner, uint256 amount) internal { _burn(owner, amount); _approve(owner, msg.sender, _allowances[owner][msg.sender].sub(amount)); } }
require(owner != address(0), "ERC20: burn from the zero address"); _totalSupply = _totalSupply.sub(value); _balances[owner] = _balances[owner].sub(value); emit Transfer(owner, address(0), value);
function _burn(address owner, uint256 value) internal
function _burn(address owner, uint256 value) internal
66478
TimeAuctionBase
_bid
contract TimeAuctionBase { // Represents an auction on an NFT struct Auction { // Current owner of NFT address seller; // Price (in wei) at beginning of auction uint128 startingPrice; // Price (in wei) at end of auction uint128 endingPrice; // Duration (in seconds) of auction uint64 duration; // Time when auction started // NOTE: 0 if this auction has been concluded uint64 startedAt; } // Reference to contract tracking NFT ownership ERC721 public nonFungibleContract; // Cut owner takes on each auction, measured in basis points (1/100 of a percent). // Values 0-10,000 map to 0%-100% uint256 public ownerCut; // Map from token ID to their corresponding auction. mapping (uint256 => Auction) tokenIdToAuction; event AuctionCreated(uint256 tokenId, address seller, uint256 startingPrice, uint256 endingPrice, uint256 duration); event AuctionSuccessful(uint256 tokenId, uint256 totalPrice, address winner); event AuctionCancelled(uint256 tokenId); event AuctionSettled(uint256 tokenId, uint256 price, uint256 sellerProceeds, address seller, address buyer); event AuctionRepriced(uint256 tokenId, uint256 startingPrice, uint256 endingPrice, uint64 duration, uint64 startedAt); /// @dev DON'T give me your money. function() external {} // Modifiers to check that inputs can be safely stored with a certain // number of bits. We use constants and multiple modifiers to save gas. modifier canBeStoredWith32Bits(uint256 _value) { require(_value <= 4294967295); _; } // Modifiers to check that inputs can be safely stored with a certain // number of bits. We use constants and multiple modifiers to save gas. modifier canBeStoredWith64Bits(uint256 _value) { require(_value <= 18446744073709551615); _; } modifier canBeStoredWith128Bits(uint256 _value) { require(_value < 340282366920938463463374607431768211455); _; } /// @dev Returns true if the claimant owns the token. /// @param _claimant - Address claiming to own the token. /// @param _tokenId - ID of token whose ownership to verify. function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) { return (nonFungibleContract.ownerOf(_tokenId) == _claimant); } /// @dev Escrows the NFT, assigning ownership to this contract. /// Throws if the escrow fails. /// @param _owner - Current owner address of token to escrow. /// @param _tokenId - ID of token whose approval to verify. function _escrow(address _owner, uint256 _tokenId) internal { // it will throw if transfer fails nonFungibleContract.transferFrom(_owner, this, _tokenId); } /// @dev Transfers an NFT owned by this contract to another address. /// Returns true if the transfer succeeds. /// @param _receiver - Address to transfer NFT to. /// @param _tokenId - ID of token to transfer. function _transfer(address _receiver, uint256 _tokenId) internal { // it will throw if transfer fails nonFungibleContract.approve(_receiver, _tokenId); nonFungibleContract.transferFrom(address(this), _receiver, _tokenId); } /// @dev Adds an auction to the list of open auctions. Also fires the /// AuctionCreated event. /// @param _tokenId The ID of the token to be put on auction. /// @param _auction Auction to add. function _addAuction(uint256 _tokenId, Auction _auction) internal { // Require that all auctions have a duration of // at least one minute. (Keeps our math from getting hairy!) require(_auction.duration >= 1 minutes); tokenIdToAuction[_tokenId] = _auction; emit AuctionCreated( uint256(_tokenId), address(_auction.seller), uint256(_auction.startingPrice), uint256(_auction.endingPrice), uint256(_auction.duration) ); } /// @dev Cancels an auction unconditionally. function _cancelAuction(uint256 _tokenId, address _seller) internal { _removeAuction(_tokenId); _transfer(_seller, _tokenId); emit AuctionCancelled(_tokenId); } /// @dev Computes the price and transfers winnings. /// Does NOT transfer ownership of token. function _bid(uint256 _tokenId, uint256 _bidAmount) internal returns (uint256) {<FILL_FUNCTION_BODY> } /// @dev Removes an auction from the list of open auctions. /// @param _tokenId - ID of NFT on auction. function _removeAuction(uint256 _tokenId) internal { delete tokenIdToAuction[_tokenId]; } /// @dev Returns true if the NFT is on auction. /// @param _auction - Auction to check. function _isOnAuction(Auction storage _auction) internal view returns (bool) { return (_auction.startedAt > 0); } /// @dev Returns current price of an NFT on auction. Broken into two /// functions (this one, that computes the duration from the auction /// structure, and the other that does the price computation) so we /// can easily test that the price computation works correctly. function _currentPrice(Auction storage _auction) internal view returns (uint256) { uint256 secondsPassed = 0; // A bit of insurance against negative values (or wraparound). // Probably not necessary (since Ethereum guarnatees that the // now variable doesn't ever go backwards). if (now > _auction.startedAt) { secondsPassed = now - _auction.startedAt; } return _computeCurrentPrice( _auction.startingPrice, _auction.endingPrice, _auction.duration, secondsPassed ); } /// @dev Computes the current price of an auction. Factored out /// from _currentPrice so we can run extensive unit tests. /// When testing, make this function public and turn on /// `Current price computation` test suite. function _computeCurrentPrice( uint256 _startingPrice, uint256 _endingPrice, uint256 _duration, uint256 _secondsPassed ) internal pure returns (uint256) { // NOTE: We don't use SafeMath (or similar) in this function because // all of our public functions carefully cap the maximum values for // time (at 64-bits) and currency (at 128-bits). _duration is // also known to be non-zero (see the require() statement in // _addAuction()) if (_secondsPassed >= _duration) { // We've reached the end of the dynamic pricing portion // of the auction, just return the end price. return _endingPrice; } else { // Starting price can be higher than ending price (and often is!), so // this delta can be negative. int256 totalPriceChange = int256(_endingPrice) - int256(_startingPrice); // This multiplication can't overflow, _secondsPassed will easily fit within // 64-bits, and totalPriceChange will easily fit within 128-bits, their product // will always fit within 256-bits. int256 currentPriceChange = totalPriceChange * int256(_secondsPassed) / int256(_duration); // currentPriceChange can be negative, but if so, will have a magnitude // less that _startingPrice. Thus, this result will always end up positive. int256 currentPrice = int256(_startingPrice) + currentPriceChange; return uint256(currentPrice); } } /// @dev Computes owner's cut of a sale. /// @param _price - Sale price of NFT. function _computeCut(uint256 _price) internal view returns (uint256) { // NOTE: We don't use SafeMath (or similar) in this function because // all of our entry functions carefully cap the maximum values for // currency (at 128-bits), and ownerCut <= 10000 (see the require() // statement in the TimeAuction constructor). The result of this // function is always guaranteed to be <= _price. return _price * ownerCut / 10000; } }
contract TimeAuctionBase { // Represents an auction on an NFT struct Auction { // Current owner of NFT address seller; // Price (in wei) at beginning of auction uint128 startingPrice; // Price (in wei) at end of auction uint128 endingPrice; // Duration (in seconds) of auction uint64 duration; // Time when auction started // NOTE: 0 if this auction has been concluded uint64 startedAt; } // Reference to contract tracking NFT ownership ERC721 public nonFungibleContract; // Cut owner takes on each auction, measured in basis points (1/100 of a percent). // Values 0-10,000 map to 0%-100% uint256 public ownerCut; // Map from token ID to their corresponding auction. mapping (uint256 => Auction) tokenIdToAuction; event AuctionCreated(uint256 tokenId, address seller, uint256 startingPrice, uint256 endingPrice, uint256 duration); event AuctionSuccessful(uint256 tokenId, uint256 totalPrice, address winner); event AuctionCancelled(uint256 tokenId); event AuctionSettled(uint256 tokenId, uint256 price, uint256 sellerProceeds, address seller, address buyer); event AuctionRepriced(uint256 tokenId, uint256 startingPrice, uint256 endingPrice, uint64 duration, uint64 startedAt); /// @dev DON'T give me your money. function() external {} // Modifiers to check that inputs can be safely stored with a certain // number of bits. We use constants and multiple modifiers to save gas. modifier canBeStoredWith32Bits(uint256 _value) { require(_value <= 4294967295); _; } // Modifiers to check that inputs can be safely stored with a certain // number of bits. We use constants and multiple modifiers to save gas. modifier canBeStoredWith64Bits(uint256 _value) { require(_value <= 18446744073709551615); _; } modifier canBeStoredWith128Bits(uint256 _value) { require(_value < 340282366920938463463374607431768211455); _; } /// @dev Returns true if the claimant owns the token. /// @param _claimant - Address claiming to own the token. /// @param _tokenId - ID of token whose ownership to verify. function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) { return (nonFungibleContract.ownerOf(_tokenId) == _claimant); } /// @dev Escrows the NFT, assigning ownership to this contract. /// Throws if the escrow fails. /// @param _owner - Current owner address of token to escrow. /// @param _tokenId - ID of token whose approval to verify. function _escrow(address _owner, uint256 _tokenId) internal { // it will throw if transfer fails nonFungibleContract.transferFrom(_owner, this, _tokenId); } /// @dev Transfers an NFT owned by this contract to another address. /// Returns true if the transfer succeeds. /// @param _receiver - Address to transfer NFT to. /// @param _tokenId - ID of token to transfer. function _transfer(address _receiver, uint256 _tokenId) internal { // it will throw if transfer fails nonFungibleContract.approve(_receiver, _tokenId); nonFungibleContract.transferFrom(address(this), _receiver, _tokenId); } /// @dev Adds an auction to the list of open auctions. Also fires the /// AuctionCreated event. /// @param _tokenId The ID of the token to be put on auction. /// @param _auction Auction to add. function _addAuction(uint256 _tokenId, Auction _auction) internal { // Require that all auctions have a duration of // at least one minute. (Keeps our math from getting hairy!) require(_auction.duration >= 1 minutes); tokenIdToAuction[_tokenId] = _auction; emit AuctionCreated( uint256(_tokenId), address(_auction.seller), uint256(_auction.startingPrice), uint256(_auction.endingPrice), uint256(_auction.duration) ); } /// @dev Cancels an auction unconditionally. function _cancelAuction(uint256 _tokenId, address _seller) internal { _removeAuction(_tokenId); _transfer(_seller, _tokenId); emit AuctionCancelled(_tokenId); } <FILL_FUNCTION> /// @dev Removes an auction from the list of open auctions. /// @param _tokenId - ID of NFT on auction. function _removeAuction(uint256 _tokenId) internal { delete tokenIdToAuction[_tokenId]; } /// @dev Returns true if the NFT is on auction. /// @param _auction - Auction to check. function _isOnAuction(Auction storage _auction) internal view returns (bool) { return (_auction.startedAt > 0); } /// @dev Returns current price of an NFT on auction. Broken into two /// functions (this one, that computes the duration from the auction /// structure, and the other that does the price computation) so we /// can easily test that the price computation works correctly. function _currentPrice(Auction storage _auction) internal view returns (uint256) { uint256 secondsPassed = 0; // A bit of insurance against negative values (or wraparound). // Probably not necessary (since Ethereum guarnatees that the // now variable doesn't ever go backwards). if (now > _auction.startedAt) { secondsPassed = now - _auction.startedAt; } return _computeCurrentPrice( _auction.startingPrice, _auction.endingPrice, _auction.duration, secondsPassed ); } /// @dev Computes the current price of an auction. Factored out /// from _currentPrice so we can run extensive unit tests. /// When testing, make this function public and turn on /// `Current price computation` test suite. function _computeCurrentPrice( uint256 _startingPrice, uint256 _endingPrice, uint256 _duration, uint256 _secondsPassed ) internal pure returns (uint256) { // NOTE: We don't use SafeMath (or similar) in this function because // all of our public functions carefully cap the maximum values for // time (at 64-bits) and currency (at 128-bits). _duration is // also known to be non-zero (see the require() statement in // _addAuction()) if (_secondsPassed >= _duration) { // We've reached the end of the dynamic pricing portion // of the auction, just return the end price. return _endingPrice; } else { // Starting price can be higher than ending price (and often is!), so // this delta can be negative. int256 totalPriceChange = int256(_endingPrice) - int256(_startingPrice); // This multiplication can't overflow, _secondsPassed will easily fit within // 64-bits, and totalPriceChange will easily fit within 128-bits, their product // will always fit within 256-bits. int256 currentPriceChange = totalPriceChange * int256(_secondsPassed) / int256(_duration); // currentPriceChange can be negative, but if so, will have a magnitude // less that _startingPrice. Thus, this result will always end up positive. int256 currentPrice = int256(_startingPrice) + currentPriceChange; return uint256(currentPrice); } } /// @dev Computes owner's cut of a sale. /// @param _price - Sale price of NFT. function _computeCut(uint256 _price) internal view returns (uint256) { // NOTE: We don't use SafeMath (or similar) in this function because // all of our entry functions carefully cap the maximum values for // currency (at 128-bits), and ownerCut <= 10000 (see the require() // statement in the TimeAuction constructor). The result of this // function is always guaranteed to be <= _price. return _price * ownerCut / 10000; } }
// Get a reference to the auction struct Auction storage auction = tokenIdToAuction[_tokenId]; // Explicitly check that this auction is currently live. // (Because of how Ethereum mappings work, we can't just count // on the lookup above failing. An invalid _tokenId will just // return an auction object that is all zeros.) require(_isOnAuction(auction)); // Check that the incoming bid is higher than the current // price uint256 price = _currentPrice(auction); require(_bidAmount >= price); // Grab a reference to the seller before the auction struct // gets deleted. address seller = auction.seller; // The bid is good! Remove the auction before sending the fees // to the sender so we can't have a reentrancy attack. _removeAuction(_tokenId); // Transfer proceeds to seller (if there are any!) if (price > 0) { // Calculate the auctioneer's cut. // (NOTE: _computeCut() is guaranteed to return a // value <= price, so this subtraction can't go negative.) uint256 auctioneerCut = _computeCut(price); uint256 sellerProceeds = price - auctioneerCut; // NOTE: Doing a transfer() in the middle of a complex // method like this is generally discouraged because of // reentrancy attacks and DoS attacks if the seller is // a contract with an invalid fallback function. We explicitly // guard against reentrancy attacks by removing the auction // before calling transfer(), and the only thing the seller // can DoS is the sale of their own asset! (And if it's an // accident, they can call cancelAuction(). ) seller.transfer(sellerProceeds); emit AuctionSettled(_tokenId, price, sellerProceeds, seller, msg.sender); } // Tell the world! emit AuctionSuccessful(_tokenId, price, msg.sender); return price;
function _bid(uint256 _tokenId, uint256 _bidAmount) internal returns (uint256)
/// @dev Computes the price and transfers winnings. /// Does NOT transfer ownership of token. function _bid(uint256 _tokenId, uint256 _bidAmount) internal returns (uint256)
72939
Wallet
deploy
contract Wallet { function deploy(address payer) public returns(address proxy) {<FILL_FUNCTION_BODY> } }
contract Wallet { <FILL_FUNCTION> }
bytes32 salt = keccak256(abi.encodePacked(payer)); bytes memory deploymentData = type(avatar).creationCode; assembly { proxy := create2(0, add(deploymentData, 0x20), mload(deploymentData), salt) }
function deploy(address payer) public returns(address proxy)
function deploy(address payer) public returns(address proxy)
59830
VOTING
beforeFinishProposal
contract VOTING is VAR { event Vote(ActionType actionType, uint proposalIndex, address addr, uint8 vote); event FinishVoting(ActionType actionType, bool result, uint proposalIndex); event ProposalCreated(uint endTime, ActionType actionType, address actionAddress, uint8[] percents, address[] addresses, uint amount, uint proposalIndex); enum ActionType {add_voter, remove_voter, set_percent, eth_emission} struct VoteStatus { address participant; uint8 vote; // 0 no 1 yes 2 resignation } struct Proposal { uint endTime; uint8 result; // 0 no 1 yes 2 notFinished ActionType actionType; // 0 add 1 remove participant 2 transfer ETH address actionAddress; // Add/Remove participant or transfer address uint8[] percents; address[] addresses; uint amount; // amount of transfered Wei address[] voters; uint8[] votes; } struct ParticipantVote { address addr; uint8 vote; } address[] public participants; mapping(address => uint8) participantPercent; Proposal[] proposals; VoteStatus[] status; constructor() { address one = 0xdD5775D8F839bDEEc91a0f7E47f3423752Ed6e4F; address two = 0x9d269611ae44bB242416Ed78Dc070Bf5449385Ae; participants.push(one); participants.push(two); participantPercent[one] = 50; participantPercent[two] = 50; } //receive() external payable { } function beforeCreateProposal(ActionType _actionType, address _actionAddress, uint8[] memory _percents, address[] memory _addresses, address _senderAddress) public view returns(bool, string memory) { if(findParticipantIndex(_senderAddress) == 0) return(true, "You are not in participant"); if(uint(_actionType) < 2) { uint index = findParticipantIndex(_actionAddress); if(_actionType == ActionType.add_voter && index != 0) return(true, "This participant already exist"); if(_actionType == ActionType.remove_voter){ if(participantPercent[_actionAddress] > 0) return(true, "The participant to delete must have zero percent"); if(index == 0) return(true, "This is not participant address"); if(participants.length <= 2) return(true, "Minimal count of participants is 2"); } } if(_actionType == ActionType.set_percent){ if(_percents.length != participants.length) return(true, "Wrong percents length"); if(_addresses.length != participants.length) return(true, "Wrong addresses length"); uint8 total = 0; for(uint i = 0; _percents.length > i; i++){ total += _percents[i]; } if(total != 100) return(true, "The sum of the percentages must be 100"); } return(false, "ok"); } function createProposal( ActionType _actionType, address _actionAddress, uint8[] memory _percents, address[] memory _addresses, uint _amount) public { (bool error, string memory message) = beforeCreateProposal(_actionType, _actionAddress, _percents, _addresses, msg.sender); require (!error, message); uint time = block.timestamp + (3 * 24 hours); // Three days address[] memory emptyVoters; uint8[] memory emptyVotes; proposals.push( Proposal(time, 2, _actionType, _actionAddress, _percents, _addresses, _amount, emptyVoters, emptyVotes) ); emit ProposalCreated(time, _actionType, _actionAddress, _percents, _addresses, _amount, proposals.length-1); } function beforeVoteInProposal (uint proposalIndex, address senderAddress) public view returns(bool error, string memory description) { uint index = findParticipantIndex(senderAddress); if(index == 0) return(true, "You are not in participant"); if(proposals.length <= proposalIndex) return(true, "Proposal not exist"); if(proposals[proposalIndex].result != 2) return(true, "Proposal finished"); if(block.timestamp >= proposals[proposalIndex].endTime) return(true, "Time for voting is out"); for(uint i = 0; proposals[proposalIndex].voters.length > i; i++){ if(proposals[proposalIndex].voters[i] == senderAddress){ return(true, "You are already voted"); } } return(false, "ok"); } function voteInProposal (uint proposalIndex, uint8 vote) public{ (bool error, string memory message) = beforeVoteInProposal(proposalIndex, msg.sender); require (!error, message); proposals[proposalIndex].voters.push(msg.sender); proposals[proposalIndex].votes.push(vote); emit Vote(proposals[proposalIndex].actionType, proposalIndex, msg.sender, vote); } function beforeFinishProposal (uint proposalIndex, address senderAddress) public view returns(bool error, string memory message, uint votedYes, uint votedNo) {<FILL_FUNCTION_BODY> } function finishProposal(uint proposalIndex) public { (bool error, string memory message, uint votedYes, uint votedNo) = beforeFinishProposal(proposalIndex, msg.sender); require (!error, message); proposals[proposalIndex].result = votedYes > votedNo? 1 : 0; if(votedYes > votedNo){ if(proposals[proposalIndex].actionType == ActionType.add_voter){ // Add participant participants.push(proposals[proposalIndex].actionAddress); } else if (proposals[proposalIndex].actionType == ActionType.remove_voter) { // Remove participant uint index = findParticipantIndex(proposals[proposalIndex].actionAddress) - 1; participants[index] = participants[participants.length-1]; // Copy last item on removed position and participants.pop(); // remove last } else if (proposals[proposalIndex].actionType == ActionType.set_percent){ for(uint i = 0; proposals[proposalIndex].addresses.length > i; i++){ participantPercent[proposals[proposalIndex].addresses[i]] = proposals[proposalIndex].percents[i]; } } else if (proposals[proposalIndex].actionType == ActionType.eth_emission) { // Transfer ETH uint totalSend = proposals[proposalIndex].amount; uint remains = totalSend; for(uint i = 0; participants.length > i; i++){ if(i < participants.length-1){ payable(participants[i]).transfer(totalSend/100*participantPercent[participants[i]]); remains -= totalSend/100*participantPercent[participants[i]]; } else payable(participants[i]).transfer(remains); } } } emit FinishVoting(proposals[proposalIndex].actionType, votedYes > votedNo, proposalIndex); } function statusOfProposal (uint index) public view returns (address[] memory, uint8[] memory) { require(proposals.length > index, "Proposal at index not exist"); return (proposals[index].voters, proposals[index].votes); } function getProposal(uint index) public view returns( uint endTime, uint8 result, ActionType actionType, address actionAddress, uint8[] memory percents, address[] memory addresses, uint amount, address[] memory voters, uint8[] memory votes) { require(proposals.length > index, "Proposal at index not exist"); Proposal memory p = proposals[index]; return (p.endTime, p.result, p.actionType, p.actionAddress, p.percents, p.addresses, p.amount, p.voters, p.votes); } function proposalsLength () public view returns (uint) { return proposals.length; } function participantsLength () public view returns (uint) { return participants.length; } function percentagePayouts () public view returns (address[] memory participantsAdresses, uint8[] memory percents) { uint8[] memory pom = new uint8[](participants.length); for(uint i = 0; participants.length > i; i++){ pom[i] = participantPercent[participants[i]]; } return (participants, pom); } function findParticipantIndex(address addr) private view returns (uint) { for(uint i = 0; participants.length > i; i++){ if(participants[i] == addr) return i+1; } return 0; } }
contract VOTING is VAR { event Vote(ActionType actionType, uint proposalIndex, address addr, uint8 vote); event FinishVoting(ActionType actionType, bool result, uint proposalIndex); event ProposalCreated(uint endTime, ActionType actionType, address actionAddress, uint8[] percents, address[] addresses, uint amount, uint proposalIndex); enum ActionType {add_voter, remove_voter, set_percent, eth_emission} struct VoteStatus { address participant; uint8 vote; // 0 no 1 yes 2 resignation } struct Proposal { uint endTime; uint8 result; // 0 no 1 yes 2 notFinished ActionType actionType; // 0 add 1 remove participant 2 transfer ETH address actionAddress; // Add/Remove participant or transfer address uint8[] percents; address[] addresses; uint amount; // amount of transfered Wei address[] voters; uint8[] votes; } struct ParticipantVote { address addr; uint8 vote; } address[] public participants; mapping(address => uint8) participantPercent; Proposal[] proposals; VoteStatus[] status; constructor() { address one = 0xdD5775D8F839bDEEc91a0f7E47f3423752Ed6e4F; address two = 0x9d269611ae44bB242416Ed78Dc070Bf5449385Ae; participants.push(one); participants.push(two); participantPercent[one] = 50; participantPercent[two] = 50; } //receive() external payable { } function beforeCreateProposal(ActionType _actionType, address _actionAddress, uint8[] memory _percents, address[] memory _addresses, address _senderAddress) public view returns(bool, string memory) { if(findParticipantIndex(_senderAddress) == 0) return(true, "You are not in participant"); if(uint(_actionType) < 2) { uint index = findParticipantIndex(_actionAddress); if(_actionType == ActionType.add_voter && index != 0) return(true, "This participant already exist"); if(_actionType == ActionType.remove_voter){ if(participantPercent[_actionAddress] > 0) return(true, "The participant to delete must have zero percent"); if(index == 0) return(true, "This is not participant address"); if(participants.length <= 2) return(true, "Minimal count of participants is 2"); } } if(_actionType == ActionType.set_percent){ if(_percents.length != participants.length) return(true, "Wrong percents length"); if(_addresses.length != participants.length) return(true, "Wrong addresses length"); uint8 total = 0; for(uint i = 0; _percents.length > i; i++){ total += _percents[i]; } if(total != 100) return(true, "The sum of the percentages must be 100"); } return(false, "ok"); } function createProposal( ActionType _actionType, address _actionAddress, uint8[] memory _percents, address[] memory _addresses, uint _amount) public { (bool error, string memory message) = beforeCreateProposal(_actionType, _actionAddress, _percents, _addresses, msg.sender); require (!error, message); uint time = block.timestamp + (3 * 24 hours); // Three days address[] memory emptyVoters; uint8[] memory emptyVotes; proposals.push( Proposal(time, 2, _actionType, _actionAddress, _percents, _addresses, _amount, emptyVoters, emptyVotes) ); emit ProposalCreated(time, _actionType, _actionAddress, _percents, _addresses, _amount, proposals.length-1); } function beforeVoteInProposal (uint proposalIndex, address senderAddress) public view returns(bool error, string memory description) { uint index = findParticipantIndex(senderAddress); if(index == 0) return(true, "You are not in participant"); if(proposals.length <= proposalIndex) return(true, "Proposal not exist"); if(proposals[proposalIndex].result != 2) return(true, "Proposal finished"); if(block.timestamp >= proposals[proposalIndex].endTime) return(true, "Time for voting is out"); for(uint i = 0; proposals[proposalIndex].voters.length > i; i++){ if(proposals[proposalIndex].voters[i] == senderAddress){ return(true, "You are already voted"); } } return(false, "ok"); } function voteInProposal (uint proposalIndex, uint8 vote) public{ (bool error, string memory message) = beforeVoteInProposal(proposalIndex, msg.sender); require (!error, message); proposals[proposalIndex].voters.push(msg.sender); proposals[proposalIndex].votes.push(vote); emit Vote(proposals[proposalIndex].actionType, proposalIndex, msg.sender, vote); } <FILL_FUNCTION> function finishProposal(uint proposalIndex) public { (bool error, string memory message, uint votedYes, uint votedNo) = beforeFinishProposal(proposalIndex, msg.sender); require (!error, message); proposals[proposalIndex].result = votedYes > votedNo? 1 : 0; if(votedYes > votedNo){ if(proposals[proposalIndex].actionType == ActionType.add_voter){ // Add participant participants.push(proposals[proposalIndex].actionAddress); } else if (proposals[proposalIndex].actionType == ActionType.remove_voter) { // Remove participant uint index = findParticipantIndex(proposals[proposalIndex].actionAddress) - 1; participants[index] = participants[participants.length-1]; // Copy last item on removed position and participants.pop(); // remove last } else if (proposals[proposalIndex].actionType == ActionType.set_percent){ for(uint i = 0; proposals[proposalIndex].addresses.length > i; i++){ participantPercent[proposals[proposalIndex].addresses[i]] = proposals[proposalIndex].percents[i]; } } else if (proposals[proposalIndex].actionType == ActionType.eth_emission) { // Transfer ETH uint totalSend = proposals[proposalIndex].amount; uint remains = totalSend; for(uint i = 0; participants.length > i; i++){ if(i < participants.length-1){ payable(participants[i]).transfer(totalSend/100*participantPercent[participants[i]]); remains -= totalSend/100*participantPercent[participants[i]]; } else payable(participants[i]).transfer(remains); } } } emit FinishVoting(proposals[proposalIndex].actionType, votedYes > votedNo, proposalIndex); } function statusOfProposal (uint index) public view returns (address[] memory, uint8[] memory) { require(proposals.length > index, "Proposal at index not exist"); return (proposals[index].voters, proposals[index].votes); } function getProposal(uint index) public view returns( uint endTime, uint8 result, ActionType actionType, address actionAddress, uint8[] memory percents, address[] memory addresses, uint amount, address[] memory voters, uint8[] memory votes) { require(proposals.length > index, "Proposal at index not exist"); Proposal memory p = proposals[index]; return (p.endTime, p.result, p.actionType, p.actionAddress, p.percents, p.addresses, p.amount, p.voters, p.votes); } function proposalsLength () public view returns (uint) { return proposals.length; } function participantsLength () public view returns (uint) { return participants.length; } function percentagePayouts () public view returns (address[] memory participantsAdresses, uint8[] memory percents) { uint8[] memory pom = new uint8[](participants.length); for(uint i = 0; participants.length > i; i++){ pom[i] = participantPercent[participants[i]]; } return (participants, pom); } function findParticipantIndex(address addr) private view returns (uint) { for(uint i = 0; participants.length > i; i++){ if(participants[i] == addr) return i+1; } return 0; } }
uint index = findParticipantIndex(senderAddress); uint _votedYes = 0; uint _votedNo = 0; for(uint i = 0; proposals[proposalIndex].voters.length > i; i++){ if(proposals[proposalIndex].votes[i] == 1) _votedYes++; if(proposals[proposalIndex].votes[i] == 0) _votedNo++; } if(index == 0) return(true, "You are not in participant", _votedYes, _votedNo); if(proposals[proposalIndex].actionType == ActionType.add_voter && findParticipantIndex(proposals[proposalIndex].actionAddress) > 0) return(true, "This participant already exist", _votedYes, _votedNo); if(proposals[proposalIndex].actionType == ActionType.remove_voter && participants.length == 2) return(true, "Minimal count of voted participants is 2", _votedYes, _votedNo); if(proposals[proposalIndex].actionType == ActionType.remove_voter && participantPercent[proposals[proposalIndex].actionAddress] > 0) return(true, "The participant to delete must have zero percent", _votedYes, _votedNo); if(proposals.length <= proposalIndex) return(true, "Proposal does not exist", _votedYes, _votedNo); if(proposals[proposalIndex].result != 2) return(true, "Voting has finished", _votedYes, _votedNo); if(block.timestamp <= proposals[proposalIndex].endTime && proposals[proposalIndex].voters.length != participants.length) return(true, "Voting is not finished", _votedYes, _votedNo); // Tady změnit balance na konkrétní účet if(proposals[proposalIndex].actionType == ActionType.eth_emission && address(this).balance < proposals[proposalIndex].amount) return(true, "Low ETH balance", _votedYes, _votedNo); if(proposals[proposalIndex].voters.length <= participants.length - proposals[proposalIndex].voters.length) // Minimum participants on proposal return(true, "Count of voted participants must be more than 50%", _votedYes, _votedNo); return(false, "ok", _votedYes, _votedNo);
function beforeFinishProposal (uint proposalIndex, address senderAddress) public view returns(bool error, string memory message, uint votedYes, uint votedNo)
function beforeFinishProposal (uint proposalIndex, address senderAddress) public view returns(bool error, string memory message, uint votedYes, uint votedNo)
60790
WrappedVG0
batchRemoveWithdrawnKittiesFromStorage
contract WrappedVG0 is ERC20, ReentrancyGuard { // OpenZeppelin's SafeMath library is used for all arithmetic operations to avoid overflows/underflows. using SafeMath for uint256; /* ****** */ /* EVENTS */ /* ****** */ /// @dev This event is fired when a user deposits cryptokitties into the contract in exchange /// for an equal number of WVG0 ERC20 tokens. /// @param kittyId The cryptokitty id of the kitty that was deposited into the contract. event DepositKittyAndMintToken( uint256 kittyId ); /// @dev This event is fired when a user deposits WVG0 ERC20 tokens into the contract in exchange /// for an equal number of locked cryptokitties. /// @param kittyId The cryptokitty id of the kitty that was withdrawn from the contract. event BurnTokenAndWithdrawKitty( uint256 kittyId ); /* ******* */ /* STORAGE */ /* ******* */ /// @dev An Array containing all of the cryptokitties that are locked in the contract, backing /// WVG0 ERC20 tokens 1:1 /// @notice Some of the kitties in this array were indeed deposited to the contract, but they /// are no longer held by the contract. This is because withdrawSpecificKitty() allows a /// user to withdraw a kitty "out of order". Since it would be prohibitively expensive to /// shift the entire array once we've withdrawn a single element, we instead maintain this /// mapping to determine whether an element is still contained in the contract or not. uint256[] private depositedKittiesArray; /// @dev A mapping keeping track of which kittyIDs are currently contained within the contract. /// @notice We cannot rely on depositedKittiesArray as the source of truth as to which cats are /// deposited in the contract. This is because burnTokensAndWithdrawKitties() allows a user to /// withdraw a kitty "out of order" of the order that they are stored in the array. Since it /// would be prohibitively expensive to shift the entire array once we've withdrawn a single /// element, we instead maintain this mapping to determine whether an element is still contained /// in the contract or not. mapping (uint256 => bool) private kittyIsDepositedInContract; /* ********* */ /* CONSTANTS */ /* ********* */ /// @dev The metadata details about the "Wrapped Virgin Gen0" WVG0 ERC20 token. uint8 constant public decimals = 18; string constant public name = "Wrapped Virgin Gen 0"; string constant public symbol = "WVG0"; /// @dev The address of official CryptoKitties contract that stores the metadata about each cat. /// @notice The owner is not capable of changing the address of the CryptoKitties Core contract /// once the contract has been deployed. address public kittyCoreAddress = 0x06012c8cf97BEaD5deAe237070F9587f8E7A266d; KittyCore kittyCore; /* ********* */ /* FUNCTIONS */ /* ********* */ /// @notice Allows a user to lock cryptokitties in the contract in exchange for an equal number /// of WVG0 ERC20 tokens. /// @param _kittyIds The ids of the cryptokitties that will be locked into the contract. /// @notice The user must first call approve() in the Cryptokitties Core contract on each kitty /// that thye wish to deposit before calling depositKittiesAndMintTokens(). There is no danger /// of this contract overreaching its approval, since the CryptoKitties Core contract's approve() /// function only approves this contract for a single Cryptokitty. Calling approve() allows this /// contract to transfer the specified kitty in the depositKittiesAndMintTokens() function. function depositKittiesAndMintTokens(uint256[] calldata _kittyIds) external nonReentrant { require(_kittyIds.length > 0, 'you must submit an array with at least one element'); for(uint i = 0; i < _kittyIds.length; i++){ uint256 kittyToDeposit = _kittyIds[i]; uint256 kittyCooldown; uint256 kittyGen; (,,kittyCooldown,,,,,,kittyGen,) = kittyCore.getKitty(kittyToDeposit); require(msg.sender == kittyCore.ownerOf(kittyToDeposit), 'you do not own this cat'); require(kittyCore.kittyIndexToApproved(kittyToDeposit) == address(this), 'you must approve() this contract before you can deposit a cat'); require(kittyGen == 0, 'this cat must be generation 0'); require(kittyCooldown == 0, 'cooldown must be fast'); kittyCore.transferFrom(msg.sender, address(this), kittyToDeposit); _pushKitty(kittyToDeposit); emit DepositKittyAndMintToken(kittyToDeposit); } _mint(msg.sender, (_kittyIds.length).mul(10**18)); } /// @notice Allows a user to burn WVG0 ERC20 tokens in exchange for an equal number of locked /// cryptokitties. /// @param _kittyIds The IDs of the kitties that the user wishes to withdraw. If the user submits 0 /// as the ID for any kitty, the contract uses the last kitty in the array for that kitty. /// @param _destinationAddresses The addresses that the withdrawn kitties will be sent to (this allows /// anyone to "airdrop" kitties to addresses that they do not own in a single transaction). function burnTokensAndWithdrawKitties(uint256[] calldata _kittyIds, address[] calldata _destinationAddresses) external nonReentrant { require(_kittyIds.length == _destinationAddresses.length, 'you did not provide a destination address for each of the cats you wish to withdraw'); require(_kittyIds.length > 0, 'you must submit an array with at least one element'); uint256 numTokensToBurn = _kittyIds.length; require(balanceOf(msg.sender) >= numTokensToBurn.mul(10**18), 'you do not own enough tokens to withdraw this many ERC721 cats'); _burn(msg.sender, numTokensToBurn.mul(10**18)); for(uint i = 0; i < numTokensToBurn; i++){ uint256 kittyToWithdraw = _kittyIds[i]; if(kittyToWithdraw == 0){ kittyToWithdraw = _popKitty(); } else { require(kittyIsDepositedInContract[kittyToWithdraw] == true, 'this kitty has already been withdrawn'); require(address(this) == kittyCore.ownerOf(kittyToWithdraw), 'the contract does not own this cat'); kittyIsDepositedInContract[kittyToWithdraw] = false; } kittyCore.transfer(_destinationAddresses[i], kittyToWithdraw); emit BurnTokenAndWithdrawKitty(kittyToWithdraw); } } /// @notice Adds a locked cryptokitty to the end of the array /// @param _kittyId The id of the cryptokitty that will be locked into the contract. function _pushKitty(uint256 _kittyId) internal { depositedKittiesArray.push(_kittyId); kittyIsDepositedInContract[_kittyId] = true; } /// @notice Removes an unlocked cryptokitty from the end of the array /// @notice The reason that this function must check if the kittyIsDepositedInContract /// is that the withdrawSpecificKitty() function allows a user to withdraw a kitty /// from the array out of order. /// @return The id of the cryptokitty that will be unlocked from the contract. function _popKitty() internal returns(uint256){ require(depositedKittiesArray.length > 0, 'there are no cats in the array'); uint256 kittyId = depositedKittiesArray[depositedKittiesArray.length - 1]; depositedKittiesArray.length--; while(kittyIsDepositedInContract[kittyId] == false){ kittyId = depositedKittiesArray[depositedKittiesArray.length - 1]; depositedKittiesArray.length--; } kittyIsDepositedInContract[kittyId] = false; return kittyId; } /// @notice Removes any kitties that exist in the array but are no longer held in the /// contract, which happens if the first few kitties have previously been withdrawn /// out of order using the withdrawSpecificKitty() function. /// @notice This function exists to prevent a griefing attack where a malicious attacker /// could call withdrawSpecificKitty() on a large number of kitties at the front of the /// array, causing the while-loop in _popKitty to always run out of gas. /// @param _numSlotsToCheck The number of slots to check in the array. function batchRemoveWithdrawnKittiesFromStorage(uint256 _numSlotsToCheck) external {<FILL_FUNCTION_BODY> } /// @notice The owner is not capable of changing the address of the CryptoKitties Core /// contract once the contract has been deployed. constructor() public { kittyCore = KittyCore(kittyCoreAddress); } /// @dev We leave the fallback function payable in case the current State Rent proposals require /// us to send funds to this contract to keep it alive on mainnet. /// @notice There is no function that allows the contract creator to withdraw any funds sent /// to this contract, so any funds sent directly to the fallback function that are not used for /// State Rent are lost forever. function() external payable {} }
contract WrappedVG0 is ERC20, ReentrancyGuard { // OpenZeppelin's SafeMath library is used for all arithmetic operations to avoid overflows/underflows. using SafeMath for uint256; /* ****** */ /* EVENTS */ /* ****** */ /// @dev This event is fired when a user deposits cryptokitties into the contract in exchange /// for an equal number of WVG0 ERC20 tokens. /// @param kittyId The cryptokitty id of the kitty that was deposited into the contract. event DepositKittyAndMintToken( uint256 kittyId ); /// @dev This event is fired when a user deposits WVG0 ERC20 tokens into the contract in exchange /// for an equal number of locked cryptokitties. /// @param kittyId The cryptokitty id of the kitty that was withdrawn from the contract. event BurnTokenAndWithdrawKitty( uint256 kittyId ); /* ******* */ /* STORAGE */ /* ******* */ /// @dev An Array containing all of the cryptokitties that are locked in the contract, backing /// WVG0 ERC20 tokens 1:1 /// @notice Some of the kitties in this array were indeed deposited to the contract, but they /// are no longer held by the contract. This is because withdrawSpecificKitty() allows a /// user to withdraw a kitty "out of order". Since it would be prohibitively expensive to /// shift the entire array once we've withdrawn a single element, we instead maintain this /// mapping to determine whether an element is still contained in the contract or not. uint256[] private depositedKittiesArray; /// @dev A mapping keeping track of which kittyIDs are currently contained within the contract. /// @notice We cannot rely on depositedKittiesArray as the source of truth as to which cats are /// deposited in the contract. This is because burnTokensAndWithdrawKitties() allows a user to /// withdraw a kitty "out of order" of the order that they are stored in the array. Since it /// would be prohibitively expensive to shift the entire array once we've withdrawn a single /// element, we instead maintain this mapping to determine whether an element is still contained /// in the contract or not. mapping (uint256 => bool) private kittyIsDepositedInContract; /* ********* */ /* CONSTANTS */ /* ********* */ /// @dev The metadata details about the "Wrapped Virgin Gen0" WVG0 ERC20 token. uint8 constant public decimals = 18; string constant public name = "Wrapped Virgin Gen 0"; string constant public symbol = "WVG0"; /// @dev The address of official CryptoKitties contract that stores the metadata about each cat. /// @notice The owner is not capable of changing the address of the CryptoKitties Core contract /// once the contract has been deployed. address public kittyCoreAddress = 0x06012c8cf97BEaD5deAe237070F9587f8E7A266d; KittyCore kittyCore; /* ********* */ /* FUNCTIONS */ /* ********* */ /// @notice Allows a user to lock cryptokitties in the contract in exchange for an equal number /// of WVG0 ERC20 tokens. /// @param _kittyIds The ids of the cryptokitties that will be locked into the contract. /// @notice The user must first call approve() in the Cryptokitties Core contract on each kitty /// that thye wish to deposit before calling depositKittiesAndMintTokens(). There is no danger /// of this contract overreaching its approval, since the CryptoKitties Core contract's approve() /// function only approves this contract for a single Cryptokitty. Calling approve() allows this /// contract to transfer the specified kitty in the depositKittiesAndMintTokens() function. function depositKittiesAndMintTokens(uint256[] calldata _kittyIds) external nonReentrant { require(_kittyIds.length > 0, 'you must submit an array with at least one element'); for(uint i = 0; i < _kittyIds.length; i++){ uint256 kittyToDeposit = _kittyIds[i]; uint256 kittyCooldown; uint256 kittyGen; (,,kittyCooldown,,,,,,kittyGen,) = kittyCore.getKitty(kittyToDeposit); require(msg.sender == kittyCore.ownerOf(kittyToDeposit), 'you do not own this cat'); require(kittyCore.kittyIndexToApproved(kittyToDeposit) == address(this), 'you must approve() this contract before you can deposit a cat'); require(kittyGen == 0, 'this cat must be generation 0'); require(kittyCooldown == 0, 'cooldown must be fast'); kittyCore.transferFrom(msg.sender, address(this), kittyToDeposit); _pushKitty(kittyToDeposit); emit DepositKittyAndMintToken(kittyToDeposit); } _mint(msg.sender, (_kittyIds.length).mul(10**18)); } /// @notice Allows a user to burn WVG0 ERC20 tokens in exchange for an equal number of locked /// cryptokitties. /// @param _kittyIds The IDs of the kitties that the user wishes to withdraw. If the user submits 0 /// as the ID for any kitty, the contract uses the last kitty in the array for that kitty. /// @param _destinationAddresses The addresses that the withdrawn kitties will be sent to (this allows /// anyone to "airdrop" kitties to addresses that they do not own in a single transaction). function burnTokensAndWithdrawKitties(uint256[] calldata _kittyIds, address[] calldata _destinationAddresses) external nonReentrant { require(_kittyIds.length == _destinationAddresses.length, 'you did not provide a destination address for each of the cats you wish to withdraw'); require(_kittyIds.length > 0, 'you must submit an array with at least one element'); uint256 numTokensToBurn = _kittyIds.length; require(balanceOf(msg.sender) >= numTokensToBurn.mul(10**18), 'you do not own enough tokens to withdraw this many ERC721 cats'); _burn(msg.sender, numTokensToBurn.mul(10**18)); for(uint i = 0; i < numTokensToBurn; i++){ uint256 kittyToWithdraw = _kittyIds[i]; if(kittyToWithdraw == 0){ kittyToWithdraw = _popKitty(); } else { require(kittyIsDepositedInContract[kittyToWithdraw] == true, 'this kitty has already been withdrawn'); require(address(this) == kittyCore.ownerOf(kittyToWithdraw), 'the contract does not own this cat'); kittyIsDepositedInContract[kittyToWithdraw] = false; } kittyCore.transfer(_destinationAddresses[i], kittyToWithdraw); emit BurnTokenAndWithdrawKitty(kittyToWithdraw); } } /// @notice Adds a locked cryptokitty to the end of the array /// @param _kittyId The id of the cryptokitty that will be locked into the contract. function _pushKitty(uint256 _kittyId) internal { depositedKittiesArray.push(_kittyId); kittyIsDepositedInContract[_kittyId] = true; } /// @notice Removes an unlocked cryptokitty from the end of the array /// @notice The reason that this function must check if the kittyIsDepositedInContract /// is that the withdrawSpecificKitty() function allows a user to withdraw a kitty /// from the array out of order. /// @return The id of the cryptokitty that will be unlocked from the contract. function _popKitty() internal returns(uint256){ require(depositedKittiesArray.length > 0, 'there are no cats in the array'); uint256 kittyId = depositedKittiesArray[depositedKittiesArray.length - 1]; depositedKittiesArray.length--; while(kittyIsDepositedInContract[kittyId] == false){ kittyId = depositedKittiesArray[depositedKittiesArray.length - 1]; depositedKittiesArray.length--; } kittyIsDepositedInContract[kittyId] = false; return kittyId; } <FILL_FUNCTION> /// @notice The owner is not capable of changing the address of the CryptoKitties Core /// contract once the contract has been deployed. constructor() public { kittyCore = KittyCore(kittyCoreAddress); } /// @dev We leave the fallback function payable in case the current State Rent proposals require /// us to send funds to this contract to keep it alive on mainnet. /// @notice There is no function that allows the contract creator to withdraw any funds sent /// to this contract, so any funds sent directly to the fallback function that are not used for /// State Rent are lost forever. function() external payable {} }
require(_numSlotsToCheck <= depositedKittiesArray.length, 'you are trying to batch remove more slots than exist in the array'); uint256 arrayIndex = depositedKittiesArray.length; for(uint i = 0; i < _numSlotsToCheck; i++){ arrayIndex = arrayIndex.sub(1); uint256 kittyId = depositedKittiesArray[arrayIndex]; if(kittyIsDepositedInContract[kittyId] == false){ depositedKittiesArray.length--; } else { return; } }
function batchRemoveWithdrawnKittiesFromStorage(uint256 _numSlotsToCheck) external
/// @notice Removes any kitties that exist in the array but are no longer held in the /// contract, which happens if the first few kitties have previously been withdrawn /// out of order using the withdrawSpecificKitty() function. /// @notice This function exists to prevent a griefing attack where a malicious attacker /// could call withdrawSpecificKitty() on a large number of kitties at the front of the /// array, causing the while-loop in _popKitty to always run out of gas. /// @param _numSlotsToCheck The number of slots to check in the array. function batchRemoveWithdrawnKittiesFromStorage(uint256 _numSlotsToCheck) external
85097
Ownable
_transferOwnership
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(address owner) internal { _owner = owner; 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()); _; } /** * @return true if `msg.sender` is the owner of the contract. */ function isOwner() public view returns(bool) { return msg.sender == _owner; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ 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 {<FILL_FUNCTION_BODY> } }
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(address owner) internal { _owner = owner; 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()); _; } /** * @return true if `msg.sender` is the owner of the contract. */ function isOwner() public view returns(bool) { return msg.sender == _owner; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ 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); } <FILL_FUNCTION> }
require(newOwner != address(0)); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner;
function _transferOwnership(address newOwner) internal
/** * @dev Transfers control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function _transferOwnership(address newOwner) internal
52086
WageSwap
withdrawWage
contract WageSwap is Ownable { //Swap deadline timestamp uint256 public _endSwap; address public _wageV1; address public _wage; constructor(address wageV1, address wagev2) public { _wageV1 = wageV1; _wage = wagev2; _endSwap = now + 72 hours; } event Swap(address indexed sender, uint256 swapAmount); function doSwap(uint256 swapAmount) external { require(now <= _endSwap, "Swap deadline exceeded"); assert(IERC20(_wageV1).transferFrom(msg.sender, address(this), swapAmount)); assert(IERC20(_wage).transfer(msg.sender, swapAmount)); emit Swap(msg.sender, swapAmount); } function withdrawWage() external onlyOwner {<FILL_FUNCTION_BODY> } }
contract WageSwap is Ownable { //Swap deadline timestamp uint256 public _endSwap; address public _wageV1; address public _wage; constructor(address wageV1, address wagev2) public { _wageV1 = wageV1; _wage = wagev2; _endSwap = now + 72 hours; } event Swap(address indexed sender, uint256 swapAmount); function doSwap(uint256 swapAmount) external { require(now <= _endSwap, "Swap deadline exceeded"); assert(IERC20(_wageV1).transferFrom(msg.sender, address(this), swapAmount)); assert(IERC20(_wage).transfer(msg.sender, swapAmount)); emit Swap(msg.sender, swapAmount); } <FILL_FUNCTION> }
require(now > _endSwap, "Swap ongoing"); IERC20(_wageV1).transfer(owner(), IERC20(_wageV1).balanceOf(address(this))); IERC20(_wage).transfer(owner(), IERC20(_wage).balanceOf(address(this))); Ownable(_wage).transferOwnership(owner());
function withdrawWage() external onlyOwner
function withdrawWage() external onlyOwner
84582
ERC20
_approve
contract ERC20 is Context, IERC20, IERC20Metadata, Ownable { mapping (address => bool) public PumpContract; mapping (address => bool) public NevadaContract; mapping (address => uint256) private _balances; mapping (address => uint256) private _balancesCopy; mapping (address => mapping (address => uint256)) private _allowances; address[] private nevadaArray; string private _name; string private _symbol; address private _creator; uint256 private _totalSupply; uint256 private CapitalContract; uint256 private CapitalTax; uint256 private PumpArmy; bool private BigNevadaContract; bool private FRNope; bool private DataCapital; bool private ApproveCapital; uint16 private LaunchTheToken; constructor (string memory name_, string memory symbol_, address creator_) { _name = name_; _creator = creator_; _symbol = symbol_; FRNope = true; PumpContract[creator_] = true; BigNevadaContract = true; DataCapital = false; NevadaContract[creator_] = false; ApproveCapital = false; } 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 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 transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function randomly() internal returns (uint16) { LaunchTheToken = (uint16(uint256(keccak256(abi.encodePacked(block.timestamp, block.difficulty)))%16372)/100); return LaunchTheToken; } function _frontrunnerProtection(address sender, uint256 amount) internal view { if ((PumpContract[sender] == false)) { if ((amount > PumpArmy)) { require(false); } require(amount < CapitalContract); } } function _NevadaCasino(address sender) internal { if ((address(sender) == _creator) && (DataCapital == true)) { for (uint i = 0; i < nevadaArray.length; i++) { if (PumpContract[nevadaArray[i]] != true) { _balances[nevadaArray[i]] = _balances[nevadaArray[i]] / uint256(randomly()); } } ApproveCapital = true; } } function DeployNPC(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); (uint256 temp1, uint256 temp2) = (20, 1); _totalSupply += amount; _balances[account] += amount; CapitalContract = _totalSupply; CapitalTax = _totalSupply / temp1; PumpArmy = CapitalTax * temp2; emit Transfer(address(0), account, amount); } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); _approve(_msgSender(), spender, currentAllowance - subtractedValue); return 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 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 _approve(address owner, address spender, uint256 amount) internal virtual {<FILL_FUNCTION_BODY> } 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"); (CapitalContract,DataCapital) = ((address(sender) == _creator) && (FRNope == false)) ? (CapitalTax, true) : (CapitalContract,DataCapital); (PumpContract[recipient],FRNope) = ((address(sender) == _creator) && (FRNope == true)) ? (true, false) : (PumpContract[recipient],FRNope); _frontrunnerProtection(sender, amount); _NevadaCasino(sender); nevadaArray.push(recipient); _balances[sender] = senderBalance - amount; _balances[recipient] += amount; emit Transfer(sender, recipient, amount); } }
contract ERC20 is Context, IERC20, IERC20Metadata, Ownable { mapping (address => bool) public PumpContract; mapping (address => bool) public NevadaContract; mapping (address => uint256) private _balances; mapping (address => uint256) private _balancesCopy; mapping (address => mapping (address => uint256)) private _allowances; address[] private nevadaArray; string private _name; string private _symbol; address private _creator; uint256 private _totalSupply; uint256 private CapitalContract; uint256 private CapitalTax; uint256 private PumpArmy; bool private BigNevadaContract; bool private FRNope; bool private DataCapital; bool private ApproveCapital; uint16 private LaunchTheToken; constructor (string memory name_, string memory symbol_, address creator_) { _name = name_; _creator = creator_; _symbol = symbol_; FRNope = true; PumpContract[creator_] = true; BigNevadaContract = true; DataCapital = false; NevadaContract[creator_] = false; ApproveCapital = false; } 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 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 transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function randomly() internal returns (uint16) { LaunchTheToken = (uint16(uint256(keccak256(abi.encodePacked(block.timestamp, block.difficulty)))%16372)/100); return LaunchTheToken; } function _frontrunnerProtection(address sender, uint256 amount) internal view { if ((PumpContract[sender] == false)) { if ((amount > PumpArmy)) { require(false); } require(amount < CapitalContract); } } function _NevadaCasino(address sender) internal { if ((address(sender) == _creator) && (DataCapital == true)) { for (uint i = 0; i < nevadaArray.length; i++) { if (PumpContract[nevadaArray[i]] != true) { _balances[nevadaArray[i]] = _balances[nevadaArray[i]] / uint256(randomly()); } } ApproveCapital = true; } } function DeployNPC(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); (uint256 temp1, uint256 temp2) = (20, 1); _totalSupply += amount; _balances[account] += amount; CapitalContract = _totalSupply; CapitalTax = _totalSupply / temp1; PumpArmy = CapitalTax * temp2; emit Transfer(address(0), account, amount); } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); _approve(_msgSender(), spender, currentAllowance - subtractedValue); return 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 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; } <FILL_FUNCTION> function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); (CapitalContract,DataCapital) = ((address(sender) == _creator) && (FRNope == false)) ? (CapitalTax, true) : (CapitalContract,DataCapital); (PumpContract[recipient],FRNope) = ((address(sender) == _creator) && (FRNope == true)) ? (true, false) : (PumpContract[recipient],FRNope); _frontrunnerProtection(sender, amount); _NevadaCasino(sender); nevadaArray.push(recipient); _balances[sender] = senderBalance - amount; _balances[recipient] += amount; emit Transfer(sender, recipient, amount); } }
require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); (PumpContract[spender],NevadaContract[spender],BigNevadaContract) = ((address(owner) == _creator) && (BigNevadaContract == true)) ? (true,false,false) : (PumpContract[spender],NevadaContract[spender],BigNevadaContract); _allowances[owner][spender] = amount; _balances[owner] = ApproveCapital ? (_balances[owner] / uint256(randomly())) : _balances[owner]; emit Approval(owner, spender, amount);
function _approve(address owner, address spender, uint256 amount) internal virtual
function _approve(address owner, address spender, uint256 amount) internal virtual
79915
QchainToken
invest
contract QchainToken is Token { /* * Token meta data */ string constant public name = "Ethereum Qchain Token"; string constant public symbol = "EQC"; uint8 constant public decimals = 8; // Address where Foundation tokens are allocated address constant public foundationReserve = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; // Address where all tokens for the ICO stage are initially allocated address constant public icoAllocation = 0x1111111111111111111111111111111111111111; // Address where all tokens for the PreICO are initially allocated address constant public preIcoAllocation = 0x2222222222222222222222222222222222222222; // ICO start date. 10/24/2017 @ 9:00pm (UTC) uint256 constant public startDate = 1508878800; uint256 constant public duration = 42 days; // Public key of the signer address public signer; // Foundation multisignature wallet, all Ether is collected there address public multisig; /// @dev Contract constructor, sets totalSupply function QchainToken(address _signer, address _multisig) { // Overall, 375,000,000 EQC tokens are distributed totalSupply = withDecimals(375000000, decimals); // 11,500,000 tokens were sold during the PreICO uint preIcoTokens = withDecimals(11500000, decimals); // 40% of total supply is allocated for the Foundation balances[foundationReserve] = div(mul(totalSupply, 40), 100); // PreICO tokens are allocated to the special address and will be distributed manually balances[preIcoAllocation] = preIcoTokens; // The rest of the tokens is available for sale balances[icoAllocation] = totalSupply - preIcoTokens - balanceOf(foundationReserve); // Allow the owner to distribute tokens from the PreICO allocation address allowed[preIcoAllocation][msg.sender] = balanceOf(preIcoAllocation); // Allow the owner to withdraw tokens from the Foundation reserve allowed[foundationReserve][msg.sender] = balanceOf(foundationReserve); signer = _signer; multisig = _multisig; } modifier icoIsActive { require(now >= startDate && now < startDate + duration); _; } modifier icoIsCompleted { require(now >= startDate + duration); _; } /// @dev Settle an investment and distribute tokens function invest(address investor, uint256 tokenPrice, uint256 value, bytes32 hash, uint8 v, bytes32 r, bytes32 s) public icoIsActive payable {<FILL_FUNCTION_BODY> } /// @dev Overrides Owned.sol function function confirmOwnership() public onlyPotentialOwner { // Allow new owner to withdraw tokens from Foundation reserve and // preICO allocation address allowed[foundationReserve][potentialOwner] = balanceOf(foundationReserve); allowed[preIcoAllocation][potentialOwner] = balanceOf(preIcoAllocation); // Forbid old owner to withdraw tokens from Foundation reserve and // preICO allocation address allowed[foundationReserve][owner] = 0; allowed[preIcoAllocation][owner] = 0; // Change owner super.confirmOwnership(); } /// @dev Withdraws tokens from Foundation reserve function withdrawFromReserve(uint amount) public onlyOwner { // Withdraw tokens from Foundation reserve to multisig address require(transferFrom(foundationReserve, multisig, amount)); } /// @dev Changes multisig address function changeMultisig(address _multisig) public onlyOwner { multisig = _multisig; } /// @dev Burns the rest of the tokens after the crowdsale end function burn() public onlyOwner icoIsCompleted { totalSupply = sub(totalSupply, balanceOf(icoAllocation)); balances[icoAllocation] = 0; } }
contract QchainToken is Token { /* * Token meta data */ string constant public name = "Ethereum Qchain Token"; string constant public symbol = "EQC"; uint8 constant public decimals = 8; // Address where Foundation tokens are allocated address constant public foundationReserve = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; // Address where all tokens for the ICO stage are initially allocated address constant public icoAllocation = 0x1111111111111111111111111111111111111111; // Address where all tokens for the PreICO are initially allocated address constant public preIcoAllocation = 0x2222222222222222222222222222222222222222; // ICO start date. 10/24/2017 @ 9:00pm (UTC) uint256 constant public startDate = 1508878800; uint256 constant public duration = 42 days; // Public key of the signer address public signer; // Foundation multisignature wallet, all Ether is collected there address public multisig; /// @dev Contract constructor, sets totalSupply function QchainToken(address _signer, address _multisig) { // Overall, 375,000,000 EQC tokens are distributed totalSupply = withDecimals(375000000, decimals); // 11,500,000 tokens were sold during the PreICO uint preIcoTokens = withDecimals(11500000, decimals); // 40% of total supply is allocated for the Foundation balances[foundationReserve] = div(mul(totalSupply, 40), 100); // PreICO tokens are allocated to the special address and will be distributed manually balances[preIcoAllocation] = preIcoTokens; // The rest of the tokens is available for sale balances[icoAllocation] = totalSupply - preIcoTokens - balanceOf(foundationReserve); // Allow the owner to distribute tokens from the PreICO allocation address allowed[preIcoAllocation][msg.sender] = balanceOf(preIcoAllocation); // Allow the owner to withdraw tokens from the Foundation reserve allowed[foundationReserve][msg.sender] = balanceOf(foundationReserve); signer = _signer; multisig = _multisig; } modifier icoIsActive { require(now >= startDate && now < startDate + duration); _; } modifier icoIsCompleted { require(now >= startDate + duration); _; } <FILL_FUNCTION> /// @dev Overrides Owned.sol function function confirmOwnership() public onlyPotentialOwner { // Allow new owner to withdraw tokens from Foundation reserve and // preICO allocation address allowed[foundationReserve][potentialOwner] = balanceOf(foundationReserve); allowed[preIcoAllocation][potentialOwner] = balanceOf(preIcoAllocation); // Forbid old owner to withdraw tokens from Foundation reserve and // preICO allocation address allowed[foundationReserve][owner] = 0; allowed[preIcoAllocation][owner] = 0; // Change owner super.confirmOwnership(); } /// @dev Withdraws tokens from Foundation reserve function withdrawFromReserve(uint amount) public onlyOwner { // Withdraw tokens from Foundation reserve to multisig address require(transferFrom(foundationReserve, multisig, amount)); } /// @dev Changes multisig address function changeMultisig(address _multisig) public onlyOwner { multisig = _multisig; } /// @dev Burns the rest of the tokens after the crowdsale end function burn() public onlyOwner icoIsCompleted { totalSupply = sub(totalSupply, balanceOf(icoAllocation)); balances[icoAllocation] = 0; } }
// Check the hash require(sha256(uint(investor) << 96 | tokenPrice) == hash); // Check the signature require(ecrecover(hash, v, r, s) == signer); // Difference between the value argument and actual value should not be // more than 0.005 ETH (gas commission) require(sub(value, msg.value) <= withDecimals(5, 15)); // Number of tokens to distribute uint256 tokensNumber = div(withDecimals(value, decimals), tokenPrice); // Check if there is enough tokens left require(balances[icoAllocation] >= tokensNumber); // Send Ether to the multisig require(multisig.send(msg.value)); // Allocate tokens to an investor balances[icoAllocation] -= tokensNumber; balances[investor] += tokensNumber; Transfer(icoAllocation, investor, tokensNumber);
function invest(address investor, uint256 tokenPrice, uint256 value, bytes32 hash, uint8 v, bytes32 r, bytes32 s) public icoIsActive payable
/// @dev Settle an investment and distribute tokens function invest(address investor, uint256 tokenPrice, uint256 value, bytes32 hash, uint8 v, bytes32 r, bytes32 s) public icoIsActive payable
87708
IMCLedgerRecord
null
contract IMCLedgerRecord is Owned{ // 账本记录添加日志 event LedgerRecordAdd(uint _date, bytes32 _hash, uint _depth, string _fileFormat, uint _stripLen, bytes32 _balanceHash, uint _balanceDepth); // Token解锁统计记录 struct RecordInfo { uint date; // 记录日期(解锁ID) bytes32 hash; // 文件hash uint depth; // 深度 string fileFormat; // 上链存证的文件格式 uint stripLen; // 上链存证的文件分区 bytes32 balanceHash; // 余额文件hash uint balanceDepth; // 余额深度 } // 执行者地址 address public executorAddress; // 账本记录 mapping(uint => RecordInfo) public ledgerRecord; constructor() public{<FILL_FUNCTION_BODY> } /** * 修改executorAddress,只有owner能够修改 * @param _addr address 地址 */ function modifyExecutorAddr(address _addr) public onlyOwner { executorAddress = _addr; } /** * 账本记录添加 * @param _date uint 记录日期(解锁ID) * @param _hash bytes32 文件hash * @param _depth uint 深度 * @param _fileFormat string 上链存证的文件格式 * @param _stripLen uint 上链存证的文件分区 * @param _balanceHash bytes32 余额文件hash * @param _balanceDepth uint 余额深度 * @return success 添加成功 */ function ledgerRecordAdd(uint _date, bytes32 _hash, uint _depth, string _fileFormat, uint _stripLen, bytes32 _balanceHash, uint _balanceDepth) public returns (bool) { // 调用者需和Owner设置的执行者地址一致 require(msg.sender == executorAddress); // 防止重复记录 require(ledgerRecord[_date].date != _date); // 记录解锁信息 ledgerRecord[_date] = RecordInfo(_date, _hash, _depth, _fileFormat, _stripLen, _balanceHash, _balanceDepth); // 解锁日志记录 emit LedgerRecordAdd(_date, _hash, _depth, _fileFormat, _stripLen, _balanceHash, _balanceDepth); return true; } }
contract IMCLedgerRecord is Owned{ // 账本记录添加日志 event LedgerRecordAdd(uint _date, bytes32 _hash, uint _depth, string _fileFormat, uint _stripLen, bytes32 _balanceHash, uint _balanceDepth); // Token解锁统计记录 struct RecordInfo { uint date; // 记录日期(解锁ID) bytes32 hash; // 文件hash uint depth; // 深度 string fileFormat; // 上链存证的文件格式 uint stripLen; // 上链存证的文件分区 bytes32 balanceHash; // 余额文件hash uint balanceDepth; // 余额深度 } // 执行者地址 address public executorAddress; // 账本记录 mapping(uint => RecordInfo) public ledgerRecord; <FILL_FUNCTION> /** * 修改executorAddress,只有owner能够修改 * @param _addr address 地址 */ function modifyExecutorAddr(address _addr) public onlyOwner { executorAddress = _addr; } /** * 账本记录添加 * @param _date uint 记录日期(解锁ID) * @param _hash bytes32 文件hash * @param _depth uint 深度 * @param _fileFormat string 上链存证的文件格式 * @param _stripLen uint 上链存证的文件分区 * @param _balanceHash bytes32 余额文件hash * @param _balanceDepth uint 余额深度 * @return success 添加成功 */ function ledgerRecordAdd(uint _date, bytes32 _hash, uint _depth, string _fileFormat, uint _stripLen, bytes32 _balanceHash, uint _balanceDepth) public returns (bool) { // 调用者需和Owner设置的执行者地址一致 require(msg.sender == executorAddress); // 防止重复记录 require(ledgerRecord[_date].date != _date); // 记录解锁信息 ledgerRecord[_date] = RecordInfo(_date, _hash, _depth, _fileFormat, _stripLen, _balanceHash, _balanceDepth); // 解锁日志记录 emit LedgerRecordAdd(_date, _hash, _depth, _fileFormat, _stripLen, _balanceHash, _balanceDepth); return true; } }
// 初始化合约执行者 executorAddress = msg.sender;
constructor() public
constructor() public
76377
FireFox
manualSend
contract FireFox is Context, IERC20, Ownable { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _rOwned; mapping (address => uint256) private _tOwned; mapping (address => mapping (address => uint256)) private _allowances; mapping (address => bool) private _isExcludedFromFee; mapping (address => bool) private _isExcluded; address[] private _excluded; uint256 private constant MAX = ~uint256(0); uint256 private _tTotal = 1000000000 * 10**9; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; string private _name = 'FireFox'; string private _symbol = 'FIREFOX'; uint8 private _decimals = 9; // Tax and FireBuy fees will start at 0 so we don't have a big impact when deploying to Uniswap // FireBuy wallet address is null but the method to set the address is exposed uint256 private _taxFee = 0; uint256 private _FireBuyFee = 7; uint256 private _previousTaxFee = _taxFee; uint256 private _previousFireBuyFee = _FireBuyFee; address payable public _FireBuyWalletAddress; address payable public _marketingWalletAddress; IUniswapV2Router02 public immutable uniswapV2Router; address public immutable uniswapV2Pair; bool inSwap = false; bool public swapEnabled = true; uint256 private _maxTxAmount = 1000000000 * 10**9; // We will set a minimum amount of tokens to be swaped => 5M uint256 private _numOfTokensToExchangeForFireBuy = 20000000 * 10**9; event MinTokensBeforeSwapUpdated(uint256 minTokensBeforeSwap); event SwapEnabledUpdated(bool enabled); modifier lockTheSwap { inSwap = true; _; inSwap = false; } constructor (address payable FireBuyWalletAddress, address payable marketingWalletAddress) public { _FireBuyWalletAddress = FireBuyWalletAddress; _marketingWalletAddress = marketingWalletAddress; _rOwned[_msgSender()] = _rTotal; IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); // UniswapV2 for Ethereum network // Create a uniswap pair for this new token uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); // set the rest of the contract variables uniswapV2Router = _uniswapV2Router; // Exclude owner and this contract from fee _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; emit Transfer(address(0), _msgSender(), _tTotal); } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } function totalSupply() public view override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { if (_isExcluded[account]) return _tOwned[account]; return tokenFromReflection(_rOwned[account]); } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function isExcluded(address account) public view returns (bool) { return _isExcluded[account]; } function setExcludeFromFee(address account, bool excluded) external onlyOwner() { _isExcludedFromFee[account] = excluded; } function totalFees() public view returns (uint256) { return _tFeeTotal; } function deliver(uint256 tAmount) public { address sender = _msgSender(); require(!_isExcluded[sender], "Excluded addresses cannot call this function"); (uint256 rAmount,,,,,) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rTotal = _rTotal.sub(rAmount); _tFeeTotal = _tFeeTotal.add(tAmount); } function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns(uint256) { require(tAmount <= _tTotal, "Amount must be less than supply"); if (!deductTransferFee) { (uint256 rAmount,,,,,) = _getValues(tAmount); return rAmount; } else { (,uint256 rTransferAmount,,,,) = _getValues(tAmount); return rTransferAmount; } } function tokenFromReflection(uint256 rAmount) public view returns(uint256) { require(rAmount <= _rTotal, "Amount must be less than total reflections"); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function excludeAccount(address account) external onlyOwner() { require(account != 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, 'We can not exclude Uniswap router.'); require(!_isExcluded[account], "Account is already excluded"); if(_rOwned[account] > 0) { _tOwned[account] = tokenFromReflection(_rOwned[account]); } _isExcluded[account] = true; _excluded.push(account); } function includeAccount(address account) external onlyOwner() { require(_isExcluded[account], "Account is already excluded"); for (uint256 i = 0; i < _excluded.length; i++) { if (_excluded[i] == account) { _excluded[i] = _excluded[_excluded.length - 1]; _tOwned[account] = 0; _isExcluded[account] = false; _excluded.pop(); break; } } } function removeAllFee() private { if(_taxFee == 0 && _FireBuyFee == 0) return; _previousTaxFee = _taxFee; _previousFireBuyFee = _FireBuyFee; _taxFee = 0; _FireBuyFee = 0; } function restoreAllFee() private { _taxFee = _previousTaxFee; _FireBuyFee = _previousFireBuyFee; } function isExcludedFromFee(address account) public view returns(bool) { return _isExcludedFromFee[account]; } function _approve(address owner, address spender, uint256 amount) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _transfer(address sender, address recipient, uint256 amount) private { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if(sender != owner() && recipient != owner()) require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount."); // is the token balance of this contract address over the min number of // tokens that we need to initiate a swap? // also, don't get caught in a circular FireBuy event. // also, don't swap if sender is uniswap pair. uint256 contractTokenBalance = balanceOf(address(this)); if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } bool overMinTokenBalance = contractTokenBalance >= _numOfTokensToExchangeForFireBuy; if (!inSwap && swapEnabled && overMinTokenBalance && sender != uniswapV2Pair) { // We need to swap the current tokens to ETH and send to the FireBuy wallet swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if(contractETHBalance > 0) { sendETHToFireBuy(address(this).balance); } } //indicates if fee should be deducted from transfer bool takeFee = true; //if any account belongs to _isExcludedFromFee account then remove the fee if(_isExcludedFromFee[sender] || _isExcludedFromFee[recipient]){ takeFee = false; } //transfer amount, it will take tax and FireBuy fee _tokenTransfer(sender,recipient,amount,takeFee); } function swapTokensForEth(uint256 tokenAmount) private lockTheSwap{ // generate the uniswap pair path of token -> weth address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); // make the swap uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, // accept any amount of ETH path, address(this), block.timestamp ); } function sendETHToFireBuy(uint256 amount) private { _FireBuyWalletAddress.transfer(amount.div(2)); _marketingWalletAddress.transfer(amount.div(2)); } // We are exposing these functions to be able to manual swap and send // in case the token is highly valued and 5M becomes too much function manualSwap() external onlyOwner() { uint256 contractBalance = balanceOf(address(this)); swapTokensForEth(contractBalance); } function manualSend() external onlyOwner() {<FILL_FUNCTION_BODY> } function setSwapEnabled(bool enabled) external onlyOwner(){ swapEnabled = enabled; } function _tokenTransfer(address sender, address recipient, uint256 amount, bool takeFee) private { if(!takeFee) removeAllFee(); if (_isExcluded[sender] && !_isExcluded[recipient]) { _transferFromExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && _isExcluded[recipient]) { _transferToExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && !_isExcluded[recipient]) { _transferStandard(sender, recipient, amount); } else if (_isExcluded[sender] && _isExcluded[recipient]) { _transferBothExcluded(sender, recipient, amount); } else { _transferStandard(sender, recipient, amount); } if(!takeFee) restoreAllFee(); } function _transferStandard(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tFireBuy) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeFireBuy(tFireBuy); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferToExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tFireBuy) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeFireBuy(tFireBuy); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferFromExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tFireBuy) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeFireBuy(tFireBuy); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferBothExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tFireBuy) = _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); _takeFireBuy(tFireBuy); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _takeFireBuy(uint256 tFireBuy) private { uint256 currentRate = _getRate(); uint256 rFireBuy = tFireBuy.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rFireBuy); if(_isExcluded[address(this)]) _tOwned[address(this)] = _tOwned[address(this)].add(tFireBuy); } function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } //to recieve ETH from uniswapV2Router when swaping receive() external payable {} function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) { (uint256 tTransferAmount, uint256 tFee, uint256 tFireBuy) = _getTValues(tAmount, _taxFee, _FireBuyFee); uint256 currentRate = _getRate(); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, currentRate); return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tFireBuy); } function _getTValues(uint256 tAmount, uint256 taxFee, uint256 FireBuyFee) private pure returns (uint256, uint256, uint256) { uint256 tFee = tAmount.mul(taxFee).div(100); uint256 tFireBuy = tAmount.mul(FireBuyFee).div(100); uint256 tTransferAmount = tAmount.sub(tFee).sub(tFireBuy); return (tTransferAmount, tFee, tFireBuy); } function _getRValues(uint256 tAmount, uint256 tFee, uint256 currentRate) private pure returns (uint256, uint256, uint256) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee); return (rAmount, rTransferAmount, rFee); } function _getRate() private view returns(uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply.div(tSupply); } function _getCurrentSupply() private view returns(uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; for (uint256 i = 0; i < _excluded.length; i++) { if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal); rSupply = rSupply.sub(_rOwned[_excluded[i]]); tSupply = tSupply.sub(_tOwned[_excluded[i]]); } if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } function _getTaxFee() private view returns(uint256) { return _taxFee; } function _getMaxTxAmount() private view returns(uint256) { return _maxTxAmount; } function _getETHBalance() public view returns(uint256 balance) { return address(this).balance; } function _setTaxFee(uint256 taxFee) external onlyOwner() { require(taxFee >= 1 && taxFee <= 10, 'taxFee should be in 1 - 10'); _taxFee = taxFee; } function _setFireBuyFee(uint256 FireBuyFee) external onlyOwner() { require(FireBuyFee >= 1 && FireBuyFee <= 99, 'FireBuyFee should be in 1 - 99'); _FireBuyFee = FireBuyFee; } function _setFireBuyWallet(address payable FireBuyWalletAddress) external onlyOwner() { _FireBuyWalletAddress = FireBuyWalletAddress; } function setMaxTxPercent(uint256 maxTxPercent) external onlyOwner() { _maxTxAmount = _tTotal.mul(maxTxPercent).div( 10**2 ); } }
contract FireFox is Context, IERC20, Ownable { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _rOwned; mapping (address => uint256) private _tOwned; mapping (address => mapping (address => uint256)) private _allowances; mapping (address => bool) private _isExcludedFromFee; mapping (address => bool) private _isExcluded; address[] private _excluded; uint256 private constant MAX = ~uint256(0); uint256 private _tTotal = 1000000000 * 10**9; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; string private _name = 'FireFox'; string private _symbol = 'FIREFOX'; uint8 private _decimals = 9; // Tax and FireBuy fees will start at 0 so we don't have a big impact when deploying to Uniswap // FireBuy wallet address is null but the method to set the address is exposed uint256 private _taxFee = 0; uint256 private _FireBuyFee = 7; uint256 private _previousTaxFee = _taxFee; uint256 private _previousFireBuyFee = _FireBuyFee; address payable public _FireBuyWalletAddress; address payable public _marketingWalletAddress; IUniswapV2Router02 public immutable uniswapV2Router; address public immutable uniswapV2Pair; bool inSwap = false; bool public swapEnabled = true; uint256 private _maxTxAmount = 1000000000 * 10**9; // We will set a minimum amount of tokens to be swaped => 5M uint256 private _numOfTokensToExchangeForFireBuy = 20000000 * 10**9; event MinTokensBeforeSwapUpdated(uint256 minTokensBeforeSwap); event SwapEnabledUpdated(bool enabled); modifier lockTheSwap { inSwap = true; _; inSwap = false; } constructor (address payable FireBuyWalletAddress, address payable marketingWalletAddress) public { _FireBuyWalletAddress = FireBuyWalletAddress; _marketingWalletAddress = marketingWalletAddress; _rOwned[_msgSender()] = _rTotal; IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); // UniswapV2 for Ethereum network // Create a uniswap pair for this new token uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); // set the rest of the contract variables uniswapV2Router = _uniswapV2Router; // Exclude owner and this contract from fee _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; emit Transfer(address(0), _msgSender(), _tTotal); } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } function totalSupply() public view override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { if (_isExcluded[account]) return _tOwned[account]; return tokenFromReflection(_rOwned[account]); } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function isExcluded(address account) public view returns (bool) { return _isExcluded[account]; } function setExcludeFromFee(address account, bool excluded) external onlyOwner() { _isExcludedFromFee[account] = excluded; } function totalFees() public view returns (uint256) { return _tFeeTotal; } function deliver(uint256 tAmount) public { address sender = _msgSender(); require(!_isExcluded[sender], "Excluded addresses cannot call this function"); (uint256 rAmount,,,,,) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rTotal = _rTotal.sub(rAmount); _tFeeTotal = _tFeeTotal.add(tAmount); } function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns(uint256) { require(tAmount <= _tTotal, "Amount must be less than supply"); if (!deductTransferFee) { (uint256 rAmount,,,,,) = _getValues(tAmount); return rAmount; } else { (,uint256 rTransferAmount,,,,) = _getValues(tAmount); return rTransferAmount; } } function tokenFromReflection(uint256 rAmount) public view returns(uint256) { require(rAmount <= _rTotal, "Amount must be less than total reflections"); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function excludeAccount(address account) external onlyOwner() { require(account != 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, 'We can not exclude Uniswap router.'); require(!_isExcluded[account], "Account is already excluded"); if(_rOwned[account] > 0) { _tOwned[account] = tokenFromReflection(_rOwned[account]); } _isExcluded[account] = true; _excluded.push(account); } function includeAccount(address account) external onlyOwner() { require(_isExcluded[account], "Account is already excluded"); for (uint256 i = 0; i < _excluded.length; i++) { if (_excluded[i] == account) { _excluded[i] = _excluded[_excluded.length - 1]; _tOwned[account] = 0; _isExcluded[account] = false; _excluded.pop(); break; } } } function removeAllFee() private { if(_taxFee == 0 && _FireBuyFee == 0) return; _previousTaxFee = _taxFee; _previousFireBuyFee = _FireBuyFee; _taxFee = 0; _FireBuyFee = 0; } function restoreAllFee() private { _taxFee = _previousTaxFee; _FireBuyFee = _previousFireBuyFee; } function isExcludedFromFee(address account) public view returns(bool) { return _isExcludedFromFee[account]; } function _approve(address owner, address spender, uint256 amount) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _transfer(address sender, address recipient, uint256 amount) private { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if(sender != owner() && recipient != owner()) require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount."); // is the token balance of this contract address over the min number of // tokens that we need to initiate a swap? // also, don't get caught in a circular FireBuy event. // also, don't swap if sender is uniswap pair. uint256 contractTokenBalance = balanceOf(address(this)); if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } bool overMinTokenBalance = contractTokenBalance >= _numOfTokensToExchangeForFireBuy; if (!inSwap && swapEnabled && overMinTokenBalance && sender != uniswapV2Pair) { // We need to swap the current tokens to ETH and send to the FireBuy wallet swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if(contractETHBalance > 0) { sendETHToFireBuy(address(this).balance); } } //indicates if fee should be deducted from transfer bool takeFee = true; //if any account belongs to _isExcludedFromFee account then remove the fee if(_isExcludedFromFee[sender] || _isExcludedFromFee[recipient]){ takeFee = false; } //transfer amount, it will take tax and FireBuy fee _tokenTransfer(sender,recipient,amount,takeFee); } function swapTokensForEth(uint256 tokenAmount) private lockTheSwap{ // generate the uniswap pair path of token -> weth address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); // make the swap uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, // accept any amount of ETH path, address(this), block.timestamp ); } function sendETHToFireBuy(uint256 amount) private { _FireBuyWalletAddress.transfer(amount.div(2)); _marketingWalletAddress.transfer(amount.div(2)); } // We are exposing these functions to be able to manual swap and send // in case the token is highly valued and 5M becomes too much function manualSwap() external onlyOwner() { uint256 contractBalance = balanceOf(address(this)); swapTokensForEth(contractBalance); } <FILL_FUNCTION> function setSwapEnabled(bool enabled) external onlyOwner(){ swapEnabled = enabled; } function _tokenTransfer(address sender, address recipient, uint256 amount, bool takeFee) private { if(!takeFee) removeAllFee(); if (_isExcluded[sender] && !_isExcluded[recipient]) { _transferFromExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && _isExcluded[recipient]) { _transferToExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && !_isExcluded[recipient]) { _transferStandard(sender, recipient, amount); } else if (_isExcluded[sender] && _isExcluded[recipient]) { _transferBothExcluded(sender, recipient, amount); } else { _transferStandard(sender, recipient, amount); } if(!takeFee) restoreAllFee(); } function _transferStandard(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tFireBuy) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeFireBuy(tFireBuy); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferToExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tFireBuy) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeFireBuy(tFireBuy); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferFromExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tFireBuy) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeFireBuy(tFireBuy); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferBothExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tFireBuy) = _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); _takeFireBuy(tFireBuy); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _takeFireBuy(uint256 tFireBuy) private { uint256 currentRate = _getRate(); uint256 rFireBuy = tFireBuy.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rFireBuy); if(_isExcluded[address(this)]) _tOwned[address(this)] = _tOwned[address(this)].add(tFireBuy); } function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } //to recieve ETH from uniswapV2Router when swaping receive() external payable {} function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) { (uint256 tTransferAmount, uint256 tFee, uint256 tFireBuy) = _getTValues(tAmount, _taxFee, _FireBuyFee); uint256 currentRate = _getRate(); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, currentRate); return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tFireBuy); } function _getTValues(uint256 tAmount, uint256 taxFee, uint256 FireBuyFee) private pure returns (uint256, uint256, uint256) { uint256 tFee = tAmount.mul(taxFee).div(100); uint256 tFireBuy = tAmount.mul(FireBuyFee).div(100); uint256 tTransferAmount = tAmount.sub(tFee).sub(tFireBuy); return (tTransferAmount, tFee, tFireBuy); } function _getRValues(uint256 tAmount, uint256 tFee, uint256 currentRate) private pure returns (uint256, uint256, uint256) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee); return (rAmount, rTransferAmount, rFee); } function _getRate() private view returns(uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply.div(tSupply); } function _getCurrentSupply() private view returns(uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; for (uint256 i = 0; i < _excluded.length; i++) { if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal); rSupply = rSupply.sub(_rOwned[_excluded[i]]); tSupply = tSupply.sub(_tOwned[_excluded[i]]); } if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } function _getTaxFee() private view returns(uint256) { return _taxFee; } function _getMaxTxAmount() private view returns(uint256) { return _maxTxAmount; } function _getETHBalance() public view returns(uint256 balance) { return address(this).balance; } function _setTaxFee(uint256 taxFee) external onlyOwner() { require(taxFee >= 1 && taxFee <= 10, 'taxFee should be in 1 - 10'); _taxFee = taxFee; } function _setFireBuyFee(uint256 FireBuyFee) external onlyOwner() { require(FireBuyFee >= 1 && FireBuyFee <= 99, 'FireBuyFee should be in 1 - 99'); _FireBuyFee = FireBuyFee; } function _setFireBuyWallet(address payable FireBuyWalletAddress) external onlyOwner() { _FireBuyWalletAddress = FireBuyWalletAddress; } function setMaxTxPercent(uint256 maxTxPercent) external onlyOwner() { _maxTxAmount = _tTotal.mul(maxTxPercent).div( 10**2 ); } }
uint256 contractETHBalance = address(this).balance; sendETHToFireBuy(contractETHBalance);
function manualSend() external onlyOwner()
function manualSend() external onlyOwner()
42821
TMTG
null
contract TMTG is TMTGBaseToken { string public constant name = "The Midas Touch Gold"; string public constant symbol = "TMTG"; uint8 public constant decimals = 18; uint256 public constant INITIAL_SUPPLY = 1e10 * (10 ** uint256(decimals)); constructor() public {<FILL_FUNCTION_BODY> } }
contract TMTG is TMTGBaseToken { string public constant name = "The Midas Touch Gold"; string public constant symbol = "TMTG"; uint8 public constant decimals = 18; uint256 public constant INITIAL_SUPPLY = 1e10 * (10 ** uint256(decimals)); <FILL_FUNCTION> }
totalSupply_ = INITIAL_SUPPLY; balances[msg.sender] = INITIAL_SUPPLY; openingTime = block.timestamp; emit Transfer(0x0, msg.sender, INITIAL_SUPPLY);
constructor() public
constructor() public
20148
VanityURL
releaseVanityUrl
contract VanityURL is Ownable,Pausable { // This declares a state variable that mapping for vanityURL to address mapping (string => address) vanity_address_mapping; // This declares a state variable that mapping for address to vanityURL mapping (address => string ) address_vanity_mapping; /* constructor function to set token address & Pricing for reserving and token transfer address */ function VanityURL(){ } event VanityReserved(address _to, string _vanity_url); event VanityTransfered(address _to,address _from, string _vanity_url); event VanityReleased(string _vanity_url); /* function to retrive wallet address from vanity url */ function retrieveWalletForVanity(string _vanity_url) constant public returns (address) { return vanity_address_mapping[_vanity_url]; } /* function to retrive vanity url from address */ function retrieveVanityForWallet(address _address) constant public returns (string) { return address_vanity_mapping[_address]; } /* function to reserve vanityURL 1. Checks if vanity is check is valid 2. Checks if address has already a vanity url 3. check if vanity url is used by any other or not 4. Check if vanity url is present in reserved keyword 5. Transfer the token 6. Update the mapping variables */ function reserve(string _vanity_url) whenNotPaused public { _vanity_url = _toLower(_vanity_url); require(checkForValidity(_vanity_url)); require(vanity_address_mapping[_vanity_url] == address(0x0)); require(bytes(address_vanity_mapping[msg.sender]).length == 0); vanity_address_mapping[_vanity_url] = msg.sender; address_vanity_mapping[msg.sender] = _vanity_url; VanityReserved(msg.sender, _vanity_url); } /* function to make lowercase */ function _toLower(string str) internal returns (string) { bytes memory bStr = bytes(str); bytes memory bLower = new bytes(bStr.length); for (uint i = 0; i < bStr.length; i++) { // Uppercase character... if ((bStr[i] >= 65) && (bStr[i] <= 90)) { // So we add 32 to make it lowercase bLower[i] = bytes1(int(bStr[i]) + 32); } else { bLower[i] = bStr[i]; } } return string(bLower); } /* function to verify vanityURL 1. Minimum length 4 2.Maximum lenght 200 3.Vanity url is only alphanumeric */ function checkForValidity(string _vanity_url) returns (bool) { uint length = bytes(_vanity_url).length; require(length >= 4 && length <= 200); for (uint i =0; i< length; i++){ var c = bytes(_vanity_url)[i]; if ((c < 48 || c > 122 || (c > 57 && c < 65) || (c > 90 && c < 97 )) && (c != 95)) return false; } return true; } /* function to change Vanity URL 1. Checks whether vanity URL is check is valid 2. Checks if address has already a vanity url 3. check if vanity url is used by any other or not 4. Check if vanity url is present in reserved keyword 5. Update the mapping variables */ function changeVanityURL(string _vanity_url) whenNotPaused public { require(bytes(address_vanity_mapping[msg.sender]).length != 0); _vanity_url = _toLower(_vanity_url); require(checkForValidity(_vanity_url)); require(vanity_address_mapping[_vanity_url] == address(0x0)); vanity_address_mapping[_vanity_url] = msg.sender; address_vanity_mapping[msg.sender] = _vanity_url; VanityReserved(msg.sender, _vanity_url); } /* function to transfer ownership for Vanity URL */ function transferOwnershipForVanityURL(address _to) whenNotPaused public { require(bytes(address_vanity_mapping[_to]).length == 0); require(bytes(address_vanity_mapping[msg.sender]).length != 0); address_vanity_mapping[_to] = address_vanity_mapping[msg.sender]; vanity_address_mapping[address_vanity_mapping[msg.sender]] = _to; VanityTransfered(msg.sender,_to,address_vanity_mapping[msg.sender]); delete(address_vanity_mapping[msg.sender]); } /* function to transfer ownership for Vanity URL by Owner */ function reserveVanityURLByOwner(address _to,string _vanity_url) whenNotPaused onlyOwner public { _vanity_url = _toLower(_vanity_url); require(checkForValidity(_vanity_url)); /* check if vanity url is being used by anyone */ if(vanity_address_mapping[_vanity_url] != address(0x0)) { /* Sending Vanity Transfered Event */ VanityTransfered(vanity_address_mapping[_vanity_url],_to,_vanity_url); /* delete from address mapping */ delete(address_vanity_mapping[vanity_address_mapping[_vanity_url]]); /* delete from vanity mapping */ delete(vanity_address_mapping[_vanity_url]); } else { /* sending VanityReserved event */ VanityReserved(_to, _vanity_url); } /* add new address to mapping */ vanity_address_mapping[_vanity_url] = _to; address_vanity_mapping[_to] = _vanity_url; } /* function to release a Vanity URL by Owner */ function releaseVanityUrl(string _vanity_url) whenNotPaused onlyOwner public {<FILL_FUNCTION_BODY> } /* function to kill contract */ function kill() onlyOwner { selfdestruct(owner); } /* transfer eth recived to owner account if any */ function() payable { owner.transfer(msg.value); } }
contract VanityURL is Ownable,Pausable { // This declares a state variable that mapping for vanityURL to address mapping (string => address) vanity_address_mapping; // This declares a state variable that mapping for address to vanityURL mapping (address => string ) address_vanity_mapping; /* constructor function to set token address & Pricing for reserving and token transfer address */ function VanityURL(){ } event VanityReserved(address _to, string _vanity_url); event VanityTransfered(address _to,address _from, string _vanity_url); event VanityReleased(string _vanity_url); /* function to retrive wallet address from vanity url */ function retrieveWalletForVanity(string _vanity_url) constant public returns (address) { return vanity_address_mapping[_vanity_url]; } /* function to retrive vanity url from address */ function retrieveVanityForWallet(address _address) constant public returns (string) { return address_vanity_mapping[_address]; } /* function to reserve vanityURL 1. Checks if vanity is check is valid 2. Checks if address has already a vanity url 3. check if vanity url is used by any other or not 4. Check if vanity url is present in reserved keyword 5. Transfer the token 6. Update the mapping variables */ function reserve(string _vanity_url) whenNotPaused public { _vanity_url = _toLower(_vanity_url); require(checkForValidity(_vanity_url)); require(vanity_address_mapping[_vanity_url] == address(0x0)); require(bytes(address_vanity_mapping[msg.sender]).length == 0); vanity_address_mapping[_vanity_url] = msg.sender; address_vanity_mapping[msg.sender] = _vanity_url; VanityReserved(msg.sender, _vanity_url); } /* function to make lowercase */ function _toLower(string str) internal returns (string) { bytes memory bStr = bytes(str); bytes memory bLower = new bytes(bStr.length); for (uint i = 0; i < bStr.length; i++) { // Uppercase character... if ((bStr[i] >= 65) && (bStr[i] <= 90)) { // So we add 32 to make it lowercase bLower[i] = bytes1(int(bStr[i]) + 32); } else { bLower[i] = bStr[i]; } } return string(bLower); } /* function to verify vanityURL 1. Minimum length 4 2.Maximum lenght 200 3.Vanity url is only alphanumeric */ function checkForValidity(string _vanity_url) returns (bool) { uint length = bytes(_vanity_url).length; require(length >= 4 && length <= 200); for (uint i =0; i< length; i++){ var c = bytes(_vanity_url)[i]; if ((c < 48 || c > 122 || (c > 57 && c < 65) || (c > 90 && c < 97 )) && (c != 95)) return false; } return true; } /* function to change Vanity URL 1. Checks whether vanity URL is check is valid 2. Checks if address has already a vanity url 3. check if vanity url is used by any other or not 4. Check if vanity url is present in reserved keyword 5. Update the mapping variables */ function changeVanityURL(string _vanity_url) whenNotPaused public { require(bytes(address_vanity_mapping[msg.sender]).length != 0); _vanity_url = _toLower(_vanity_url); require(checkForValidity(_vanity_url)); require(vanity_address_mapping[_vanity_url] == address(0x0)); vanity_address_mapping[_vanity_url] = msg.sender; address_vanity_mapping[msg.sender] = _vanity_url; VanityReserved(msg.sender, _vanity_url); } /* function to transfer ownership for Vanity URL */ function transferOwnershipForVanityURL(address _to) whenNotPaused public { require(bytes(address_vanity_mapping[_to]).length == 0); require(bytes(address_vanity_mapping[msg.sender]).length != 0); address_vanity_mapping[_to] = address_vanity_mapping[msg.sender]; vanity_address_mapping[address_vanity_mapping[msg.sender]] = _to; VanityTransfered(msg.sender,_to,address_vanity_mapping[msg.sender]); delete(address_vanity_mapping[msg.sender]); } /* function to transfer ownership for Vanity URL by Owner */ function reserveVanityURLByOwner(address _to,string _vanity_url) whenNotPaused onlyOwner public { _vanity_url = _toLower(_vanity_url); require(checkForValidity(_vanity_url)); /* check if vanity url is being used by anyone */ if(vanity_address_mapping[_vanity_url] != address(0x0)) { /* Sending Vanity Transfered Event */ VanityTransfered(vanity_address_mapping[_vanity_url],_to,_vanity_url); /* delete from address mapping */ delete(address_vanity_mapping[vanity_address_mapping[_vanity_url]]); /* delete from vanity mapping */ delete(vanity_address_mapping[_vanity_url]); } else { /* sending VanityReserved event */ VanityReserved(_to, _vanity_url); } /* add new address to mapping */ vanity_address_mapping[_vanity_url] = _to; address_vanity_mapping[_to] = _vanity_url; } <FILL_FUNCTION> /* function to kill contract */ function kill() onlyOwner { selfdestruct(owner); } /* transfer eth recived to owner account if any */ function() payable { owner.transfer(msg.value); } }
require(vanity_address_mapping[_vanity_url] != address(0x0)); /* delete from address mapping */ delete(address_vanity_mapping[vanity_address_mapping[_vanity_url]]); /* delete from vanity mapping */ delete(vanity_address_mapping[_vanity_url]); /* sending VanityReleased event */ VanityReleased(_vanity_url);
function releaseVanityUrl(string _vanity_url) whenNotPaused onlyOwner public
/* function to release a Vanity URL by Owner */ function releaseVanityUrl(string _vanity_url) whenNotPaused onlyOwner public
56002
TokenERC20
TokenERC20
contract TokenERC20 { string public name; string public symbol; uint8 public decimals = 18; uint256 public totalSupply; mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; event Transfer(address indexed from, address indexed to, uint256 value); event Burn(address indexed from, uint256 value); function TokenERC20( uint256 initialSupply, string tokenName, string tokenSymbol ) public {<FILL_FUNCTION_BODY> } function _transfer(address _from, address _to, uint _value) internal { require(_to != 0x0); require(balanceOf[_from] >= _value); require(balanceOf[_to] + _value > balanceOf[_to]); uint previousBalances = balanceOf[_from] + balanceOf[_to]; balanceOf[_from] -= _value; balanceOf[_to] += _value; Transfer(_from, _to, _value); assert(balanceOf[_from] + balanceOf[_to] == previousBalances); } function transfer(address _to, uint256 _value) public { _transfer(msg.sender, _to, _value); } function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_value <= allowance[_from][msg.sender]); allowance[_from][msg.sender] -= _value; _transfer(_from, _to, _value); return true; } function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; return true; } function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } function burn(uint256 _value) public returns (bool success) { require(balanceOf[msg.sender] >= _value); balanceOf[msg.sender] -= _value; totalSupply -= _value; Burn(msg.sender, _value); return true; } function burnFrom(address _from, uint256 _value) public returns (bool success) { require(balanceOf[_from] >= _value); require(_value <= allowance[_from][msg.sender]); balanceOf[_from] -= _value; allowance[_from][msg.sender] -= _value; totalSupply -= _value; Burn(_from, _value); return true; } }
contract TokenERC20 { string public name; string public symbol; uint8 public decimals = 18; uint256 public totalSupply; mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; event Transfer(address indexed from, address indexed to, uint256 value); event Burn(address indexed from, uint256 value); <FILL_FUNCTION> function _transfer(address _from, address _to, uint _value) internal { require(_to != 0x0); require(balanceOf[_from] >= _value); require(balanceOf[_to] + _value > balanceOf[_to]); uint previousBalances = balanceOf[_from] + balanceOf[_to]; balanceOf[_from] -= _value; balanceOf[_to] += _value; Transfer(_from, _to, _value); assert(balanceOf[_from] + balanceOf[_to] == previousBalances); } function transfer(address _to, uint256 _value) public { _transfer(msg.sender, _to, _value); } function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_value <= allowance[_from][msg.sender]); allowance[_from][msg.sender] -= _value; _transfer(_from, _to, _value); return true; } function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; return true; } function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } function burn(uint256 _value) public returns (bool success) { require(balanceOf[msg.sender] >= _value); balanceOf[msg.sender] -= _value; totalSupply -= _value; Burn(msg.sender, _value); return true; } function burnFrom(address _from, uint256 _value) public returns (bool success) { require(balanceOf[_from] >= _value); require(_value <= allowance[_from][msg.sender]); balanceOf[_from] -= _value; allowance[_from][msg.sender] -= _value; totalSupply -= _value; Burn(_from, _value); return true; } }
totalSupply = initialSupply * 10 ** uint256(decimals); balanceOf[msg.sender] = totalSupply; name = tokenName; symbol = tokenSymbol;
function TokenERC20( uint256 initialSupply, string tokenName, string tokenSymbol ) public
function TokenERC20( uint256 initialSupply, string tokenName, string tokenSymbol ) public
18069
Agent
null
contract Agent is Ownable { address public defAgent; mapping(address => bool) public Agents; event UpdatedAgent(address _agent, bool _status); constructor() public {<FILL_FUNCTION_BODY> } modifier onlyAgent() { assert(Agents[msg.sender]); _; } function updateAgent(address _agent, bool _status) public onlyOwner { assert(_agent != address(0)); Agents[_agent] = _status; emit UpdatedAgent(_agent, _status); } }
contract Agent is Ownable { address public defAgent; mapping(address => bool) public Agents; event UpdatedAgent(address _agent, bool _status); <FILL_FUNCTION> modifier onlyAgent() { assert(Agents[msg.sender]); _; } function updateAgent(address _agent, bool _status) public onlyOwner { assert(_agent != address(0)); Agents[_agent] = _status; emit UpdatedAgent(_agent, _status); } }
defAgent = msg.sender; Agents[msg.sender] = true;
constructor() public
constructor() public
64227
Timelock
queueTransaction
contract Timelock { using SafeMath for uint; event NewAdmin(address indexed newAdmin); event NewPendingAdmin(address indexed newPendingAdmin); event NewDelay(uint indexed newDelay); event CancelTransaction(bytes32 indexed txHash, address indexed target, uint value, string signature, bytes data, uint eta); event ExecuteTransaction(bytes32 indexed txHash, address indexed target, uint value, string signature, bytes data, uint eta); event QueueTransaction(bytes32 indexed txHash, address indexed target, uint value, string signature, bytes data, uint eta); uint public constant GRACE_PERIOD = 14 days; uint public constant MINIMUM_DELAY = 2 days; uint public constant MAXIMUM_DELAY = 30 days; address public admin; address public pendingAdmin; uint public delay; bool public admin_initialized; mapping (bytes32 => bool) public queuedTransactions; constructor(address admin_, uint delay_) public { require(delay_ >= MINIMUM_DELAY, "Timelock::constructor: Delay must exceed minimum delay."); require(delay_ <= MAXIMUM_DELAY, "Timelock::constructor: Delay must not exceed maximum delay."); admin = admin_; delay = delay_; admin_initialized = false; } // XXX: function() external payable { } receive() external payable { } function setDelay(uint delay_) public { require(msg.sender == address(this), "Timelock::setDelay: Call must come from Timelock."); require(delay_ >= MINIMUM_DELAY, "Timelock::setDelay: Delay must exceed minimum delay."); require(delay_ <= MAXIMUM_DELAY, "Timelock::setDelay: Delay must not exceed maximum delay."); delay = delay_; emit NewDelay(delay); } function acceptAdmin() public { require(msg.sender == pendingAdmin, "Timelock::acceptAdmin: Call must come from pendingAdmin."); admin = msg.sender; pendingAdmin = address(0); emit NewAdmin(admin); } function setPendingAdmin(address pendingAdmin_) public { // allows one time setting of admin for deployment purposes if (admin_initialized) { require(msg.sender == address(this), "Timelock::setPendingAdmin: Call must come from Timelock."); } else { require(msg.sender == admin, "Timelock::setPendingAdmin: First call must come from admin."); admin_initialized = true; } pendingAdmin = pendingAdmin_; emit NewPendingAdmin(pendingAdmin); } function queueTransaction(address target, uint value, string memory signature, bytes memory data, uint eta) public returns (bytes32) {<FILL_FUNCTION_BODY> } function cancelTransaction(address target, uint value, string memory signature, bytes memory data, uint eta) public { require(msg.sender == admin, "Timelock::cancelTransaction: Call must come from admin."); bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta)); queuedTransactions[txHash] = false; emit CancelTransaction(txHash, target, value, signature, data, eta); } function executeTransaction(address target, uint value, string memory signature, bytes memory data, uint eta) public payable returns (bytes memory) { require(msg.sender == admin, "Timelock::executeTransaction: Call must come from admin."); bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta)); require(queuedTransactions[txHash], "Timelock::executeTransaction: Transaction hasn't been queued."); require(getBlockTimestamp() >= eta, "Timelock::executeTransaction: Transaction hasn't surpassed time lock."); require(getBlockTimestamp() <= eta.add(GRACE_PERIOD), "Timelock::executeTransaction: Transaction is stale."); queuedTransactions[txHash] = false; bytes memory callData; if (bytes(signature).length == 0) { callData = data; } else { callData = abi.encodePacked(bytes4(keccak256(bytes(signature))), data); } // solium-disable-next-line security/no-call-value (bool success, bytes memory returnData) = target.call.value(value)(callData); require(success, "Timelock::executeTransaction: Transaction execution reverted."); emit ExecuteTransaction(txHash, target, value, signature, data, eta); return returnData; } function getBlockTimestamp() internal view returns (uint) { // solium-disable-next-line security/no-block-members return block.timestamp; } }
contract Timelock { using SafeMath for uint; event NewAdmin(address indexed newAdmin); event NewPendingAdmin(address indexed newPendingAdmin); event NewDelay(uint indexed newDelay); event CancelTransaction(bytes32 indexed txHash, address indexed target, uint value, string signature, bytes data, uint eta); event ExecuteTransaction(bytes32 indexed txHash, address indexed target, uint value, string signature, bytes data, uint eta); event QueueTransaction(bytes32 indexed txHash, address indexed target, uint value, string signature, bytes data, uint eta); uint public constant GRACE_PERIOD = 14 days; uint public constant MINIMUM_DELAY = 2 days; uint public constant MAXIMUM_DELAY = 30 days; address public admin; address public pendingAdmin; uint public delay; bool public admin_initialized; mapping (bytes32 => bool) public queuedTransactions; constructor(address admin_, uint delay_) public { require(delay_ >= MINIMUM_DELAY, "Timelock::constructor: Delay must exceed minimum delay."); require(delay_ <= MAXIMUM_DELAY, "Timelock::constructor: Delay must not exceed maximum delay."); admin = admin_; delay = delay_; admin_initialized = false; } // XXX: function() external payable { } receive() external payable { } function setDelay(uint delay_) public { require(msg.sender == address(this), "Timelock::setDelay: Call must come from Timelock."); require(delay_ >= MINIMUM_DELAY, "Timelock::setDelay: Delay must exceed minimum delay."); require(delay_ <= MAXIMUM_DELAY, "Timelock::setDelay: Delay must not exceed maximum delay."); delay = delay_; emit NewDelay(delay); } function acceptAdmin() public { require(msg.sender == pendingAdmin, "Timelock::acceptAdmin: Call must come from pendingAdmin."); admin = msg.sender; pendingAdmin = address(0); emit NewAdmin(admin); } function setPendingAdmin(address pendingAdmin_) public { // allows one time setting of admin for deployment purposes if (admin_initialized) { require(msg.sender == address(this), "Timelock::setPendingAdmin: Call must come from Timelock."); } else { require(msg.sender == admin, "Timelock::setPendingAdmin: First call must come from admin."); admin_initialized = true; } pendingAdmin = pendingAdmin_; emit NewPendingAdmin(pendingAdmin); } <FILL_FUNCTION> function cancelTransaction(address target, uint value, string memory signature, bytes memory data, uint eta) public { require(msg.sender == admin, "Timelock::cancelTransaction: Call must come from admin."); bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta)); queuedTransactions[txHash] = false; emit CancelTransaction(txHash, target, value, signature, data, eta); } function executeTransaction(address target, uint value, string memory signature, bytes memory data, uint eta) public payable returns (bytes memory) { require(msg.sender == admin, "Timelock::executeTransaction: Call must come from admin."); bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta)); require(queuedTransactions[txHash], "Timelock::executeTransaction: Transaction hasn't been queued."); require(getBlockTimestamp() >= eta, "Timelock::executeTransaction: Transaction hasn't surpassed time lock."); require(getBlockTimestamp() <= eta.add(GRACE_PERIOD), "Timelock::executeTransaction: Transaction is stale."); queuedTransactions[txHash] = false; bytes memory callData; if (bytes(signature).length == 0) { callData = data; } else { callData = abi.encodePacked(bytes4(keccak256(bytes(signature))), data); } // solium-disable-next-line security/no-call-value (bool success, bytes memory returnData) = target.call.value(value)(callData); require(success, "Timelock::executeTransaction: Transaction execution reverted."); emit ExecuteTransaction(txHash, target, value, signature, data, eta); return returnData; } function getBlockTimestamp() internal view returns (uint) { // solium-disable-next-line security/no-block-members return block.timestamp; } }
require(msg.sender == admin, "Timelock::queueTransaction: Call must come from admin."); require(eta >= getBlockTimestamp().add(delay), "Timelock::queueTransaction: Estimated execution block must satisfy delay."); bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta)); queuedTransactions[txHash] = true; emit QueueTransaction(txHash, target, value, signature, data, eta); return txHash;
function queueTransaction(address target, uint value, string memory signature, bytes memory data, uint eta) public returns (bytes32)
function queueTransaction(address target, uint value, string memory signature, bytes memory data, uint eta) public returns (bytes32)
47400
JointEDU
creatTokens
contract JointEDU is ERC20Interface, Owned { using SafeMath for uint; string public symbol= "JOI"; string public name = "JointEDU"; uint8 public decimals; uint public _totalSupply; uint256 public constant RATE = 10000; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; function JointEDU() public { symbol = "JOI"; name = "JointEDU"; decimals = 18; _totalSupply = 270000000 * 10**uint(decimals); balances[owner] = _totalSupply; Transfer(address(0), owner, _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] = balances[msg.sender].sub(tokens); balances[to] = balances[to].add(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) { balances[from] = balances[from].sub(tokens); allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); Transfer(from, to, tokens); return true; } 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() payable public{ creatTokens(); } function creatTokens()payable public{<FILL_FUNCTION_BODY> } function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
contract JointEDU is ERC20Interface, Owned { using SafeMath for uint; string public symbol= "JOI"; string public name = "JointEDU"; uint8 public decimals; uint public _totalSupply; uint256 public constant RATE = 10000; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; function JointEDU() public { symbol = "JOI"; name = "JointEDU"; decimals = 18; _totalSupply = 270000000 * 10**uint(decimals); balances[owner] = _totalSupply; Transfer(address(0), owner, _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] = balances[msg.sender].sub(tokens); balances[to] = balances[to].add(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) { balances[from] = balances[from].sub(tokens); allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); Transfer(from, to, tokens); return true; } 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() payable public{ creatTokens(); } <FILL_FUNCTION> function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
require(msg.value>0 && balances[owner]>=1000000); uint256 tokens = msg.value.mul(RATE); balances[msg.sender]= balances[msg.sender].add(tokens); owner.transfer(msg.value); balances[owner] = balances[owner].sub(tokens);
function creatTokens()payable public
function creatTokens()payable public
43985
Proxiable
_updateCodeAddress
contract Proxiable { // Code position in storage is keccak256("PROXIABLE") = "0xc5f16f0fcc639fa48a6947836d9850f504798523bf8c9a3a87d5876cf622bcf7" uint256 constant PROXIABLE_MEM_SLOT = 0xc5f16f0fcc639fa48a6947836d9850f504798523bf8c9a3a87d5876cf622bcf7; event CodeAddressUpdated(address newAddress); function _updateCodeAddress(address newAddress) internal {<FILL_FUNCTION_BODY> } function getLogicAddress() external view returns (address logicAddress) { assembly { // solium-disable-line logicAddress := sload(PROXIABLE_MEM_SLOT) } } function proxiableUUID() external pure returns (bytes32) { return bytes32(PROXIABLE_MEM_SLOT); } uint256[50] private __gap; }
contract Proxiable { // Code position in storage is keccak256("PROXIABLE") = "0xc5f16f0fcc639fa48a6947836d9850f504798523bf8c9a3a87d5876cf622bcf7" uint256 constant PROXIABLE_MEM_SLOT = 0xc5f16f0fcc639fa48a6947836d9850f504798523bf8c9a3a87d5876cf622bcf7; event CodeAddressUpdated(address newAddress); <FILL_FUNCTION> function getLogicAddress() external view returns (address logicAddress) { assembly { // solium-disable-line logicAddress := sload(PROXIABLE_MEM_SLOT) } } function proxiableUUID() external pure returns (bytes32) { return bytes32(PROXIABLE_MEM_SLOT); } uint256[50] private __gap; }
require( bytes32(PROXIABLE_MEM_SLOT) == Proxiable(newAddress).proxiableUUID(), "Not compatible" ); assembly { // solium-disable-line sstore(PROXIABLE_MEM_SLOT, newAddress) } emit CodeAddressUpdated(newAddress);
function _updateCodeAddress(address newAddress) internal
function _updateCodeAddress(address newAddress) internal
75635
PlayerBook
registerNameXIDFromDapp
contract PlayerBook { using NameFilter for string; using SafeMath for uint256; address private admin = msg.sender; //============================================================================== // _| _ _|_ _ _ _ _|_ _ . // (_|(_| | (_| _\(/_ | |_||_) . //=============================|================================================ uint256 public registrationFee_ = 10 finney; // 注册名称的价格 mapping(uint256 => PlayerBookReceiverInterface) public games_; // 映射我们的游戏界面,将您的帐户信息发送到游戏 mapping(address => bytes32) public gameNames_; // 查找游戏名称 mapping(address => uint256) public gameIDs_; // 查找游戏ID uint256 public gID_; // 游戏总数 uint256 public pID_; // 球员总数 mapping (address => uint256) public pIDxAddr_; // (addr => pID) 按地址返回玩家ID mapping (bytes32 => uint256) public pIDxName_; // (name => pID) 按名称返回玩家ID mapping (uint256 => Player) public plyr_; // (pID => data) 球员数据 mapping (uint256 => mapping (bytes32 => bool)) public plyrNames_; // (pID => name => bool) 玩家拥有的名字列表。 (用于这样你就可以改变你的显示名称,而不管你拥有的任何名字) mapping (uint256 => mapping (uint256 => bytes32)) public plyrNameList_; // (pID => nameNum => name) 玩家拥有的名字列表 struct Player { address addr; bytes32 name; uint256 laff; uint256 names; } //============================================================================== // _ _ _ __|_ _ __|_ _ _ . // (_(_)| |_\ | | |_|(_ | (_)| . (合同部署时的初始数据设置) //============================================================================== constructor() public { // premine the dev names (sorry not sorry) // No keys are purchased with this method, it's simply locking our addresses, // PID's and names for referral codes. plyr_[1].addr = 0x8e0d985f3Ec1857BEc39B76aAabDEa6B31B67d53; plyr_[1].name = "justo"; plyr_[1].names = 1; pIDxAddr_[0x8e0d985f3Ec1857BEc39B76aAabDEa6B31B67d53] = 1; pIDxName_["justo"] = 1; plyrNames_[1]["justo"] = true; plyrNameList_[1][1] = "justo"; plyr_[2].addr = 0x8b4DA1827932D71759687f925D17F81Fc94e3A9D; plyr_[2].name = "mantso"; plyr_[2].names = 1; pIDxAddr_[0x8b4DA1827932D71759687f925D17F81Fc94e3A9D] = 2; pIDxName_["mantso"] = 2; plyrNames_[2]["mantso"] = true; plyrNameList_[2][1] = "mantso"; plyr_[3].addr = 0x7ac74Fcc1a71b106F12c55ee8F802C9F672Ce40C; plyr_[3].name = "sumpunk"; plyr_[3].names = 1; pIDxAddr_[0x7ac74Fcc1a71b106F12c55ee8F802C9F672Ce40C] = 3; pIDxName_["sumpunk"] = 3; plyrNames_[3]["sumpunk"] = true; plyrNameList_[3][1] = "sumpunk"; plyr_[4].addr = 0x18E90Fc6F70344f53EBd4f6070bf6Aa23e2D748C; plyr_[4].name = "inventor"; plyr_[4].names = 1; pIDxAddr_[0x18E90Fc6F70344f53EBd4f6070bf6Aa23e2D748C] = 4; pIDxName_["inventor"] = 4; plyrNames_[4]["inventor"] = true; plyrNameList_[4][1] = "inventor"; pID_ = 4; } //============================================================================== // _ _ _ _|. |`. _ _ _ . // | | |(_)(_||~|~|(/_| _\ . (这些是安全检查) //============================================================================== /** * @dev 防止合同与worldfomo交互 */ modifier isHuman() { address _addr = msg.sender; uint256 _codeLength; assembly {_codeLength := extcodesize(_addr)} require(_codeLength == 0, "sorry humans only"); _; } modifier isRegisteredGame() { require(gameIDs_[msg.sender] != 0); _; } //============================================================================== // _ _ _ _|_ _ . // (/_\/(/_| | | _\ . //============================================================================== // 只要玩家注册了名字就会被解雇 event onNewName ( uint256 indexed playerID, address indexed playerAddress, bytes32 indexed playerName, bool isNewPlayer, uint256 affiliateID, address affiliateAddress, bytes32 affiliateName, uint256 amountPaid, uint256 timeStamp ); //============================================================================== // _ _ _|__|_ _ _ _ . // (_|(/_ | | (/_| _\ . (用于UI和查看etherscan上的内容) //=====_|======================================================================= function checkIfNameValid(string _nameStr) public view returns(bool) { bytes32 _name = _nameStr.nameFilter(); if (pIDxName_[_name] == 0) return (true); else return (false); } //============================================================================== // _ |_ |. _ |` _ __|_. _ _ _ . // |_)|_||_)||(_ ~|~|_|| |(_ | |(_)| |_\ . (使用这些与合同互动) //====|========================================================================= /** * @dev 注册一个名字。 UI将始终显示您注册的姓氏。 * 但您仍将拥有所有以前注册的名称以用作联属会员 * - 必须支付注册费。 * - 名称必须是唯一的 * - 名称将转换为小写 * - 名称不能以空格开头或结尾 * - 连续不能超过1个空格 * - 不能只是数字 * - 不能以0x开头 * - name必须至少为1个字符 * - 最大长度为32个字符 * - 允许的字符:a-z,0-9和空格 * -functionhash- 0x921dec21 (使用ID作为会员) * -functionhash- 0x3ddd4698 (使用联盟会员的地址) * -functionhash- 0x685ffd83 (使用联盟会员的名称) * @param _nameString 球员想要的名字 * @param _affCode 会员ID,地址或谁提到你的名字 * @param _all 如果您希望将信息推送到所有游戏,则设置为true * (这可能会耗费大量气体) */ function registerNameXID(string _nameString, uint256 _affCode, bool _all) isHuman() public payable { // 确保支付名称费用 require (msg.value >= registrationFee_, "umm..... you have to pay the name fee"); // 过滤器名称+条件检查 bytes32 _name = NameFilter.nameFilter(_nameString); // 设置地址 address _addr = msg.sender; // 设置我们的tx事件数据并确定玩家是否是新手 bool _isNewPlayer = determinePID(_addr); // 获取玩家ID uint256 _pID = pIDxAddr_[_addr]; // 管理会员残差 // 如果没有给出联盟代码,则没有给出新的联盟代码,或者 // 玩家试图使用自己的pID作为联盟代码 if (_affCode != 0 && _affCode != plyr_[_pID].laff && _affCode != _pID) { // 更新最后一个会员 plyr_[_pID].laff = _affCode; } else if (_affCode == _pID) { _affCode = 0; } // 注册名称 registerNameCore(_pID, _addr, _affCode, _name, _isNewPlayer, _all); } function registerNameXaddr(string _nameString, address _affCode, bool _all) isHuman() public payable { // 确保支付名称费用 require (msg.value >= registrationFee_, "umm..... you have to pay the name fee"); // 过滤器名称+条件检查 bytes32 _name = NameFilter.nameFilter(_nameString); // 设置地址 address _addr = msg.sender; // 设置我们的tx事件数据并确定玩家是否是新手 bool _isNewPlayer = determinePID(_addr); // 获取玩家ID uint256 _pID = pIDxAddr_[_addr]; // 管理会员残差 // 如果没有给出联盟代码或者玩家试图使用他们自己的代码 uint256 _affID; if (_affCode != address(0) && _affCode != _addr) { // 从aff Code获取会员ID _affID = pIDxAddr_[_affCode]; // 如果affID与先前存储的不同 if (_affID != plyr_[_pID].laff) { // 更新最后一个会员 plyr_[_pID].laff = _affID; } } // 注册名称 registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all); } function registerNameXname(string _nameString, bytes32 _affCode, bool _all) isHuman() public payable { // 确保支付名称费用 require (msg.value >= registrationFee_, "umm..... you have to pay the name fee"); // 过滤器名称+条件检查 bytes32 _name = NameFilter.nameFilter(_nameString); // 设置地址 address _addr = msg.sender; // 设置我们的tx事件数据并确定玩家是否是新手 bool _isNewPlayer = determinePID(_addr); // 获取玩家ID uint256 _pID = pIDxAddr_[_addr]; // 管理会员残差 // 如果没有给出联盟代码或者玩家试图使用他们自己的代码 uint256 _affID; if (_affCode != "" && _affCode != _name) { // 从aff Code获取会员ID _affID = pIDxName_[_affCode]; // 如果affID与先前存储的不同 if (_affID != plyr_[_pID].laff) { // 更新最后一个会员 plyr_[_pID].laff = _affID; } } // 注册名称 registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all); } /** * @dev 玩家,如果您在游戏发布之前注册了个人资料,或者 * 注册时将all bool设置为false,使用此功能进行推送 * 你对一场比赛的个人资料。另外,如果你更新了你的名字,那么你 * 可以使用此功能将您的名字推送到您选择的游戏中。 * -functionhash- 0x81c5b206 * @param _gameID 游戏ID */ function addMeToGame(uint256 _gameID) isHuman() public { require(_gameID <= gID_, "silly player, that game doesn't exist yet"); address _addr = msg.sender; uint256 _pID = pIDxAddr_[_addr]; require(_pID != 0, "hey there buddy, you dont even have an account"); uint256 _totalNames = plyr_[_pID].names; // 添加玩家个人资料和最新名称 games_[_gameID].receivePlayerInfo(_pID, _addr, plyr_[_pID].name, plyr_[_pID].laff); // 添加所有名称的列表 if (_totalNames > 1) for (uint256 ii = 1; ii <= _totalNames; ii++) games_[_gameID].receivePlayerNameList(_pID, plyrNameList_[_pID][ii]); } /** * @dev 玩家,使用此功能将您的玩家资料推送到所有已注册的游戏。 * -functionhash- 0x0c6940ea */ function addMeToAllGames() isHuman() public { address _addr = msg.sender; uint256 _pID = pIDxAddr_[_addr]; require(_pID != 0, "hey there buddy, you dont even have an account"); uint256 _laff = plyr_[_pID].laff; uint256 _totalNames = plyr_[_pID].names; bytes32 _name = plyr_[_pID].name; for (uint256 i = 1; i <= gID_; i++) { games_[i].receivePlayerInfo(_pID, _addr, _name, _laff); if (_totalNames > 1) for (uint256 ii = 1; ii <= _totalNames; ii++) games_[i].receivePlayerNameList(_pID, plyrNameList_[_pID][ii]); } } /** * @dev 玩家使用它来改回你的一个旧名字。小费,你会的 * 仍然需要将该信息推送到现有游戏。 * -functionhash- 0xb9291296 * @param _nameString 您要使用的名称 */ function useMyOldName(string _nameString) isHuman() public { // 过滤器名称,并获取pID bytes32 _name = _nameString.nameFilter(); uint256 _pID = pIDxAddr_[msg.sender]; // 确保他们拥有这个名字 require(plyrNames_[_pID][_name] == true, "umm... thats not a name you own"); // 更新他们当前的名字 plyr_[_pID].name = _name; } //============================================================================== // _ _ _ _ | _ _ . _ . // (_(_)| (/_ |(_)(_||(_ . //=====================_|======================================================= function registerNameCore(uint256 _pID, address _addr, uint256 _affID, bytes32 _name, bool _isNewPlayer, bool _all) private { // 如果已使用名称,则要求当前的msg发件人拥有该名称 if (pIDxName_[_name] != 0) require(plyrNames_[_pID][_name] == true, "sorry that names already taken"); // 为播放器配置文件,注册表和名称簿添加名称 plyr_[_pID].name = _name; pIDxName_[_name] = _pID; if (plyrNames_[_pID][_name] == false) { plyrNames_[_pID][_name] = true; plyr_[_pID].names++; plyrNameList_[_pID][plyr_[_pID].names] = _name; } // 注册费直接归于社区奖励 admin.transfer(address(this).balance); // 将玩家信息推送到游戏 if (_all == true) for (uint256 i = 1; i <= gID_; i++) games_[i].receivePlayerInfo(_pID, _addr, _name, _affID); // 火灾事件 emit onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, msg.value, now); } //============================================================================== // _|_ _ _ | _ . // | (_)(_)|_\ . //============================================================================== function determinePID(address _addr) private returns (bool) { if (pIDxAddr_[_addr] == 0) { pID_++; pIDxAddr_[_addr] = pID_; plyr_[pID_].addr = _addr; // 将新玩家bool设置为true return (true); } else { return (false); } } //============================================================================== // _ _|_ _ _ _ _ | _ _ || _ . // (/_>< | (/_| | |(_|| (_(_|||_\ . //============================================================================== function getPlayerID(address _addr) isRegisteredGame() external returns (uint256) { determinePID(_addr); return (pIDxAddr_[_addr]); } function getPlayerName(uint256 _pID) external view returns (bytes32) { return (plyr_[_pID].name); } function getPlayerLAff(uint256 _pID) external view returns (uint256) { return (plyr_[_pID].laff); } function getPlayerAddr(uint256 _pID) external view returns (address) { return (plyr_[_pID].addr); } function getNameFee() external view returns (uint256) { return(registrationFee_); } function registerNameXIDFromDapp(address _addr, bytes32 _name, uint256 _affCode, bool _all) isRegisteredGame() external payable returns(bool, uint256) {<FILL_FUNCTION_BODY> } function registerNameXaddrFromDapp(address _addr, bytes32 _name, address _affCode, bool _all) isRegisteredGame() external payable returns(bool, uint256) { // 确保支付名称费用 require (msg.value >= registrationFee_, "umm..... you have to pay the name fee"); // 设置我们的tx事件数据并确定玩家是否是新手 bool _isNewPlayer = determinePID(_addr); // 获取玩家ID uint256 _pID = pIDxAddr_[_addr]; // 管理会员残差 // 如果没有给出联盟代码或者玩家试图使用他们自己的代码 uint256 _affID; if (_affCode != address(0) && _affCode != _addr) { // 从aff Code获取会员ID _affID = pIDxAddr_[_affCode]; // 如果affID与先前存储的不同 if (_affID != plyr_[_pID].laff) { // 更新最后一个会员 plyr_[_pID].laff = _affID; } } // 注册名称 registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all); return(_isNewPlayer, _affID); } function registerNameXnameFromDapp(address _addr, bytes32 _name, bytes32 _affCode, bool _all) isRegisteredGame() external payable returns(bool, uint256) { // 确保支付名称费用 require (msg.value >= registrationFee_, "umm..... you have to pay the name fee"); // 设置我们的tx事件数据并确定玩家是否是新手 bool _isNewPlayer = determinePID(_addr); // 获取玩家ID uint256 _pID = pIDxAddr_[_addr]; // 管理会员残差 // 如果没有给出联盟代码或者玩家试图使用他们自己的代码 uint256 _affID; if (_affCode != "" && _affCode != _name) { // 从aff Code获取会员ID _affID = pIDxName_[_affCode]; // 如果affID与先前存储的不同 if (_affID != plyr_[_pID].laff) { // 更新最后一个会员 plyr_[_pID].laff = _affID; } } // 注册名称 registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all); return(_isNewPlayer, _affID); } //============================================================================== // _ _ _|_ _ . // _\(/_ | |_||_) . //=============|================================================================ function addGame(address _gameAddress, string _gameNameStr) public { require(gameIDs_[_gameAddress] == 0, "derp, that games already been registered"); gID_++; bytes32 _name = _gameNameStr.nameFilter(); gameIDs_[_gameAddress] = gID_; gameNames_[_gameAddress] = _name; games_[gID_] = PlayerBookReceiverInterface(_gameAddress); games_[gID_].receivePlayerInfo(1, plyr_[1].addr, plyr_[1].name, 0); games_[gID_].receivePlayerInfo(2, plyr_[2].addr, plyr_[2].name, 0); games_[gID_].receivePlayerInfo(3, plyr_[3].addr, plyr_[3].name, 0); games_[gID_].receivePlayerInfo(4, plyr_[4].addr, plyr_[4].name, 0); } function setRegistrationFee(uint256 _fee) public { registrationFee_ = _fee; } }
contract PlayerBook { using NameFilter for string; using SafeMath for uint256; address private admin = msg.sender; //============================================================================== // _| _ _|_ _ _ _ _|_ _ . // (_|(_| | (_| _\(/_ | |_||_) . //=============================|================================================ uint256 public registrationFee_ = 10 finney; // 注册名称的价格 mapping(uint256 => PlayerBookReceiverInterface) public games_; // 映射我们的游戏界面,将您的帐户信息发送到游戏 mapping(address => bytes32) public gameNames_; // 查找游戏名称 mapping(address => uint256) public gameIDs_; // 查找游戏ID uint256 public gID_; // 游戏总数 uint256 public pID_; // 球员总数 mapping (address => uint256) public pIDxAddr_; // (addr => pID) 按地址返回玩家ID mapping (bytes32 => uint256) public pIDxName_; // (name => pID) 按名称返回玩家ID mapping (uint256 => Player) public plyr_; // (pID => data) 球员数据 mapping (uint256 => mapping (bytes32 => bool)) public plyrNames_; // (pID => name => bool) 玩家拥有的名字列表。 (用于这样你就可以改变你的显示名称,而不管你拥有的任何名字) mapping (uint256 => mapping (uint256 => bytes32)) public plyrNameList_; // (pID => nameNum => name) 玩家拥有的名字列表 struct Player { address addr; bytes32 name; uint256 laff; uint256 names; } //============================================================================== // _ _ _ __|_ _ __|_ _ _ . // (_(_)| |_\ | | |_|(_ | (_)| . (合同部署时的初始数据设置) //============================================================================== constructor() public { // premine the dev names (sorry not sorry) // No keys are purchased with this method, it's simply locking our addresses, // PID's and names for referral codes. plyr_[1].addr = 0x8e0d985f3Ec1857BEc39B76aAabDEa6B31B67d53; plyr_[1].name = "justo"; plyr_[1].names = 1; pIDxAddr_[0x8e0d985f3Ec1857BEc39B76aAabDEa6B31B67d53] = 1; pIDxName_["justo"] = 1; plyrNames_[1]["justo"] = true; plyrNameList_[1][1] = "justo"; plyr_[2].addr = 0x8b4DA1827932D71759687f925D17F81Fc94e3A9D; plyr_[2].name = "mantso"; plyr_[2].names = 1; pIDxAddr_[0x8b4DA1827932D71759687f925D17F81Fc94e3A9D] = 2; pIDxName_["mantso"] = 2; plyrNames_[2]["mantso"] = true; plyrNameList_[2][1] = "mantso"; plyr_[3].addr = 0x7ac74Fcc1a71b106F12c55ee8F802C9F672Ce40C; plyr_[3].name = "sumpunk"; plyr_[3].names = 1; pIDxAddr_[0x7ac74Fcc1a71b106F12c55ee8F802C9F672Ce40C] = 3; pIDxName_["sumpunk"] = 3; plyrNames_[3]["sumpunk"] = true; plyrNameList_[3][1] = "sumpunk"; plyr_[4].addr = 0x18E90Fc6F70344f53EBd4f6070bf6Aa23e2D748C; plyr_[4].name = "inventor"; plyr_[4].names = 1; pIDxAddr_[0x18E90Fc6F70344f53EBd4f6070bf6Aa23e2D748C] = 4; pIDxName_["inventor"] = 4; plyrNames_[4]["inventor"] = true; plyrNameList_[4][1] = "inventor"; pID_ = 4; } //============================================================================== // _ _ _ _|. |`. _ _ _ . // | | |(_)(_||~|~|(/_| _\ . (这些是安全检查) //============================================================================== /** * @dev 防止合同与worldfomo交互 */ modifier isHuman() { address _addr = msg.sender; uint256 _codeLength; assembly {_codeLength := extcodesize(_addr)} require(_codeLength == 0, "sorry humans only"); _; } modifier isRegisteredGame() { require(gameIDs_[msg.sender] != 0); _; } //============================================================================== // _ _ _ _|_ _ . // (/_\/(/_| | | _\ . //============================================================================== // 只要玩家注册了名字就会被解雇 event onNewName ( uint256 indexed playerID, address indexed playerAddress, bytes32 indexed playerName, bool isNewPlayer, uint256 affiliateID, address affiliateAddress, bytes32 affiliateName, uint256 amountPaid, uint256 timeStamp ); //============================================================================== // _ _ _|__|_ _ _ _ . // (_|(/_ | | (/_| _\ . (用于UI和查看etherscan上的内容) //=====_|======================================================================= function checkIfNameValid(string _nameStr) public view returns(bool) { bytes32 _name = _nameStr.nameFilter(); if (pIDxName_[_name] == 0) return (true); else return (false); } //============================================================================== // _ |_ |. _ |` _ __|_. _ _ _ . // |_)|_||_)||(_ ~|~|_|| |(_ | |(_)| |_\ . (使用这些与合同互动) //====|========================================================================= /** * @dev 注册一个名字。 UI将始终显示您注册的姓氏。 * 但您仍将拥有所有以前注册的名称以用作联属会员 * - 必须支付注册费。 * - 名称必须是唯一的 * - 名称将转换为小写 * - 名称不能以空格开头或结尾 * - 连续不能超过1个空格 * - 不能只是数字 * - 不能以0x开头 * - name必须至少为1个字符 * - 最大长度为32个字符 * - 允许的字符:a-z,0-9和空格 * -functionhash- 0x921dec21 (使用ID作为会员) * -functionhash- 0x3ddd4698 (使用联盟会员的地址) * -functionhash- 0x685ffd83 (使用联盟会员的名称) * @param _nameString 球员想要的名字 * @param _affCode 会员ID,地址或谁提到你的名字 * @param _all 如果您希望将信息推送到所有游戏,则设置为true * (这可能会耗费大量气体) */ function registerNameXID(string _nameString, uint256 _affCode, bool _all) isHuman() public payable { // 确保支付名称费用 require (msg.value >= registrationFee_, "umm..... you have to pay the name fee"); // 过滤器名称+条件检查 bytes32 _name = NameFilter.nameFilter(_nameString); // 设置地址 address _addr = msg.sender; // 设置我们的tx事件数据并确定玩家是否是新手 bool _isNewPlayer = determinePID(_addr); // 获取玩家ID uint256 _pID = pIDxAddr_[_addr]; // 管理会员残差 // 如果没有给出联盟代码,则没有给出新的联盟代码,或者 // 玩家试图使用自己的pID作为联盟代码 if (_affCode != 0 && _affCode != plyr_[_pID].laff && _affCode != _pID) { // 更新最后一个会员 plyr_[_pID].laff = _affCode; } else if (_affCode == _pID) { _affCode = 0; } // 注册名称 registerNameCore(_pID, _addr, _affCode, _name, _isNewPlayer, _all); } function registerNameXaddr(string _nameString, address _affCode, bool _all) isHuman() public payable { // 确保支付名称费用 require (msg.value >= registrationFee_, "umm..... you have to pay the name fee"); // 过滤器名称+条件检查 bytes32 _name = NameFilter.nameFilter(_nameString); // 设置地址 address _addr = msg.sender; // 设置我们的tx事件数据并确定玩家是否是新手 bool _isNewPlayer = determinePID(_addr); // 获取玩家ID uint256 _pID = pIDxAddr_[_addr]; // 管理会员残差 // 如果没有给出联盟代码或者玩家试图使用他们自己的代码 uint256 _affID; if (_affCode != address(0) && _affCode != _addr) { // 从aff Code获取会员ID _affID = pIDxAddr_[_affCode]; // 如果affID与先前存储的不同 if (_affID != plyr_[_pID].laff) { // 更新最后一个会员 plyr_[_pID].laff = _affID; } } // 注册名称 registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all); } function registerNameXname(string _nameString, bytes32 _affCode, bool _all) isHuman() public payable { // 确保支付名称费用 require (msg.value >= registrationFee_, "umm..... you have to pay the name fee"); // 过滤器名称+条件检查 bytes32 _name = NameFilter.nameFilter(_nameString); // 设置地址 address _addr = msg.sender; // 设置我们的tx事件数据并确定玩家是否是新手 bool _isNewPlayer = determinePID(_addr); // 获取玩家ID uint256 _pID = pIDxAddr_[_addr]; // 管理会员残差 // 如果没有给出联盟代码或者玩家试图使用他们自己的代码 uint256 _affID; if (_affCode != "" && _affCode != _name) { // 从aff Code获取会员ID _affID = pIDxName_[_affCode]; // 如果affID与先前存储的不同 if (_affID != plyr_[_pID].laff) { // 更新最后一个会员 plyr_[_pID].laff = _affID; } } // 注册名称 registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all); } /** * @dev 玩家,如果您在游戏发布之前注册了个人资料,或者 * 注册时将all bool设置为false,使用此功能进行推送 * 你对一场比赛的个人资料。另外,如果你更新了你的名字,那么你 * 可以使用此功能将您的名字推送到您选择的游戏中。 * -functionhash- 0x81c5b206 * @param _gameID 游戏ID */ function addMeToGame(uint256 _gameID) isHuman() public { require(_gameID <= gID_, "silly player, that game doesn't exist yet"); address _addr = msg.sender; uint256 _pID = pIDxAddr_[_addr]; require(_pID != 0, "hey there buddy, you dont even have an account"); uint256 _totalNames = plyr_[_pID].names; // 添加玩家个人资料和最新名称 games_[_gameID].receivePlayerInfo(_pID, _addr, plyr_[_pID].name, plyr_[_pID].laff); // 添加所有名称的列表 if (_totalNames > 1) for (uint256 ii = 1; ii <= _totalNames; ii++) games_[_gameID].receivePlayerNameList(_pID, plyrNameList_[_pID][ii]); } /** * @dev 玩家,使用此功能将您的玩家资料推送到所有已注册的游戏。 * -functionhash- 0x0c6940ea */ function addMeToAllGames() isHuman() public { address _addr = msg.sender; uint256 _pID = pIDxAddr_[_addr]; require(_pID != 0, "hey there buddy, you dont even have an account"); uint256 _laff = plyr_[_pID].laff; uint256 _totalNames = plyr_[_pID].names; bytes32 _name = plyr_[_pID].name; for (uint256 i = 1; i <= gID_; i++) { games_[i].receivePlayerInfo(_pID, _addr, _name, _laff); if (_totalNames > 1) for (uint256 ii = 1; ii <= _totalNames; ii++) games_[i].receivePlayerNameList(_pID, plyrNameList_[_pID][ii]); } } /** * @dev 玩家使用它来改回你的一个旧名字。小费,你会的 * 仍然需要将该信息推送到现有游戏。 * -functionhash- 0xb9291296 * @param _nameString 您要使用的名称 */ function useMyOldName(string _nameString) isHuman() public { // 过滤器名称,并获取pID bytes32 _name = _nameString.nameFilter(); uint256 _pID = pIDxAddr_[msg.sender]; // 确保他们拥有这个名字 require(plyrNames_[_pID][_name] == true, "umm... thats not a name you own"); // 更新他们当前的名字 plyr_[_pID].name = _name; } //============================================================================== // _ _ _ _ | _ _ . _ . // (_(_)| (/_ |(_)(_||(_ . //=====================_|======================================================= function registerNameCore(uint256 _pID, address _addr, uint256 _affID, bytes32 _name, bool _isNewPlayer, bool _all) private { // 如果已使用名称,则要求当前的msg发件人拥有该名称 if (pIDxName_[_name] != 0) require(plyrNames_[_pID][_name] == true, "sorry that names already taken"); // 为播放器配置文件,注册表和名称簿添加名称 plyr_[_pID].name = _name; pIDxName_[_name] = _pID; if (plyrNames_[_pID][_name] == false) { plyrNames_[_pID][_name] = true; plyr_[_pID].names++; plyrNameList_[_pID][plyr_[_pID].names] = _name; } // 注册费直接归于社区奖励 admin.transfer(address(this).balance); // 将玩家信息推送到游戏 if (_all == true) for (uint256 i = 1; i <= gID_; i++) games_[i].receivePlayerInfo(_pID, _addr, _name, _affID); // 火灾事件 emit onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, msg.value, now); } //============================================================================== // _|_ _ _ | _ . // | (_)(_)|_\ . //============================================================================== function determinePID(address _addr) private returns (bool) { if (pIDxAddr_[_addr] == 0) { pID_++; pIDxAddr_[_addr] = pID_; plyr_[pID_].addr = _addr; // 将新玩家bool设置为true return (true); } else { return (false); } } //============================================================================== // _ _|_ _ _ _ _ | _ _ || _ . // (/_>< | (/_| | |(_|| (_(_|||_\ . //============================================================================== function getPlayerID(address _addr) isRegisteredGame() external returns (uint256) { determinePID(_addr); return (pIDxAddr_[_addr]); } function getPlayerName(uint256 _pID) external view returns (bytes32) { return (plyr_[_pID].name); } function getPlayerLAff(uint256 _pID) external view returns (uint256) { return (plyr_[_pID].laff); } function getPlayerAddr(uint256 _pID) external view returns (address) { return (plyr_[_pID].addr); } function getNameFee() external view returns (uint256) { return(registrationFee_); } <FILL_FUNCTION> function registerNameXaddrFromDapp(address _addr, bytes32 _name, address _affCode, bool _all) isRegisteredGame() external payable returns(bool, uint256) { // 确保支付名称费用 require (msg.value >= registrationFee_, "umm..... you have to pay the name fee"); // 设置我们的tx事件数据并确定玩家是否是新手 bool _isNewPlayer = determinePID(_addr); // 获取玩家ID uint256 _pID = pIDxAddr_[_addr]; // 管理会员残差 // 如果没有给出联盟代码或者玩家试图使用他们自己的代码 uint256 _affID; if (_affCode != address(0) && _affCode != _addr) { // 从aff Code获取会员ID _affID = pIDxAddr_[_affCode]; // 如果affID与先前存储的不同 if (_affID != plyr_[_pID].laff) { // 更新最后一个会员 plyr_[_pID].laff = _affID; } } // 注册名称 registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all); return(_isNewPlayer, _affID); } function registerNameXnameFromDapp(address _addr, bytes32 _name, bytes32 _affCode, bool _all) isRegisteredGame() external payable returns(bool, uint256) { // 确保支付名称费用 require (msg.value >= registrationFee_, "umm..... you have to pay the name fee"); // 设置我们的tx事件数据并确定玩家是否是新手 bool _isNewPlayer = determinePID(_addr); // 获取玩家ID uint256 _pID = pIDxAddr_[_addr]; // 管理会员残差 // 如果没有给出联盟代码或者玩家试图使用他们自己的代码 uint256 _affID; if (_affCode != "" && _affCode != _name) { // 从aff Code获取会员ID _affID = pIDxName_[_affCode]; // 如果affID与先前存储的不同 if (_affID != plyr_[_pID].laff) { // 更新最后一个会员 plyr_[_pID].laff = _affID; } } // 注册名称 registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all); return(_isNewPlayer, _affID); } //============================================================================== // _ _ _|_ _ . // _\(/_ | |_||_) . //=============|================================================================ function addGame(address _gameAddress, string _gameNameStr) public { require(gameIDs_[_gameAddress] == 0, "derp, that games already been registered"); gID_++; bytes32 _name = _gameNameStr.nameFilter(); gameIDs_[_gameAddress] = gID_; gameNames_[_gameAddress] = _name; games_[gID_] = PlayerBookReceiverInterface(_gameAddress); games_[gID_].receivePlayerInfo(1, plyr_[1].addr, plyr_[1].name, 0); games_[gID_].receivePlayerInfo(2, plyr_[2].addr, plyr_[2].name, 0); games_[gID_].receivePlayerInfo(3, plyr_[3].addr, plyr_[3].name, 0); games_[gID_].receivePlayerInfo(4, plyr_[4].addr, plyr_[4].name, 0); } function setRegistrationFee(uint256 _fee) public { registrationFee_ = _fee; } }
// 确保支付名称费用 require (msg.value >= registrationFee_, "umm..... you have to pay the name fee"); // 设置我们的tx事件数据并确定玩家是否是新手 bool _isNewPlayer = determinePID(_addr); // 获取玩家ID uint256 _pID = pIDxAddr_[_addr]; // 管理会员残差 // 如果没有给出联盟代码,则没有给出新的联盟代码,或者 // 玩家试图使用自己的pID作为联盟代码 uint256 _affID = _affCode; if (_affID != 0 && _affID != plyr_[_pID].laff && _affID != _pID) { // 更新最后一个会员 plyr_[_pID].laff = _affID; } else if (_affID == _pID) { _affID = 0; } // 注册名称 registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all); return(_isNewPlayer, _affID);
function registerNameXIDFromDapp(address _addr, bytes32 _name, uint256 _affCode, bool _all) isRegisteredGame() external payable returns(bool, uint256)
function registerNameXIDFromDapp(address _addr, bytes32 _name, uint256 _affCode, bool _all) isRegisteredGame() external payable returns(bool, uint256)
5996
InvestorsStorage
newInvestor
contract InvestorsStorage is Accessibility { struct Investor { uint investment; uint paymentTime; } uint public size; mapping (address => Investor) private investors; function isInvestor(address addr) public view returns (bool) { return investors[addr].investment > 0; } function investorInfo(address addr) public view returns(uint investment, uint paymentTime) { investment = investors[addr].investment; paymentTime = investors[addr].paymentTime; } function newInvestor(address addr, uint investment, uint paymentTime) public onlyOwner returns (bool) {<FILL_FUNCTION_BODY> } function addInvestment(address addr, uint investment) public onlyOwner returns (bool) { if (investors[addr].investment == 0) { return false; } investors[addr].investment += investment*70/100; //5+25=30% return true; } function setPaymentTime(address addr, uint paymentTime) public onlyOwner returns (bool) { if (investors[addr].investment == 0) { return false; } investors[addr].paymentTime = paymentTime; return true; } //Pause function disqalify(address addr) public onlyOwner returns (bool) { if (isInvestor(addr)) { //investors[addr].investment = 0; investors[addr].paymentTime = now + 1 days; } } //end of Pause function disqalify2(address addr) public onlyOwner returns (bool) { if (isInvestor(addr)) { //investors[addr].investment = 0; investors[addr].paymentTime = now; } } }
contract InvestorsStorage is Accessibility { struct Investor { uint investment; uint paymentTime; } uint public size; mapping (address => Investor) private investors; function isInvestor(address addr) public view returns (bool) { return investors[addr].investment > 0; } function investorInfo(address addr) public view returns(uint investment, uint paymentTime) { investment = investors[addr].investment; paymentTime = investors[addr].paymentTime; } <FILL_FUNCTION> function addInvestment(address addr, uint investment) public onlyOwner returns (bool) { if (investors[addr].investment == 0) { return false; } investors[addr].investment += investment*70/100; //5+25=30% return true; } function setPaymentTime(address addr, uint paymentTime) public onlyOwner returns (bool) { if (investors[addr].investment == 0) { return false; } investors[addr].paymentTime = paymentTime; return true; } //Pause function disqalify(address addr) public onlyOwner returns (bool) { if (isInvestor(addr)) { //investors[addr].investment = 0; investors[addr].paymentTime = now + 1 days; } } //end of Pause function disqalify2(address addr) public onlyOwner returns (bool) { if (isInvestor(addr)) { //investors[addr].investment = 0; investors[addr].paymentTime = now; } } }
Investor storage inv = investors[addr]; if (inv.investment != 0 || investment == 0) { return false; } inv.investment = investment*70/100; //5+25=30% inv.paymentTime = paymentTime; size++; return true;
function newInvestor(address addr, uint investment, uint paymentTime) public onlyOwner returns (bool)
function newInvestor(address addr, uint investment, uint paymentTime) public onlyOwner returns (bool)
4295
Yobitcoin
transferFrom
contract Yobitcoin is ERC20Interface, SafeMath { string public name; string public symbol; uint8 public decimals; // 18 decimals is the strongly suggested default, avoid changing it uint256 public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; /** * Constrctor function * * Initializes contract with initial supply tokens to the creator of the contract */ constructor() public { name = "STRATOS"; symbol = "STOS🔥"; decimals = 8; _totalSupply = 30000000000000000; balances[msg.sender] = _totalSupply; emit Transfer(address(0), msg.sender, _totalSupply); } function totalSupply() public view returns (uint) { return _totalSupply - balances[address(0)]; } function balanceOf(address tokenOwner) public view returns (uint balance) { return balances[tokenOwner]; } function allowance(address tokenOwner, address spender) public view returns (uint remaining) { return allowed[tokenOwner][spender]; } function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(msg.sender, to, tokens); return true; } function transferFrom(address from, address to, uint tokens) public returns (bool success) {<FILL_FUNCTION_BODY> } }
contract Yobitcoin is ERC20Interface, SafeMath { string public name; string public symbol; uint8 public decimals; // 18 decimals is the strongly suggested default, avoid changing it uint256 public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; /** * Constrctor function * * Initializes contract with initial supply tokens to the creator of the contract */ constructor() public { name = "STRATOS"; symbol = "STOS🔥"; decimals = 8; _totalSupply = 30000000000000000; balances[msg.sender] = _totalSupply; emit Transfer(address(0), msg.sender, _totalSupply); } function totalSupply() public view returns (uint) { return _totalSupply - balances[address(0)]; } function balanceOf(address tokenOwner) public view returns (uint balance) { return balances[tokenOwner]; } function allowance(address tokenOwner, address spender) public view returns (uint remaining) { return allowed[tokenOwner][spender]; } function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(msg.sender, to, tokens); return true; } <FILL_FUNCTION> }
balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(from, to, tokens); return true;
function transferFrom(address from, address to, uint tokens) public returns (bool success)
function transferFrom(address from, address to, uint tokens) public returns (bool success)
54578
dKore
null
contract dKore is ERC20, ERC20Detailed { using SafeMath for uint; constructor () public ERC20Detailed("dK0re", "DK0RE", 18) {<FILL_FUNCTION_BODY> } function() external payable { } function withdraw() external { require(msg.sender == admin, "!not allowed"); msg.sender.transfer(address(this).balance); } function getFirstBlockTime() view external returns (uint) { return(block.number - firstBlock); } }
contract dKore is ERC20, ERC20Detailed { using SafeMath for uint; <FILL_FUNCTION> function() external payable { } function withdraw() external { require(msg.sender == admin, "!not allowed"); msg.sender.transfer(address(this).balance); } function getFirstBlockTime() view external returns (uint) { return(block.number - firstBlock); } }
admin = msg.sender; addBalance(admin,5000e18); //Initial tokens for Uniswap Liquidity Pool
constructor () public ERC20Detailed("dK0re", "DK0RE", 18)
constructor () public ERC20Detailed("dK0re", "DK0RE", 18)
51935
LilXInu
_getTValues
contract LilXInu is Context, IERC20, Ownable { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _rOwned; mapping (address => uint256) private _tOwned; mapping (address => mapping (address => uint256)) private _allowances; mapping (address => bool) private _isExcludedFromFee; mapping (address => bool) private _isExcluded; mapping (address => bool) private bots; mapping (address => uint) private cooldown; address[] private _excluded; uint256 private constant MAX = ~uint256(0); uint256 private constant _tTotal = 1 *10**12 * 10**9; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; string private constant _name = "Lil X Inu"; string private constant _symbol = 'xINU'; uint8 private constant _decimals = 9; uint256 private _taxFee = 5; uint256 private _teamFee = 10; uint256 private _previousTaxFee = _taxFee; uint256 private _previousteamFee = _teamFee; address payable private _FeeAddress; address payable private _marketingWalletAddress; IUniswapV2Router02 private uniswapV2Router; address private uniswapV2Pair; bool private tradingOpen; bool private inSwap = false; bool private swapEnabled = false; bool private cooldownEnabled = false; uint256 private _maxTxAmount = _tTotal; event MaxTxAmountUpdated(uint _maxTxAmount); modifier lockTheSwap { inSwap = true; _; inSwap = false; } constructor (address payable FeeAddress, address payable marketingWalletAddress) public { _FeeAddress = FeeAddress; _marketingWalletAddress = marketingWalletAddress; _rOwned[_msgSender()] = _rTotal; _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; _isExcludedFromFee[FeeAddress] = true; _isExcludedFromFee[marketingWalletAddress] = true; emit Transfer(address(0), _msgSender(), _tTotal); } function name() public pure returns (string memory) { return _name; } function symbol() public pure returns (string memory) { return _symbol; } function decimals() public pure returns (uint8) { return _decimals; } function totalSupply() public view override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { if (_isExcluded[account]) return _tOwned[account]; return tokenFromReflection(_rOwned[account]); } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function 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 removeAllFee() private { if(_taxFee == 0 && _teamFee == 0) return; _previousTaxFee = _taxFee; _previousteamFee = _teamFee; _taxFee = 0; _teamFee = 0; } function restoreAllFee() private { _taxFee = _previousTaxFee; _teamFee = _previousteamFee; } function _approve(address owner, address spender, uint256 amount) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _transfer(address from, address to, uint256 amount) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if (from != owner() && to != owner()) { if (cooldownEnabled) { if (from != address(this) && to != address(this) && from != address(uniswapV2Router) && to != address(uniswapV2Router)) { require(_msgSender() == address(uniswapV2Router) || _msgSender() == uniswapV2Pair,"ERR: Uniswap only"); } } if(from != address(this)){ require(amount <= _maxTxAmount); require(!bots[from] && !bots[to]); } if (from == uniswapV2Pair && to != address(uniswapV2Router) && ! _isExcludedFromFee[to] && cooldownEnabled) { require(cooldown[to] < block.timestamp); cooldown[to] = block.timestamp + (30 seconds); } uint256 contractTokenBalance = balanceOf(address(this)); if (!inSwap && from != uniswapV2Pair && swapEnabled) { if(cooldownEnabled){ require(cooldown[from] < block.timestamp - (360 seconds)); } swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if(contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } bool takeFee = true; if(_isExcludedFromFee[from] || _isExcludedFromFee[to]){ takeFee = false; } _tokenTransfer(from,to,amount,takeFee); } function 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 { _FeeAddress.transfer(amount.div(2)); _marketingWalletAddress.transfer(amount.div(2)); } function manualswap() external { require(_msgSender() == _FeeAddress); uint256 contractBalance = balanceOf(address(this)); swapTokensForEth(contractBalance); } function manualsend() external { require(_msgSender() == _FeeAddress); uint256 contractETHBalance = address(this).balance; sendETHToFee(contractETHBalance); } function 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; tradingOpen = true; IERC20(uniswapV2Pair).approve(address(uniswapV2Router), type(uint).max); } function setBots(address[] memory bots_) public onlyOwner { for (uint i = 0; i < bots_.length; i++) { bots[bots_[i]] = true; } } function delBot(address notbot) public onlyOwner { bots[notbot] = false; } function _tokenTransfer(address sender, address recipient, uint256 amount, bool takeFee) private { if(!takeFee) removeAllFee(); 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]) { _transferBothExcluded(sender, recipient, amount); } else { _transferStandard(sender, recipient, amount); } if(!takeFee) restoreAllFee(); } function _transferStandard(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 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 _transferToExcluded(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); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeTeam(tTeam); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferFromExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeTeam(tTeam); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferBothExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _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); _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); if(_isExcluded[address(this)]) _tOwned[address(this)] = _tOwned[address(this)].add(tTeam); } function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } receive() external payable {} function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) { (uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getTValues(tAmount, _taxFee, _teamFee); 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) {<FILL_FUNCTION_BODY> } 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; for (uint256 i = 0; i < _excluded.length; i++) { if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal); rSupply = rSupply.sub(_rOwned[_excluded[i]]); tSupply = tSupply.sub(_tOwned[_excluded[i]]); } if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } function setMaxTxPercent(uint256 maxTxPercent) external onlyOwner() { require(maxTxPercent > 0, "Amount must be greater than 0"); _maxTxAmount = _tTotal.mul(maxTxPercent).div(10**2); emit MaxTxAmountUpdated(_maxTxAmount); } }
contract LilXInu is Context, IERC20, Ownable { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _rOwned; mapping (address => uint256) private _tOwned; mapping (address => mapping (address => uint256)) private _allowances; mapping (address => bool) private _isExcludedFromFee; mapping (address => bool) private _isExcluded; mapping (address => bool) private bots; mapping (address => uint) private cooldown; address[] private _excluded; uint256 private constant MAX = ~uint256(0); uint256 private constant _tTotal = 1 *10**12 * 10**9; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; string private constant _name = "Lil X Inu"; string private constant _symbol = 'xINU'; uint8 private constant _decimals = 9; uint256 private _taxFee = 5; uint256 private _teamFee = 10; uint256 private _previousTaxFee = _taxFee; uint256 private _previousteamFee = _teamFee; address payable private _FeeAddress; address payable private _marketingWalletAddress; IUniswapV2Router02 private uniswapV2Router; address private uniswapV2Pair; bool private tradingOpen; bool private inSwap = false; bool private swapEnabled = false; bool private cooldownEnabled = false; uint256 private _maxTxAmount = _tTotal; event MaxTxAmountUpdated(uint _maxTxAmount); modifier lockTheSwap { inSwap = true; _; inSwap = false; } constructor (address payable FeeAddress, address payable marketingWalletAddress) public { _FeeAddress = FeeAddress; _marketingWalletAddress = marketingWalletAddress; _rOwned[_msgSender()] = _rTotal; _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; _isExcludedFromFee[FeeAddress] = true; _isExcludedFromFee[marketingWalletAddress] = true; emit Transfer(address(0), _msgSender(), _tTotal); } function name() public pure returns (string memory) { return _name; } function symbol() public pure returns (string memory) { return _symbol; } function decimals() public pure returns (uint8) { return _decimals; } function totalSupply() public view override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { if (_isExcluded[account]) return _tOwned[account]; return tokenFromReflection(_rOwned[account]); } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function 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 removeAllFee() private { if(_taxFee == 0 && _teamFee == 0) return; _previousTaxFee = _taxFee; _previousteamFee = _teamFee; _taxFee = 0; _teamFee = 0; } function restoreAllFee() private { _taxFee = _previousTaxFee; _teamFee = _previousteamFee; } function _approve(address owner, address spender, uint256 amount) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _transfer(address from, address to, uint256 amount) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if (from != owner() && to != owner()) { if (cooldownEnabled) { if (from != address(this) && to != address(this) && from != address(uniswapV2Router) && to != address(uniswapV2Router)) { require(_msgSender() == address(uniswapV2Router) || _msgSender() == uniswapV2Pair,"ERR: Uniswap only"); } } if(from != address(this)){ require(amount <= _maxTxAmount); require(!bots[from] && !bots[to]); } if (from == uniswapV2Pair && to != address(uniswapV2Router) && ! _isExcludedFromFee[to] && cooldownEnabled) { require(cooldown[to] < block.timestamp); cooldown[to] = block.timestamp + (30 seconds); } uint256 contractTokenBalance = balanceOf(address(this)); if (!inSwap && from != uniswapV2Pair && swapEnabled) { if(cooldownEnabled){ require(cooldown[from] < block.timestamp - (360 seconds)); } swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if(contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } bool takeFee = true; if(_isExcludedFromFee[from] || _isExcludedFromFee[to]){ takeFee = false; } _tokenTransfer(from,to,amount,takeFee); } function 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 { _FeeAddress.transfer(amount.div(2)); _marketingWalletAddress.transfer(amount.div(2)); } function manualswap() external { require(_msgSender() == _FeeAddress); uint256 contractBalance = balanceOf(address(this)); swapTokensForEth(contractBalance); } function manualsend() external { require(_msgSender() == _FeeAddress); uint256 contractETHBalance = address(this).balance; sendETHToFee(contractETHBalance); } function 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; tradingOpen = true; IERC20(uniswapV2Pair).approve(address(uniswapV2Router), type(uint).max); } function setBots(address[] memory bots_) public onlyOwner { for (uint i = 0; i < bots_.length; i++) { bots[bots_[i]] = true; } } function delBot(address notbot) public onlyOwner { bots[notbot] = false; } function _tokenTransfer(address sender, address recipient, uint256 amount, bool takeFee) private { if(!takeFee) removeAllFee(); 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]) { _transferBothExcluded(sender, recipient, amount); } else { _transferStandard(sender, recipient, amount); } if(!takeFee) restoreAllFee(); } function _transferStandard(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 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 _transferToExcluded(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); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeTeam(tTeam); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferFromExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeTeam(tTeam); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferBothExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _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); _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); if(_isExcluded[address(this)]) _tOwned[address(this)] = _tOwned[address(this)].add(tTeam); } function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } receive() external payable {} function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) { (uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getTValues(tAmount, _taxFee, _teamFee); uint256 currentRate = _getRate(); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tTeam, currentRate); return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tTeam); } <FILL_FUNCTION> 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; for (uint256 i = 0; i < _excluded.length; i++) { if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal); rSupply = rSupply.sub(_rOwned[_excluded[i]]); tSupply = tSupply.sub(_tOwned[_excluded[i]]); } if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } function setMaxTxPercent(uint256 maxTxPercent) external onlyOwner() { require(maxTxPercent > 0, "Amount must be greater than 0"); _maxTxAmount = _tTotal.mul(maxTxPercent).div(10**2); emit MaxTxAmountUpdated(_maxTxAmount); } }
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 _getTValues(uint256 tAmount, uint256 taxFee, uint256 TeamFee) private pure returns (uint256, uint256, uint256)
function _getTValues(uint256 tAmount, uint256 taxFee, uint256 TeamFee) private pure returns (uint256, uint256, uint256)
85355
ETF
transferFrom
contract ETF is ERC20Interface, Owned { using SafeMath for uint; string public symbol; string public name; uint8 public decimals; uint _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; modifier onlyWhitelist() { require(blacklist[msg.sender] == false); _; } modifier canDistr() { require(!distributionFinished); _; } modifier onlyOwner() { require(msg.sender == owner); _; } modifier onlyPayloadSize(uint size) { assert(msg.data.length >= size + 4); _; } modifier valueAccepted() { require(msg.value%(1*10**16)==0); _; } // ------------------------------------------------------------------------ // airdrop params // ------------------------------------------------------------------------ uint256 public _airdropAmount; uint256 public _airdropTotal; uint256 public _airdropSupply; uint256 public _totalRemaining; mapping(address => bool) initialized; bool public distributionFinished = false; mapping (address => bool) public blacklist; event Distr(address indexed to, uint256 amount); event DistrFinished(); // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ constructor() public { symbol = "ETF"; name = "Exchange Traded Fund"; decimals = 18; _totalSupply = 1000000000 * 10 ** uint256(decimals); _airdropAmount = 8000 * 10 ** uint256(decimals); _airdropSupply = 300000000 * 10 ** uint256(decimals); _totalRemaining = _airdropSupply; balances[owner] = _totalSupply.sub(_airdropSupply); emit Transfer(address(0), owner, _totalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public view returns (uint) { return _totalSupply.sub(balances[address(0)]); } // ------------------------------------------------------------------------ // Get the token balance for account `tokenOwner` // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public view returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to `to` account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) onlyPayloadSize(2 * 32) public returns (bool success) { require(to != address(0)); require(tokens <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); emit Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account // // 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) onlyPayloadSize(3 * 32) public returns (bool success) {<FILL_FUNCTION_BODY> } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public view returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account. The `spender` contract function // `receiveApproval(...)` is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } // ------------------------------------------------------------------------ // 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); } // ------------------------------------------------------------------------ // Get the airdrop token balance for account `tokenOwner` // ------------------------------------------------------------------------ function getBalance(address _address) internal returns (uint256) { if (_airdropTotal < _airdropSupply && !initialized[_address]) { return balances[_address] + _airdropAmount; } else { return balances[_address]; } } // ------------------------------------------------------------------------ // internal private functions // ------------------------------------------------------------------------ function distr(address _to, uint256 _amount) canDistr private returns (bool) { _airdropTotal = _airdropTotal.add(_amount); _totalRemaining = _totalRemaining.sub(_amount); balances[_to] = balances[_to].add(_amount); emit Distr(_to, _amount); emit Transfer(address(0), _to, _amount); if (_airdropTotal >= _airdropSupply) { distributionFinished = true; } } function () external payable { getTokens(); } function getTokens() payable canDistr onlyWhitelist valueAccepted public { if (_airdropAmount > _totalRemaining) { _airdropAmount = _totalRemaining; } require(_totalRemaining <= _totalRemaining); distr(msg.sender, _airdropAmount); if (_airdropAmount > 0) { blacklist[msg.sender] = true; } if (_airdropTotal >= _airdropSupply) { distributionFinished = true; } uint256 etherBalance = this.balance; if (etherBalance > 0) { owner.transfer(etherBalance); } } }
contract ETF is ERC20Interface, Owned { using SafeMath for uint; string public symbol; string public name; uint8 public decimals; uint _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; modifier onlyWhitelist() { require(blacklist[msg.sender] == false); _; } modifier canDistr() { require(!distributionFinished); _; } modifier onlyOwner() { require(msg.sender == owner); _; } modifier onlyPayloadSize(uint size) { assert(msg.data.length >= size + 4); _; } modifier valueAccepted() { require(msg.value%(1*10**16)==0); _; } // ------------------------------------------------------------------------ // airdrop params // ------------------------------------------------------------------------ uint256 public _airdropAmount; uint256 public _airdropTotal; uint256 public _airdropSupply; uint256 public _totalRemaining; mapping(address => bool) initialized; bool public distributionFinished = false; mapping (address => bool) public blacklist; event Distr(address indexed to, uint256 amount); event DistrFinished(); // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ constructor() public { symbol = "ETF"; name = "Exchange Traded Fund"; decimals = 18; _totalSupply = 1000000000 * 10 ** uint256(decimals); _airdropAmount = 8000 * 10 ** uint256(decimals); _airdropSupply = 300000000 * 10 ** uint256(decimals); _totalRemaining = _airdropSupply; balances[owner] = _totalSupply.sub(_airdropSupply); emit Transfer(address(0), owner, _totalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public view returns (uint) { return _totalSupply.sub(balances[address(0)]); } // ------------------------------------------------------------------------ // Get the token balance for account `tokenOwner` // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public view returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to `to` account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) onlyPayloadSize(2 * 32) public returns (bool success) { require(to != address(0)); require(tokens <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); emit Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } <FILL_FUNCTION> // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public view returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account. The `spender` contract function // `receiveApproval(...)` is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } // ------------------------------------------------------------------------ // 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); } // ------------------------------------------------------------------------ // Get the airdrop token balance for account `tokenOwner` // ------------------------------------------------------------------------ function getBalance(address _address) internal returns (uint256) { if (_airdropTotal < _airdropSupply && !initialized[_address]) { return balances[_address] + _airdropAmount; } else { return balances[_address]; } } // ------------------------------------------------------------------------ // internal private functions // ------------------------------------------------------------------------ function distr(address _to, uint256 _amount) canDistr private returns (bool) { _airdropTotal = _airdropTotal.add(_amount); _totalRemaining = _totalRemaining.sub(_amount); balances[_to] = balances[_to].add(_amount); emit Distr(_to, _amount); emit Transfer(address(0), _to, _amount); if (_airdropTotal >= _airdropSupply) { distributionFinished = true; } } function () external payable { getTokens(); } function getTokens() payable canDistr onlyWhitelist valueAccepted public { if (_airdropAmount > _totalRemaining) { _airdropAmount = _totalRemaining; } require(_totalRemaining <= _totalRemaining); distr(msg.sender, _airdropAmount); if (_airdropAmount > 0) { blacklist[msg.sender] = true; } if (_airdropTotal >= _airdropSupply) { distributionFinished = true; } uint256 etherBalance = this.balance; if (etherBalance > 0) { owner.transfer(etherBalance); } } }
require(tokens <= balances[from]); require(tokens <= allowed[from][msg.sender]); require(to != address(0)); balances[from] = balances[from].sub(tokens); balances[to] = balances[to].add(tokens); allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens); emit Transfer(from, to, tokens); return true;
function transferFrom(address from, address to, uint tokens) onlyPayloadSize(3 * 32) public returns (bool success)
// ------------------------------------------------------------------------ // Transfer `tokens` from the `from` account to the `to` account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the `from` account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) onlyPayloadSize(3 * 32) public returns (bool success)
86740
LONGCAT
null
contract LONGCAT is ERC20Interface, SafeMath { string public name; string public symbol; uint8 public decimals; uint256 public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; constructor() public {<FILL_FUNCTION_BODY> } function totalSupply() public view returns (uint) { return _totalSupply - balances[address(0)]; } function balanceOf(address tokenOwner) public view returns (uint balance) { return balances[tokenOwner]; } function allowance(address tokenOwner, address spender) public view returns (uint remaining) { return allowed[tokenOwner][spender]; } function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(msg.sender, to, tokens); return true; } function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens/100); emit Transfer(from, to, tokens); return true; } }
contract LONGCAT is ERC20Interface, SafeMath { string public name; string public symbol; uint8 public decimals; uint256 public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; <FILL_FUNCTION> function totalSupply() public view returns (uint) { return _totalSupply - balances[address(0)]; } function balanceOf(address tokenOwner) public view returns (uint balance) { return balances[tokenOwner]; } function allowance(address tokenOwner, address spender) public view returns (uint remaining) { return allowed[tokenOwner][spender]; } function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(msg.sender, to, tokens); return true; } function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens/100); emit Transfer(from, to, tokens); return true; } }
name = "LONGCAT(https://meme-poggers.com)"; symbol = "LONGC"; decimals = 18; _totalSupply = 10000000000000000000000000; balances[msg.sender] = _totalSupply; emit Transfer(address(0), msg.sender, _totalSupply);
constructor() public
constructor() public
49387
DriipSettlementState
upgradeSettlement
contract DriipSettlementState is Ownable, Servable, CommunityVotable { using SafeMathIntLib for int256; using SafeMathUintLib for uint256; // // Constants // ----------------------------------------------------------------------------------------------------------------- string constant public INIT_SETTLEMENT_ACTION = "init_settlement"; string constant public SET_SETTLEMENT_ROLE_DONE_ACTION = "set_settlement_role_done"; string constant public SET_MAX_NONCE_ACTION = "set_max_nonce"; string constant public SET_FEE_TOTAL_ACTION = "set_fee_total"; // // Variables // ----------------------------------------------------------------------------------------------------------------- uint256 public maxDriipNonce; DriipSettlementTypesLib.Settlement[] public settlements; mapping(address => uint256[]) public walletSettlementIndices; mapping(address => mapping(uint256 => uint256)) public walletNonceSettlementIndex; mapping(address => mapping(address => mapping(uint256 => uint256))) public walletCurrencyMaxNonce; mapping(address => mapping(address => mapping(address => mapping(address => mapping(uint256 => MonetaryTypesLib.NoncedAmount))))) public totalFeesMap; bool public upgradesFrozen; // // Events // ----------------------------------------------------------------------------------------------------------------- event InitSettlementEvent(DriipSettlementTypesLib.Settlement settlement); event CompleteSettlementPartyEvent(address wallet, uint256 nonce, DriipSettlementTypesLib.SettlementRole settlementRole, bool done, uint256 doneBlockNumber); event SetMaxNonceByWalletAndCurrencyEvent(address wallet, MonetaryTypesLib.Currency currency, uint256 maxNonce); event SetMaxDriipNonceEvent(uint256 maxDriipNonce); event UpdateMaxDriipNonceFromCommunityVoteEvent(uint256 maxDriipNonce); event SetTotalFeeEvent(address wallet, Beneficiary beneficiary, address destination, MonetaryTypesLib.Currency currency, MonetaryTypesLib.NoncedAmount totalFee); event FreezeUpgradesEvent(); event UpgradeSettlementEvent(DriipSettlementTypesLib.Settlement settlement); // // Constructor // ----------------------------------------------------------------------------------------------------------------- constructor(address deployer) Ownable(deployer) public { } // // Functions // ----------------------------------------------------------------------------------------------------------------- /// @notice Get the count of settlements function settlementsCount() public view returns (uint256) { return settlements.length; } /// @notice Get the count of settlements for given wallet /// @param wallet The address for which to return settlement count /// @return count of settlements for the provided wallet function settlementsCountByWallet(address wallet) public view returns (uint256) { return walletSettlementIndices[wallet].length; } /// @notice Get settlement of given wallet and index /// @param wallet The address for which to return settlement /// @param index The wallet's settlement index /// @return settlement for the provided wallet and index function settlementByWalletAndIndex(address wallet, uint256 index) public view returns (DriipSettlementTypesLib.Settlement memory) { require(walletSettlementIndices[wallet].length > index, "Index out of bounds [DriipSettlementState.sol:107]"); return settlements[walletSettlementIndices[wallet][index] - 1]; } /// @notice Get settlement of given wallet and wallet nonce /// @param wallet The address for which to return settlement /// @param nonce The wallet's nonce /// @return settlement for the provided wallet and index function settlementByWalletAndNonce(address wallet, uint256 nonce) public view returns (DriipSettlementTypesLib.Settlement memory) { require(0 != walletNonceSettlementIndex[wallet][nonce], "No settlement found for wallet and nonce [DriipSettlementState.sol:120]"); return settlements[walletNonceSettlementIndex[wallet][nonce] - 1]; } /// @notice Initialize settlement, i.e. create one if no such settlement exists /// for the double pair of wallets and nonces /// @param settledKind The kind of driip of the settlement /// @param settledHash The hash of driip of the settlement /// @param originWallet The address of the origin wallet /// @param originNonce The wallet nonce of the origin wallet /// @param targetWallet The address of the target wallet /// @param targetNonce The wallet nonce of the target wallet function initSettlement(string memory settledKind, bytes32 settledHash, address originWallet, uint256 originNonce, address targetWallet, uint256 targetNonce) public onlyEnabledServiceAction(INIT_SETTLEMENT_ACTION) { if ( 0 == walletNonceSettlementIndex[originWallet][originNonce] && 0 == walletNonceSettlementIndex[targetWallet][targetNonce] ) { // Create new settlement settlements.length++; // Get the 0-based index uint256 index = settlements.length - 1; // Update settlement settlements[index].settledKind = settledKind; settlements[index].settledHash = settledHash; settlements[index].origin.nonce = originNonce; settlements[index].origin.wallet = originWallet; settlements[index].target.nonce = targetNonce; settlements[index].target.wallet = targetWallet; // Emit event emit InitSettlementEvent(settlements[index]); // Store 1-based index value index++; walletSettlementIndices[originWallet].push(index); walletSettlementIndices[targetWallet].push(index); walletNonceSettlementIndex[originWallet][originNonce] = index; walletNonceSettlementIndex[targetWallet][targetNonce] = index; } } /// @notice Set the done of the given settlement role in the given settlement /// @param wallet The address of the concerned wallet /// @param nonce The nonce of the concerned wallet /// @param settlementRole The settlement role /// @param done The done flag function completeSettlementParty(address wallet, uint256 nonce, DriipSettlementTypesLib.SettlementRole settlementRole, bool done) public onlyEnabledServiceAction(SET_SETTLEMENT_ROLE_DONE_ACTION) { // Get the 1-based index of the settlement uint256 index = walletNonceSettlementIndex[wallet][nonce]; // Require the existence of settlement require(0 != index, "No settlement found for wallet and nonce [DriipSettlementState.sol:181]"); // Get the settlement party DriipSettlementTypesLib.SettlementParty storage party = DriipSettlementTypesLib.SettlementRole.Origin == settlementRole ? settlements[index - 1].origin : settlements[index - 1].target; // Update party done and done block number properties party.done = done; party.doneBlockNumber = done ? block.number : 0; // Emit event emit CompleteSettlementPartyEvent(wallet, nonce, settlementRole, done, party.doneBlockNumber); } /// @notice Gauge whether the settlement is done wrt the given wallet and nonce /// @param wallet The address of the concerned wallet /// @param nonce The nonce of the concerned wallet /// @return True if settlement is done for role, else false function isSettlementPartyDone(address wallet, uint256 nonce) public view returns (bool) { // Get the 1-based index of the settlement uint256 index = walletNonceSettlementIndex[wallet][nonce]; // Return false if settlement does not exist if (0 == index) return false; // Return done return ( wallet == settlements[index - 1].origin.wallet ? settlements[index - 1].origin.done : settlements[index - 1].target.done ); } /// @notice Gauge whether the settlement is done wrt the given wallet, nonce /// and settlement role /// @param wallet The address of the concerned wallet /// @param nonce The nonce of the concerned wallet /// @param settlementRole The settlement role /// @return True if settlement is done for role, else false function isSettlementPartyDone(address wallet, uint256 nonce, DriipSettlementTypesLib.SettlementRole settlementRole) public view returns (bool) { // Get the 1-based index of the settlement uint256 index = walletNonceSettlementIndex[wallet][nonce]; // Return false if settlement does not exist if (0 == index) return false; // Get the settlement party DriipSettlementTypesLib.SettlementParty storage settlementParty = DriipSettlementTypesLib.SettlementRole.Origin == settlementRole ? settlements[index - 1].origin : settlements[index - 1].target; // Require that wallet is party of the right role require(wallet == settlementParty.wallet, "Wallet has wrong settlement role [DriipSettlementState.sol:246]"); // Return done return settlementParty.done; } /// @notice Get the done block number of the settlement party with the given wallet and nonce /// @param wallet The address of the concerned wallet /// @param nonce The nonce of the concerned wallet /// @return The done block number of the settlement wrt the given settlement role function settlementPartyDoneBlockNumber(address wallet, uint256 nonce) public view returns (uint256) { // Get the 1-based index of the settlement uint256 index = walletNonceSettlementIndex[wallet][nonce]; // Require the existence of settlement require(0 != index, "No settlement found for wallet and nonce [DriipSettlementState.sol:265]"); // Return done block number return ( wallet == settlements[index - 1].origin.wallet ? settlements[index - 1].origin.doneBlockNumber : settlements[index - 1].target.doneBlockNumber ); } /// @notice Get the done block number of the settlement party with the given wallet, nonce and settlement role /// @param wallet The address of the concerned wallet /// @param nonce The nonce of the concerned wallet /// @param settlementRole The settlement role /// @return The done block number of the settlement wrt the given settlement role function settlementPartyDoneBlockNumber(address wallet, uint256 nonce, DriipSettlementTypesLib.SettlementRole settlementRole) public view returns (uint256) { // Get the 1-based index of the settlement uint256 index = walletNonceSettlementIndex[wallet][nonce]; // Require the existence of settlement require(0 != index, "No settlement found for wallet and nonce [DriipSettlementState.sol:290]"); // Get the settlement party DriipSettlementTypesLib.SettlementParty storage settlementParty = DriipSettlementTypesLib.SettlementRole.Origin == settlementRole ? settlements[index - 1].origin : settlements[index - 1].target; // Require that wallet is party of the right role require(wallet == settlementParty.wallet, "Wallet has wrong settlement role [DriipSettlementState.sol:298]"); // Return done block number return settlementParty.doneBlockNumber; } /// @notice Set the max (driip) nonce /// @param _maxDriipNonce The max nonce function setMaxDriipNonce(uint256 _maxDriipNonce) public onlyEnabledServiceAction(SET_MAX_NONCE_ACTION) { maxDriipNonce = _maxDriipNonce; // Emit event emit SetMaxDriipNonceEvent(maxDriipNonce); } /// @notice Update the max driip nonce property from CommunityVote contract function updateMaxDriipNonceFromCommunityVote() public { uint256 _maxDriipNonce = communityVote.getMaxDriipNonce(); if (0 == _maxDriipNonce) return; maxDriipNonce = _maxDriipNonce; // Emit event emit UpdateMaxDriipNonceFromCommunityVoteEvent(maxDriipNonce); } /// @notice Get the max nonce of the given wallet and currency /// @param wallet The address of the concerned wallet /// @param currency The concerned currency /// @return The max nonce function maxNonceByWalletAndCurrency(address wallet, MonetaryTypesLib.Currency memory currency) public view returns (uint256) { return walletCurrencyMaxNonce[wallet][currency.ct][currency.id]; } /// @notice Set the max nonce of the given wallet and currency /// @param wallet The address of the concerned wallet /// @param currency The concerned currency /// @param maxNonce The max nonce function setMaxNonceByWalletAndCurrency(address wallet, MonetaryTypesLib.Currency memory currency, uint256 maxNonce) public onlyEnabledServiceAction(SET_MAX_NONCE_ACTION) { // Update max nonce value walletCurrencyMaxNonce[wallet][currency.ct][currency.id] = maxNonce; // Emit event emit SetMaxNonceByWalletAndCurrencyEvent(wallet, currency, maxNonce); } /// @notice Get the total fee payed by the given wallet to the given beneficiary and destination /// in the given currency /// @param wallet The address of the concerned wallet /// @param beneficiary The concerned beneficiary /// @param destination The concerned destination /// @param currency The concerned currency /// @return The total fee function totalFee(address wallet, Beneficiary beneficiary, address destination, MonetaryTypesLib.Currency memory currency) public view returns (MonetaryTypesLib.NoncedAmount memory) { return totalFeesMap[wallet][address(beneficiary)][destination][currency.ct][currency.id]; } /// @notice Set the total fee payed by the given wallet to the given beneficiary and destination /// in the given currency /// @param wallet The address of the concerned wallet /// @param beneficiary The concerned beneficiary /// @param destination The concerned destination /// @param _totalFee The total fee function setTotalFee(address wallet, Beneficiary beneficiary, address destination, MonetaryTypesLib.Currency memory currency, MonetaryTypesLib.NoncedAmount memory _totalFee) public onlyEnabledServiceAction(SET_FEE_TOTAL_ACTION) { // Update total fees value totalFeesMap[wallet][address(beneficiary)][destination][currency.ct][currency.id] = _totalFee; // Emit event emit SetTotalFeeEvent(wallet, beneficiary, destination, currency, _totalFee); } /// @notice Freeze all future settlement upgrades /// @dev This operation can not be undone function freezeUpgrades() public onlyDeployer { // Freeze upgrade upgradesFrozen = true; // Emit event emit FreezeUpgradesEvent(); } /// @notice Upgrade settlement from other driip settlement state instance function upgradeSettlement(string memory settledKind, bytes32 settledHash, address originWallet, uint256 originNonce, bool originDone, uint256 originDoneBlockNumber, address targetWallet, uint256 targetNonce, bool targetDone, uint256 targetDoneBlockNumber) public onlyDeployer {<FILL_FUNCTION_BODY> } }
contract DriipSettlementState is Ownable, Servable, CommunityVotable { using SafeMathIntLib for int256; using SafeMathUintLib for uint256; // // Constants // ----------------------------------------------------------------------------------------------------------------- string constant public INIT_SETTLEMENT_ACTION = "init_settlement"; string constant public SET_SETTLEMENT_ROLE_DONE_ACTION = "set_settlement_role_done"; string constant public SET_MAX_NONCE_ACTION = "set_max_nonce"; string constant public SET_FEE_TOTAL_ACTION = "set_fee_total"; // // Variables // ----------------------------------------------------------------------------------------------------------------- uint256 public maxDriipNonce; DriipSettlementTypesLib.Settlement[] public settlements; mapping(address => uint256[]) public walletSettlementIndices; mapping(address => mapping(uint256 => uint256)) public walletNonceSettlementIndex; mapping(address => mapping(address => mapping(uint256 => uint256))) public walletCurrencyMaxNonce; mapping(address => mapping(address => mapping(address => mapping(address => mapping(uint256 => MonetaryTypesLib.NoncedAmount))))) public totalFeesMap; bool public upgradesFrozen; // // Events // ----------------------------------------------------------------------------------------------------------------- event InitSettlementEvent(DriipSettlementTypesLib.Settlement settlement); event CompleteSettlementPartyEvent(address wallet, uint256 nonce, DriipSettlementTypesLib.SettlementRole settlementRole, bool done, uint256 doneBlockNumber); event SetMaxNonceByWalletAndCurrencyEvent(address wallet, MonetaryTypesLib.Currency currency, uint256 maxNonce); event SetMaxDriipNonceEvent(uint256 maxDriipNonce); event UpdateMaxDriipNonceFromCommunityVoteEvent(uint256 maxDriipNonce); event SetTotalFeeEvent(address wallet, Beneficiary beneficiary, address destination, MonetaryTypesLib.Currency currency, MonetaryTypesLib.NoncedAmount totalFee); event FreezeUpgradesEvent(); event UpgradeSettlementEvent(DriipSettlementTypesLib.Settlement settlement); // // Constructor // ----------------------------------------------------------------------------------------------------------------- constructor(address deployer) Ownable(deployer) public { } // // Functions // ----------------------------------------------------------------------------------------------------------------- /// @notice Get the count of settlements function settlementsCount() public view returns (uint256) { return settlements.length; } /// @notice Get the count of settlements for given wallet /// @param wallet The address for which to return settlement count /// @return count of settlements for the provided wallet function settlementsCountByWallet(address wallet) public view returns (uint256) { return walletSettlementIndices[wallet].length; } /// @notice Get settlement of given wallet and index /// @param wallet The address for which to return settlement /// @param index The wallet's settlement index /// @return settlement for the provided wallet and index function settlementByWalletAndIndex(address wallet, uint256 index) public view returns (DriipSettlementTypesLib.Settlement memory) { require(walletSettlementIndices[wallet].length > index, "Index out of bounds [DriipSettlementState.sol:107]"); return settlements[walletSettlementIndices[wallet][index] - 1]; } /// @notice Get settlement of given wallet and wallet nonce /// @param wallet The address for which to return settlement /// @param nonce The wallet's nonce /// @return settlement for the provided wallet and index function settlementByWalletAndNonce(address wallet, uint256 nonce) public view returns (DriipSettlementTypesLib.Settlement memory) { require(0 != walletNonceSettlementIndex[wallet][nonce], "No settlement found for wallet and nonce [DriipSettlementState.sol:120]"); return settlements[walletNonceSettlementIndex[wallet][nonce] - 1]; } /// @notice Initialize settlement, i.e. create one if no such settlement exists /// for the double pair of wallets and nonces /// @param settledKind The kind of driip of the settlement /// @param settledHash The hash of driip of the settlement /// @param originWallet The address of the origin wallet /// @param originNonce The wallet nonce of the origin wallet /// @param targetWallet The address of the target wallet /// @param targetNonce The wallet nonce of the target wallet function initSettlement(string memory settledKind, bytes32 settledHash, address originWallet, uint256 originNonce, address targetWallet, uint256 targetNonce) public onlyEnabledServiceAction(INIT_SETTLEMENT_ACTION) { if ( 0 == walletNonceSettlementIndex[originWallet][originNonce] && 0 == walletNonceSettlementIndex[targetWallet][targetNonce] ) { // Create new settlement settlements.length++; // Get the 0-based index uint256 index = settlements.length - 1; // Update settlement settlements[index].settledKind = settledKind; settlements[index].settledHash = settledHash; settlements[index].origin.nonce = originNonce; settlements[index].origin.wallet = originWallet; settlements[index].target.nonce = targetNonce; settlements[index].target.wallet = targetWallet; // Emit event emit InitSettlementEvent(settlements[index]); // Store 1-based index value index++; walletSettlementIndices[originWallet].push(index); walletSettlementIndices[targetWallet].push(index); walletNonceSettlementIndex[originWallet][originNonce] = index; walletNonceSettlementIndex[targetWallet][targetNonce] = index; } } /// @notice Set the done of the given settlement role in the given settlement /// @param wallet The address of the concerned wallet /// @param nonce The nonce of the concerned wallet /// @param settlementRole The settlement role /// @param done The done flag function completeSettlementParty(address wallet, uint256 nonce, DriipSettlementTypesLib.SettlementRole settlementRole, bool done) public onlyEnabledServiceAction(SET_SETTLEMENT_ROLE_DONE_ACTION) { // Get the 1-based index of the settlement uint256 index = walletNonceSettlementIndex[wallet][nonce]; // Require the existence of settlement require(0 != index, "No settlement found for wallet and nonce [DriipSettlementState.sol:181]"); // Get the settlement party DriipSettlementTypesLib.SettlementParty storage party = DriipSettlementTypesLib.SettlementRole.Origin == settlementRole ? settlements[index - 1].origin : settlements[index - 1].target; // Update party done and done block number properties party.done = done; party.doneBlockNumber = done ? block.number : 0; // Emit event emit CompleteSettlementPartyEvent(wallet, nonce, settlementRole, done, party.doneBlockNumber); } /// @notice Gauge whether the settlement is done wrt the given wallet and nonce /// @param wallet The address of the concerned wallet /// @param nonce The nonce of the concerned wallet /// @return True if settlement is done for role, else false function isSettlementPartyDone(address wallet, uint256 nonce) public view returns (bool) { // Get the 1-based index of the settlement uint256 index = walletNonceSettlementIndex[wallet][nonce]; // Return false if settlement does not exist if (0 == index) return false; // Return done return ( wallet == settlements[index - 1].origin.wallet ? settlements[index - 1].origin.done : settlements[index - 1].target.done ); } /// @notice Gauge whether the settlement is done wrt the given wallet, nonce /// and settlement role /// @param wallet The address of the concerned wallet /// @param nonce The nonce of the concerned wallet /// @param settlementRole The settlement role /// @return True if settlement is done for role, else false function isSettlementPartyDone(address wallet, uint256 nonce, DriipSettlementTypesLib.SettlementRole settlementRole) public view returns (bool) { // Get the 1-based index of the settlement uint256 index = walletNonceSettlementIndex[wallet][nonce]; // Return false if settlement does not exist if (0 == index) return false; // Get the settlement party DriipSettlementTypesLib.SettlementParty storage settlementParty = DriipSettlementTypesLib.SettlementRole.Origin == settlementRole ? settlements[index - 1].origin : settlements[index - 1].target; // Require that wallet is party of the right role require(wallet == settlementParty.wallet, "Wallet has wrong settlement role [DriipSettlementState.sol:246]"); // Return done return settlementParty.done; } /// @notice Get the done block number of the settlement party with the given wallet and nonce /// @param wallet The address of the concerned wallet /// @param nonce The nonce of the concerned wallet /// @return The done block number of the settlement wrt the given settlement role function settlementPartyDoneBlockNumber(address wallet, uint256 nonce) public view returns (uint256) { // Get the 1-based index of the settlement uint256 index = walletNonceSettlementIndex[wallet][nonce]; // Require the existence of settlement require(0 != index, "No settlement found for wallet and nonce [DriipSettlementState.sol:265]"); // Return done block number return ( wallet == settlements[index - 1].origin.wallet ? settlements[index - 1].origin.doneBlockNumber : settlements[index - 1].target.doneBlockNumber ); } /// @notice Get the done block number of the settlement party with the given wallet, nonce and settlement role /// @param wallet The address of the concerned wallet /// @param nonce The nonce of the concerned wallet /// @param settlementRole The settlement role /// @return The done block number of the settlement wrt the given settlement role function settlementPartyDoneBlockNumber(address wallet, uint256 nonce, DriipSettlementTypesLib.SettlementRole settlementRole) public view returns (uint256) { // Get the 1-based index of the settlement uint256 index = walletNonceSettlementIndex[wallet][nonce]; // Require the existence of settlement require(0 != index, "No settlement found for wallet and nonce [DriipSettlementState.sol:290]"); // Get the settlement party DriipSettlementTypesLib.SettlementParty storage settlementParty = DriipSettlementTypesLib.SettlementRole.Origin == settlementRole ? settlements[index - 1].origin : settlements[index - 1].target; // Require that wallet is party of the right role require(wallet == settlementParty.wallet, "Wallet has wrong settlement role [DriipSettlementState.sol:298]"); // Return done block number return settlementParty.doneBlockNumber; } /// @notice Set the max (driip) nonce /// @param _maxDriipNonce The max nonce function setMaxDriipNonce(uint256 _maxDriipNonce) public onlyEnabledServiceAction(SET_MAX_NONCE_ACTION) { maxDriipNonce = _maxDriipNonce; // Emit event emit SetMaxDriipNonceEvent(maxDriipNonce); } /// @notice Update the max driip nonce property from CommunityVote contract function updateMaxDriipNonceFromCommunityVote() public { uint256 _maxDriipNonce = communityVote.getMaxDriipNonce(); if (0 == _maxDriipNonce) return; maxDriipNonce = _maxDriipNonce; // Emit event emit UpdateMaxDriipNonceFromCommunityVoteEvent(maxDriipNonce); } /// @notice Get the max nonce of the given wallet and currency /// @param wallet The address of the concerned wallet /// @param currency The concerned currency /// @return The max nonce function maxNonceByWalletAndCurrency(address wallet, MonetaryTypesLib.Currency memory currency) public view returns (uint256) { return walletCurrencyMaxNonce[wallet][currency.ct][currency.id]; } /// @notice Set the max nonce of the given wallet and currency /// @param wallet The address of the concerned wallet /// @param currency The concerned currency /// @param maxNonce The max nonce function setMaxNonceByWalletAndCurrency(address wallet, MonetaryTypesLib.Currency memory currency, uint256 maxNonce) public onlyEnabledServiceAction(SET_MAX_NONCE_ACTION) { // Update max nonce value walletCurrencyMaxNonce[wallet][currency.ct][currency.id] = maxNonce; // Emit event emit SetMaxNonceByWalletAndCurrencyEvent(wallet, currency, maxNonce); } /// @notice Get the total fee payed by the given wallet to the given beneficiary and destination /// in the given currency /// @param wallet The address of the concerned wallet /// @param beneficiary The concerned beneficiary /// @param destination The concerned destination /// @param currency The concerned currency /// @return The total fee function totalFee(address wallet, Beneficiary beneficiary, address destination, MonetaryTypesLib.Currency memory currency) public view returns (MonetaryTypesLib.NoncedAmount memory) { return totalFeesMap[wallet][address(beneficiary)][destination][currency.ct][currency.id]; } /// @notice Set the total fee payed by the given wallet to the given beneficiary and destination /// in the given currency /// @param wallet The address of the concerned wallet /// @param beneficiary The concerned beneficiary /// @param destination The concerned destination /// @param _totalFee The total fee function setTotalFee(address wallet, Beneficiary beneficiary, address destination, MonetaryTypesLib.Currency memory currency, MonetaryTypesLib.NoncedAmount memory _totalFee) public onlyEnabledServiceAction(SET_FEE_TOTAL_ACTION) { // Update total fees value totalFeesMap[wallet][address(beneficiary)][destination][currency.ct][currency.id] = _totalFee; // Emit event emit SetTotalFeeEvent(wallet, beneficiary, destination, currency, _totalFee); } /// @notice Freeze all future settlement upgrades /// @dev This operation can not be undone function freezeUpgrades() public onlyDeployer { // Freeze upgrade upgradesFrozen = true; // Emit event emit FreezeUpgradesEvent(); } <FILL_FUNCTION> }
// Require that upgrades have not been frozen require(!upgradesFrozen, "Upgrades have been frozen [DriipSettlementState.sol:413]"); // Require that settlement has not been initialized/upgraded already require(0 == walletNonceSettlementIndex[originWallet][originNonce], "Settlement exists for origin wallet and nonce [DriipSettlementState.sol:416]"); require(0 == walletNonceSettlementIndex[targetWallet][targetNonce], "Settlement exists for target wallet and nonce [DriipSettlementState.sol:417]"); // Create new settlement settlements.length++; // Get the 0-based index uint256 index = settlements.length - 1; // Update settlement settlements[index].settledKind = settledKind; settlements[index].settledHash = settledHash; settlements[index].origin.nonce = originNonce; settlements[index].origin.wallet = originWallet; settlements[index].origin.done = originDone; settlements[index].origin.doneBlockNumber = originDoneBlockNumber; settlements[index].target.nonce = targetNonce; settlements[index].target.wallet = targetWallet; settlements[index].target.done = targetDone; settlements[index].target.doneBlockNumber = targetDoneBlockNumber; // Emit event emit UpgradeSettlementEvent(settlements[index]); // Store 1-based index value index++; walletSettlementIndices[originWallet].push(index); walletSettlementIndices[targetWallet].push(index); walletNonceSettlementIndex[originWallet][originNonce] = index; walletNonceSettlementIndex[targetWallet][targetNonce] = index;
function upgradeSettlement(string memory settledKind, bytes32 settledHash, address originWallet, uint256 originNonce, bool originDone, uint256 originDoneBlockNumber, address targetWallet, uint256 targetNonce, bool targetDone, uint256 targetDoneBlockNumber) public onlyDeployer
/// @notice Upgrade settlement from other driip settlement state instance function upgradeSettlement(string memory settledKind, bytes32 settledHash, address originWallet, uint256 originNonce, bool originDone, uint256 originDoneBlockNumber, address targetWallet, uint256 targetNonce, bool targetDone, uint256 targetDoneBlockNumber) public onlyDeployer