|
"content": "// SPDX-License-Identifier: MIT\npragma solidity 0.6.12;\n\nimport \"./Ownable.sol\";\nimport \"./Token.sol\";\nimport \"./feeds/ChainlinkPriceConsumer.sol\";\nimport \"./feeds/PairOracleConsumer.sol\";\nimport \"./Initializable.sol\";\n//import \"hardhat/console.sol\";\n\ncontract Betting is Ownable, Initializable {\n\n using SafeMath for uint;\n\n struct Game {\n address gamer1;\n address gamer2;\n\n address token1;\n address token2;\n\n uint amount1;\n uint amount2;\n\n uint latestBet;\n\n bool closed;\n }\n\n uint public referrerFee; //50%\n uint public adminFee; //50%\n uint public globalFee; //in %\n uint public transactionFee; //in USD (10^18 meanth $1))\n bool public acceptBets;\n\n address public eth_usd_consumer_address;\n ChainlinkPriceConsumer private eth_usd_pricer;\n uint8 private eth_usd_pricer_decimals;\n\n uint256 private constant PRICE_PRECISION = 1e6;\n\n address public manager;\n address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;\n mapping(address => bool) public bots;\n mapping(address => bool) public supportBots;\n mapping(uint => Game[]) public typeGames;\n\n mapping(uint => uint) public typePrice;\n mapping(address => uint) public tokenPrice;\n mapping(address => address) public userReferrer;\n mapping(address => bool) public userRegistered;\n mapping(address => bool) public inGame;\n mapping(address => ChainlinkPriceConsumer) public chainlinkMapper;\n mapping(address => uint8) public chainlinkMapperDecimals;\n mapping(address => bool) isSupportedToken;\n mapping(address => bool) isStablecoin;\n\n uint public closeDelay = 300;\n mapping(address => uint) public turnover;\n\n struct PriceOracle {\n address pairOracle;\n address chainlinkOracle;\n }\n\n mapping(address => PriceOracle) public priceOracleMapper;\n address public feeReceiver;\n\n event Registration(address indexed user, address indexed referrer, bytes32 password);\n event PriceUpdated(address indexed tokenAddress, uint price);\n event NewGamer(address indexed user, uint indexed betType, uint indexed gameIndex, address tokenAddress, uint value, bool supportsBot);\n event ForcedCloseGame(address indexed user, uint indexed betType, uint indexed gameIndex, address tokenAddress, uint value);\n event ManuallyCloseGame(address indexed user, uint indexed betType, uint indexed gameIndex, address tokenAddress, uint value);\n event NewGame(uint indexed betType, uint gameIndex);\n event GameStarted(address indexed user1, address indexed user2, uint indexed betType, uint gameIndex);\n event NewGlobalFee(uint newGlobalFee);\n event NewAdminFee(uint newAdminFee);\n event NewReferrerFee(uint newReferrerFee);\n event NewTransactionFee(uint newTransactionFee);\n event GameClosed(address indexed winner, uint indexed betType, uint indexed gameIndex, uint prize1, uint prize2, uint fee);\n event NewTypePrice(uint indexed betType, uint price);\n\n modifier onlyManager() {\n require(msg.sender == manager, 'only manager');\n _;\n }\n\n modifier onlyUnlocked() {\n require(acceptBets, 'Bets locked');\n _;\n }\n\n modifier onlyRegistrated() {\n require(userRegistered[msg.sender] || bots[msg.sender], 'register first'); // or bot\n require(!inGame[msg.sender] || bots[msg.sender], 'already in game'); // ? or bot\n _;\n }\n\n function changeCloseDelay(uint256 _newDelay) public onlyOwner {\n closeDelay = _newDelay;\n }\n\n function lockBets() public onlyOwner {\n acceptBets = false;\n }\n\n function unlockBets() public onlyOwner {\n acceptBets = true;\n }\n\n function addBots(address[] memory _bots) public onlyOwner {\n for(uint256 i = 0; i < _bots.length; i++) {\n bots[_bots[i]] = true;\n }\n }\n\n function init(address _managerAddress, address _eth_usd_consumer_address, address[] memory supportedTokens, address[] memory chainlink_price_consumer_addresses, bool[] memory _isStablecoin) public initializer {\n require(supportedTokens.length == chainlink_price_consumer_addresses.length);\n require(supportedTokens.length == _isStablecoin.length);\n\n address msgSender = _msgSender();\n _owner = msgSender;\n emit OwnershipTransferred(address(0), msgSender);\n\n manager = _managerAddress;\n setETHUSDOracle(_eth_usd_consumer_address);\n\n for(uint i = 0; i < supportedTokens.length; i++) {\n addSupportedToken(supportedTokens[i], chainlink_price_consumer_addresses[i], _isStablecoin[i], address(0));\n }\n\n referrerFee = 50;\n adminFee = 50;\n globalFee = 10;\n\n acceptBets = true;\n }\n\n function addSupportedToken(address _newToken, address _chainlink_price_consumer_address, bool _isStablecoin, address _pair_oracle_address) public onlyOwner {\n if (!_isStablecoin && _pair_oracle_address == address(0)) {\n chainlinkMapper[_newToken] = ChainlinkPriceConsumer(_chainlink_price_consumer_address);\n chainlinkMapperDecimals[_newToken] = chainlinkMapper[_newToken].getDecimals();\n } else if (!_isStablecoin) {\n PriceOracle memory _priceOracle = PriceOracle(_pair_oracle_address, _chainlink_price_consumer_address);\n priceOracleMapper[_newToken] = _priceOracle;\n }\n\n isStablecoin[_newToken] = _isStablecoin;\n isSupportedToken[_newToken] = true;\n }\n\n function registration(address _referrer, bytes32 _password) public {\n require(!userRegistered[msg.sender], \"user already exists\");\n require(_referrer != msg.sender, \"refferer must not be equal to user wallet\");\n\n userRegistered[msg.sender] = true;\n userReferrer[msg.sender] = _referrer;\n\n emit Registration(msg.sender, _referrer, _password);\n }\n\n function newManager(address _newManagerAddress) public onlyOwner {\n manager = _newManagerAddress;\n }\n\n function setFeeReceiver(address _feeReceiver) public onlyOwner {\n feeReceiver = _feeReceiver;\n }\n\n function setGlobalFee(uint _newFee) public onlyManager {\n globalFee = _newFee;\n emit NewGlobalFee(_newFee);\n }\n\n function setAdminFee(uint _newAdminFee) public onlyManager {\n adminFee = _newAdminFee;\n emit NewAdminFee(_newAdminFee);\n }\n\n function setWinnerFee(uint _newReferrerFee) public onlyManager {\n referrerFee = _newReferrerFee;\n emit NewReferrerFee(_newReferrerFee);\n }\n\n function setTransactionFee(uint _newTransactionFee) public onlyManager {\n transactionFee = _newTransactionFee;\n emit NewTransactionFee(_newTransactionFee);\n }\n\n function bet(address tokenAddress, uint t, bool supportsBot) public payable onlyRegistrated onlyUnlocked {\n require(typePrice[t] != 0, \"invalid bet type\");\n require(isSupportedToken[tokenAddress], \"Token is not supported\");\n supportBots[msg.sender] = supportsBot;\n //@todo add referrer program\n inGame[msg.sender] = true;\n if(msg.value > 0) {\n ethBet(msg.sender, t, msg.value, supportsBot);\n return;\n }\n\n tokenBet(msg.sender, t, tokenAddress, supportsBot);\n }\n\n function forcedCloseGame(uint t, uint gameIndex) public onlyManager {\n Game memory _game = typeGames[t][gameIndex];\n\n require(!_game.closed, \"Game already closed\");\n require(_game.gamer2 == address(0), \"Game started already\");\n\n typeGames[t][gameIndex].closed = true;\n inGame[_game.gamer1] = false;\n\n IERC20(_game.token1).transfer(_game.gamer1, _game.amount1);\n\n emit ForcedCloseGame(_game.gamer1, t, gameIndex, _game.token1, _game.amount1);\n }\n\n function manuallyCloseGame(uint t, uint gameIndex) public {\n Game memory _game = typeGames[t][gameIndex];\n\n require(block.timestamp >= _game.latestBet + closeDelay, \"Please wait\");\n require(_game.gamer1 == msg.sender, \"Sender is not in the game\");\n require(_game.gamer2 == address(0), \"Game started already\");\n require(!_game.closed, \"Game already closed\");\n\n typeGames[t][gameIndex].closed = true;\n inGame[_game.gamer1] = false;\n\n IERC20(_game.token1).transfer(owner(), _game.amount1 * 5 / 100); // 5% fee\n IERC20(_game.token1).transfer(_game.gamer1, _game.amount1 - _game.amount1 * 5 / 100);\n\n emit ManuallyCloseGame(_game.gamer1, t, gameIndex, _game.token1, _game.amount1);\n }\n\n function closeGame(uint t, uint gameIndex, address payable winnerAddress) public onlyManager {\n require(!typeGames[t][gameIndex].closed, \"game already closed\");\n require(feeReceiver != address(0), \"set feeReceiver\");\n\n Game memory _game = typeGames[t][gameIndex];\n require(winnerAddress == _game.gamer1 || winnerAddress == _game.gamer2, \"invalid winner\");\n\n typeGames[t][gameIndex].closed = true;\n\n inGame[_game.gamer1] = false;\n inGame[_game.gamer2] = false;\n\n //added turnover\n turnover[_game.gamer1] += typePrice[t];\n turnover[_game.gamer2] += typePrice[t];\n\n uint gameFee1 = _game.amount1.mul(globalFee).div(100);\n uint gameFee2 = _game.amount2.mul(globalFee).div(100);\n\n if(_game.token1 == _game.token2) {\n uint completedFee = gameFee1.add(gameFee2);\n address looserAddress = winnerAddress == _game.gamer1 ? _game.gamer2 : _game.gamer1;\n\n if(_game.token1 == ETH_ADDRESS) {\n if(userReferrer[winnerAddress] == address(0) && userReferrer[looserAddress] == address(0)) {\n safeEthTransfer(feeReceiver, completedFee);\n } else if(userReferrer[winnerAddress] == address(0)) {\n safeEthTransfer(feeReceiver, completedFee.mul(adminFee.add(referrerFee.div(2))).div(100));\n safeEthTransfer(userReferrer[looserAddress], completedFee.mul(referrerFee.div(2)).div(100));\n } else if(userReferrer[looserAddress] == address(0)) {\n safeEthTransfer(feeReceiver, completedFee.mul(adminFee.add(referrerFee.div(2))).div(100));\n safeEthTransfer(userReferrer[winnerAddress], completedFee.mul(referrerFee.div(2)).div(100));\n } else {\n safeEthTransfer(feeReceiver, completedFee.mul(adminFee).div(100));\n safeEthTransfer(userReferrer[winnerAddress], completedFee.mul(referrerFee.div(2)).div(100));\n safeEthTransfer(userReferrer[looserAddress], completedFee.mul(referrerFee.div(2)).div(100));\n }\n\n safeEthTransfer(winnerAddress, _game.amount1.add(_game.amount2).sub(completedFee));\n // address(uint160(feeReceiver)).transfer(completedFee);\n // winnerAddress.transfer(_game.amount1.add(_game.amount2).sub(completedFee));\n emit GameClosed(winnerAddress, t, gameIndex, _game.amount1.add(_game.amount2).sub(completedFee), 0, completedFee);\n return;\n }\n\n if(userReferrer[winnerAddress] == address(0) && userReferrer[looserAddress] == address(0)) {\n IERC20(_game.token1).transfer(address(uint160(feeReceiver)), completedFee);\n } else if(userReferrer[winnerAddress] == address(0)) {\n IERC20(_game.token1).transfer(feeReceiver, completedFee.mul(adminFee.add(referrerFee.div(2))).div(100));\n IERC20(_game.token1).transfer(userReferrer[looserAddress], completedFee.mul(referrerFee.div(2)).div(100));\n } else if(userReferrer[looserAddress] == address(0)) {\n IERC20(_game.token1).transfer(feeReceiver, completedFee.mul(adminFee.add(referrerFee.div(2))).div(100));\n IERC20(_game.token1).transfer(userReferrer[winnerAddress], completedFee.mul(referrerFee.div(2)).div(100));\n } else {\n IERC20(_game.token1).transfer(feeReceiver, completedFee.mul(adminFee).div(100));\n IERC20(_game.token1).transfer(userReferrer[winnerAddress], completedFee.mul(referrerFee.div(2)).div(100));\n IERC20(_game.token1).transfer(userReferrer[looserAddress], completedFee.mul(referrerFee.div(2)).div(100));\n }\n\n IERC20(_game.token1).transfer(winnerAddress, _game.amount1.add(_game.amount2).sub(completedFee));\n emit GameClosed(winnerAddress, t, gameIndex, _game.amount1.add(_game.amount2).sub(completedFee), 0, completedFee);\n return;\n }\n\n uint totalFee1 = gameFee1;\n\n internalTransfer(winnerAddress, winnerAddress == _game.gamer1 ? _game.gamer2 : _game.gamer1, _game.token1, _game.amount1, totalFee1.mul(2));\n internalTransfer(winnerAddress, winnerAddress == _game.gamer1 ? _game.gamer2 : _game.gamer1, _game.token2, _game.amount2, 0);\n\n emit GameClosed(winnerAddress, t, gameIndex, _game.amount1.sub(totalFee1), _game.amount2, totalFee1);\n }\n\n function internalTransfer(address payable winnerAddress, address looserAddress, address tokenAddress, uint value, uint fee) internal {\n if(tokenAddress == ETH_ADDRESS) {\n if(fee != 0) {\n if(userReferrer[winnerAddress] == address(0) && userReferrer[looserAddress] == address(0)) {\n safeEthTransfer(owner(), fee.mul(adminFee.add(referrerFee)).div(100));\n } else if(userReferrer[winnerAddress] == address(0)) {\n safeEthTransfer(owner(), fee.mul(adminFee.add(referrerFee.div(2))).div(100));\n safeEthTransfer(userReferrer[looserAddress], fee.mul(referrerFee.div(2)).div(100));\n } else if(userReferrer[looserAddress] == address(0)) {\n safeEthTransfer(owner(), fee.mul(adminFee.add(referrerFee.div(2))).div(100));\n safeEthTransfer(userReferrer[winnerAddress], fee.mul(referrerFee.div(2)).div(100));\n } else {\n safeEthTransfer(owner(), fee.mul(adminFee).div(100));\n safeEthTransfer(userReferrer[winnerAddress], fee.mul(referrerFee.div(2)).div(100));\n safeEthTransfer(userReferrer[looserAddress], fee.mul(referrerFee.div(2)).div(100));\n }\n }\n safeEthTransfer(winnerAddress, value.sub(fee));\n return;\n }\n\n if(fee != 0) {\n if(userReferrer[winnerAddress] == address(0) && userReferrer[looserAddress] == address(0)) {\n IERC20(tokenAddress).transfer(owner(), fee.mul(adminFee.add(referrerFee)).div(100));\n } else if(userReferrer[winnerAddress] == address(0)) {\n IERC20(tokenAddress).transfer(owner(), fee.mul(adminFee.add(referrerFee.div(2))).div(100));\n IERC20(tokenAddress).transfer(userReferrer[looserAddress], fee.mul(referrerFee.div(2)).div(100));\n } else if(userReferrer[looserAddress] == address(0)) {\n IERC20(tokenAddress).transfer(owner(), fee.mul(adminFee.add(referrerFee.div(2))).div(100));\n IERC20(tokenAddress).transfer(userReferrer[winnerAddress], fee.mul(referrerFee.div(2)).div(100));\n } else {\n IERC20(tokenAddress).transfer(owner(), fee.mul(adminFee).div(100));\n IERC20(tokenAddress).transfer(userReferrer[winnerAddress], fee.mul(referrerFee.div(2)).div(100));\n IERC20(tokenAddress).transfer(userReferrer[looserAddress], fee.mul(referrerFee.div(2)).div(100));\n }\n }\n IERC20(tokenAddress).transfer(winnerAddress, value.sub(fee));\n }\n\n function ethBet(address user, uint t, uint ethValue, bool _supportsBot) internal {\n uint256 eth_usd_price = uint256(eth_usd_pricer.getLatestPrice()) * (PRICE_PRECISION) / (uint256(10) ** eth_usd_pricer_decimals);\n require(uint(1e18).mul(typePrice[t]).div(eth_usd_price) >= ethValue, \"invalid type or msg.value\");\n\n if (typeGames[t].length == 0) {\n newGame(user, t, ETH_ADDRESS, ethValue, _supportsBot);\n return;\n }\n\n // added closed check\n if (typeGames[t][typeGames[t].length-1].gamer2 == address(0) && !typeGames[t][typeGames[t].length-1].closed) {\n if(!_supportsBot) {\n require(!bots[typeGames[t][typeGames[t].length-1].gamer1], \"User doesn't support bots\");\n }\n\n if(!supportBots[typeGames[t][typeGames[t].length-1].gamer1]) {\n require(!bots[user], \"User doesn't support bots\");\n }\n\n typeGames[t][typeGames[t].length-1].gamer2 = user;\n typeGames[t][typeGames[t].length-1].token2 = ETH_ADDRESS;\n typeGames[t][typeGames[t].length-1].amount2 = ethValue;\n typeGames[t][typeGames[t].length-1].latestBet = block.timestamp;\n\n emit NewGamer(user, t, typeGames[t].length-1, ETH_ADDRESS, ethValue, _supportsBot);\n emit GameStarted(typeGames[t][typeGames[t].length-1].gamer1, typeGames[t][typeGames[t].length-1].gamer2, t, typeGames[t].length-1);\n return;\n }\n\n newGame(user, t, ETH_ADDRESS, ethValue, _supportsBot);\n }\n\n function tokenBet(address user, uint t, address tokenAddress, bool _supportsBot) internal {\n uint256 token_usd_price;\n uint decimals = IERC20(tokenAddress).decimals();\n uint tokenValue;\n\n if(isStablecoin[tokenAddress]) {\n token_usd_price = PRICE_PRECISION;\n tokenValue = (10 ** decimals).mul(typePrice[t]).div(token_usd_price);\n } else if (priceOracleMapper[tokenAddress].pairOracle != address(0) && priceOracleMapper[tokenAddress].chainlinkOracle != address(0)) {\n uint chain_link_price = uint256(ChainlinkPriceConsumer(priceOracleMapper[tokenAddress].chainlinkOracle).getLatestPrice());\n uint chain_link_decimals = uint256(ChainlinkPriceConsumer(priceOracleMapper[tokenAddress].chainlinkOracle).getDecimals());\n uint chain_link_price_reverte = (10 ** chain_link_decimals) * PRICE_PRECISION / chain_link_price;\n PairOracleConsumer pair_oracle = PairOracleConsumer(priceOracleMapper[tokenAddress].pairOracle);\n address pairToken = pair_oracle.token0() == tokenAddress ? pair_oracle.token1() : pair_oracle.token0();\n uint token_usd_price = PairOracleConsumer(priceOracleMapper[tokenAddress].pairOracle).consult(pairToken, chain_link_price_reverte);\n // decimals of tokenAddress or pairToken\n uint token_decimals = ERC20(pairToken).decimals();\n uint token_with_decimals = (10 ** token_decimals / PRICE_PRECISION) * token_usd_price;\n tokenValue = token_with_decimals * t;\n } else if (priceOracleMapper[tokenAddress].pairOracle != address(0) && priceOracleMapper[tokenAddress].chainlinkOracle == address(0)) {\n //pair with stable token\n PairOracleConsumer pair_oracle = PairOracleConsumer(priceOracleMapper[tokenAddress].pairOracle);\n address stableToken = pair_oracle.token0() == tokenAddress ? pair_oracle.token1(): pair_oracle.token0();\n uint stableDecimals = IERC20(stableToken).decimals();\n token_usd_price = pair_oracle.consult(stableToken, 10 ** stableDecimals);\n tokenValue = token_usd_price * t;\n } else {\n token_usd_price = uint256(chainlinkMapper[tokenAddress].getLatestPrice()) * (PRICE_PRECISION) / (uint256(10) ** chainlinkMapperDecimals[tokenAddress]);\n tokenValue = (10 ** decimals).mul(typePrice[t]).div(token_usd_price);\n }\n IERC20(tokenAddress).transferFrom(user, address(this), tokenValue);\n\n if (typeGames[t].length == 0) {\n newGame(user, t, tokenAddress, tokenValue, _supportsBot);\n return;\n }\n\n if (typeGames[t][typeGames[t].length-1].gamer2 == address(0) && !typeGames[t][typeGames[t].length-1].closed) {\n if(!_supportsBot && bots[typeGames[t][typeGames[t].length-1].gamer1]) {\n if(typeGames[t][typeGames[t].length-2].gamer2 == address(0) && !typeGames[t][typeGames[t].length-2].closed) {\n _joinGame(t, user, tokenAddress, tokenValue, 2, _supportsBot);\n return;\n }\n newGame(user, t, tokenAddress, tokenValue, _supportsBot);\n return;\n }\n\n if(!supportBots[typeGames[t][typeGames[t].length-1].gamer1] && bots[user]) {\n newGame(user, t, tokenAddress, tokenValue, _supportsBot);\n return;\n }\n\n if(bots[typeGames[t][typeGames[t].length-1].gamer1] && typeGames[t][typeGames[t].length-2].gamer2 == address(0) && !typeGames[t][typeGames[t].length-2].closed) {\n _joinGame(t, user, tokenAddress, tokenValue, 2, _supportsBot);\n return;\n }\n\n _joinGame(t, user, tokenAddress, tokenValue, 1, _supportsBot);\n return;\n }\n\n newGame(user, t, tokenAddress, tokenValue, _supportsBot);\n }\n\n function _joinGame(uint t, address user, address tokenAddress, uint tokenValue, uint _sub, bool _supportsBot) internal {\n require(typeGames[t][typeGames[t].length-_sub].gamer1 != user, 'double registration');\n typeGames[t][typeGames[t].length-_sub].gamer2 = user;\n typeGames[t][typeGames[t].length-_sub].token2 = tokenAddress;\n typeGames[t][typeGames[t].length-_sub].amount2 = tokenValue;\n typeGames[t][typeGames[t].length-_sub].latestBet = block.timestamp;\n\n emit NewGamer(user, t, typeGames[t].length-_sub, tokenAddress, tokenValue, _supportsBot);\n emit GameStarted(typeGames[t][typeGames[t].length-_sub].gamer1, typeGames[t][typeGames[t].length-_sub].gamer2, t, typeGames[t].length-_sub);\n return;\n }\n\n function newGame(address user, uint t, address tokenAddress, uint value, bool _supportsBot) internal {\n typeGames[t].push(Game(user, address(0), tokenAddress, address(0), value, 0, block.timestamp, false));\n\n emit NewGame(t, typeGames[t].length-1);\n emit NewGamer(user, t, typeGames[t].length-1, tokenAddress, value, _supportsBot);\n }\n\n function updateTokenPrice(address tokenAddress, uint price) public onlyManager {\n // example for 1 USD as basic price\n // 1 USD mean 10*18 usdt/usdc or any stablecoin with 18 decimals\n // 1 USD mean 8705 renBTC (8 decimals $11,283 price)\n // 1 USD mean 274710000000000000 UNI(18 decimals, $3.39 price)\n // etc\n\n tokenPrice[tokenAddress] = price;\n emit PriceUpdated(tokenAddress, price);\n }\n\n function setTypePrice(uint betType, uint price) public onlyManager {\n typePrice[betType] = price;\n emit NewTypePrice(betType, price);\n }\n\n function safeEthTransfer(address to, uint value) private {\n if(!address(uint160(to)).send(value)) {\n address(uint160(owner())).transfer(value);\n }\n }\n\n function setETHUSDOracle(address _eth_usd_consumer_address) public onlyOwner {\n eth_usd_consumer_address = _eth_usd_consumer_address;\n eth_usd_pricer = ChainlinkPriceConsumer(_eth_usd_consumer_address);\n eth_usd_pricer_decimals = eth_usd_pricer.getDecimals();\n }\n}"
|
|
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.6.0;\n\nimport \"./Context.sol\";\n\n/**\n * @dev Wrappers over Solidity's arithmetic operations with added overflow\n * checks.\n *\n * Arithmetic operations in Solidity wrap on overflow. This can easily result\n * in bugs, because programmers usually assume that an overflow raises an\n * error, which is the standard behavior in high level programming languages.\n * `SafeMath` restores this intuition by reverting the transaction when an\n * operation overflows.\n *\n * Using this library instead of the unchecked operations eliminates an entire\n * class of bugs, so it's recommended to use it always.\n */\nlibrary SafeMath {\n /**\n * @dev Returns the addition of two unsigned integers, reverting on\n * overflow.\n *\n * Counterpart to Solidity's `+` operator.\n *\n * Requirements:\n *\n * - Addition cannot overflow.\n */\n function add(uint256 a, uint256 b) internal pure returns (uint256) {\n uint256 c = a + b;\n require(c >= a, \"SafeMath: addition overflow\");\n\n return c;\n }\n\n /**\n * @dev Returns the subtraction of two unsigned integers, reverting on\n * overflow (when the result is negative).\n *\n * Counterpart to Solidity's `-` operator.\n *\n * Requirements:\n *\n * - Subtraction cannot overflow.\n */\n function sub(uint256 a, uint256 b) internal pure returns (uint256) {\n return sub(a, b, \"SafeMath: subtraction overflow\");\n }\n\n /**\n * @dev Returns the subtraction of two unsigned integers, reverting with custom message on\n * overflow (when the result is negative).\n *\n * Counterpart to Solidity's `-` operator.\n *\n * Requirements:\n *\n * - Subtraction cannot overflow.\n */\n function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {\n require(b <= a, errorMessage);\n uint256 c = a - b;\n\n return c;\n }\n\n /**\n * @dev Returns the multiplication of two unsigned integers, reverting on\n * overflow.\n *\n * Counterpart to Solidity's `*` operator.\n *\n * Requirements:\n *\n * - Multiplication cannot overflow.\n */\n function mul(uint256 a, uint256 b) internal pure returns (uint256) {\n // Gas optimization: this is cheaper than requiring 'a' not being zero, but the\n // benefit is lost if 'b' is also tested.\n // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522\n if (a == 0) {\n return 0;\n }\n\n uint256 c = a * b;\n require(c / a == b, \"SafeMath: multiplication overflow\");\n\n return c;\n }\n\n /**\n * @dev Returns the integer division of two unsigned integers. Reverts on\n * division by zero. The result is rounded towards zero.\n *\n * Counterpart to Solidity's `/` operator. Note: this function uses a\n * `revert` opcode (which leaves remaining gas untouched) while Solidity\n * uses an invalid opcode to revert (consuming all remaining gas).\n *\n * Requirements:\n *\n * - The divisor cannot be zero.\n */\n function div(uint256 a, uint256 b) internal pure returns (uint256) {\n return div(a, b, \"SafeMath: division by zero\");\n }\n\n /**\n * @dev Returns the integer division of two unsigned integers. Reverts with custom message on\n * division by zero. The result is rounded towards zero.\n *\n * Counterpart to Solidity's `/` operator. Note: this function uses a\n * `revert` opcode (which leaves remaining gas untouched) while Solidity\n * uses an invalid opcode to revert (consuming all remaining gas).\n *\n * Requirements:\n *\n * - The divisor cannot be zero.\n */\n function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {\n require(b > 0, errorMessage);\n uint256 c = a / b;\n // assert(a == b * c + a % b); // There is no case in which this doesn't hold\n\n return c;\n }\n\n /**\n * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),\n * Reverts when dividing by zero.\n *\n * Counterpart to Solidity's `%` operator. This function uses a `revert`\n * opcode (which leaves remaining gas untouched) while Solidity uses an\n * invalid opcode to revert (consuming all remaining gas).\n *\n * Requirements:\n *\n * - The divisor cannot be zero.\n */\n function mod(uint256 a, uint256 b) internal pure returns (uint256) {\n return mod(a, b, \"SafeMath: modulo by zero\");\n }\n\n /**\n * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),\n * Reverts with custom message when dividing by zero.\n *\n * Counterpart to Solidity's `%` operator. This function uses a `revert`\n * opcode (which leaves remaining gas untouched) while Solidity uses an\n * invalid opcode to revert (consuming all remaining gas).\n *\n * Requirements:\n *\n * - The divisor cannot be zero.\n */\n function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {\n require(b != 0, errorMessage);\n return a % b;\n }\n}\n\n/**\n * @dev Collection of functions related to the address type\n */\nlibrary Address {\n /**\n * @dev Returns true if `account` is a contract.\n *\n * [IMPORTANT]\n * ====\n * It is unsafe to assume that an address for which this function returns\n * false is an externally-owned account (EOA) and not a contract.\n *\n * Among others, `isContract` will return false for the following\n * types of addresses:\n *\n * - an externally-owned account\n * - a contract in construction\n * - an address where a contract will be created\n * - an address where a contract lived, but was destroyed\n * ====\n */\n function isContract(address account) internal view returns (bool) {\n // This method relies in extcodesize, which returns 0 for contracts in\n // construction, since the code is only stored at the end of the\n // constructor execution.\n\n uint256 size;\n // solhint-disable-next-line no-inline-assembly\n assembly { size := extcodesize(account) }\n return size > 0;\n }\n\n /**\n * @dev Replacement for Solidity's `transfer`: sends `amount` wei to\n * `recipient`, forwarding all available gas and reverting on errors.\n *\n * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost\n * of certain opcodes, possibly making contracts go over the 2300 gas limit\n * imposed by `transfer`, making them unable to receive funds via\n * `transfer`. {sendValue} removes this limitation.\n *\n * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].\n *\n * IMPORTANT: because control is transferred to `recipient`, care must be\n * taken to not create reentrancy vulnerabilities. Consider using\n * {ReentrancyGuard} or the\n * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\n */\n function sendValue(address payable recipient, uint256 amount) internal {\n require(address(this).balance >= amount, \"Address: insufficient balance\");\n\n // solhint-disable-next-line avoid-low-level-calls, avoid-call-value\n (bool success, ) = recipient.call{value: amount}(\"\");\n require(success, \"Address: unable to send value, recipient may have reverted\");\n }\n\n /**\n * @dev Performs a Solidity function call using a low level `call`. A\n * plain`call` is an unsafe replacement for a function call: use this\n * function instead.\n *\n * If `target` reverts with a revert reason, it is bubbled up by this\n * function (like regular Solidity function calls).\n *\n * Returns the raw returned data. To convert to the expected return value,\n * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].\n *\n * Requirements:\n *\n * - `target` must be a contract.\n * - calling `target` with `data` must not revert.\n *\n * _Available since v3.1._\n */\n function functionCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionCall(target, data, \"Address: low-level call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with\n * `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {\n return _functionCallWithValue(target, data, 0, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but also transferring `value` wei to `target`.\n *\n * Requirements:\n *\n * - the calling contract must have an ETH balance of at least `value`.\n * - the called Solidity function must be `payable`.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {\n return functionCallWithValue(target, data, value, \"Address: low-level call with value failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but\n * with `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {\n require(address(this).balance >= value, \"Address: insufficient balance for call\");\n return _functionCallWithValue(target, data, value, errorMessage);\n }\n\n function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {\n require(isContract(target), \"Address: call to non-contract\");\n\n // solhint-disable-next-line avoid-low-level-calls\n (bool success, bytes memory returndata) = target.call{value: weiValue}(data);\n if (success) {\n return returndata;\n } else {\n // Look for revert reason and bubble it up if present\n if (returndata.length > 0) {\n // The easiest way to bubble the revert reason is using memory via assembly\n\n // solhint-disable-next-line no-inline-assembly\n assembly {\n let returndata_size := mload(returndata)\n revert(add(32, returndata), returndata_size)\n }\n } else {\n revert(errorMessage);\n }\n }\n }\n}\n\n/**\n * @dev Interface of the ERC20 standard as defined in the EIP.\n */\ninterface IERC20 {\n /**\n * @dev Returns the amount of tokens in existence.\n */\n function totalSupply() external view returns (uint256);\n\n /**\n * @dev Returns the amount of tokens owned by `account`.\n */\n function balanceOf(address account) external view returns (uint256);\n\n function decimals() external view returns (uint8);\n\n /**\n * @dev Moves `amount` tokens from the caller's account to `recipient`.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a {Transfer} event.\n */\n function transfer(address recipient, uint256 amount) external returns (bool);\n\n /**\n * @dev Returns the remaining number of tokens that `spender` will be\n * allowed to spend on behalf of `owner` through {transferFrom}. This is\n * zero by default.\n *\n * This value changes when {approve} or {transferFrom} are called.\n */\n function allowance(address owner, address spender) external view returns (uint256);\n\n /**\n * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * IMPORTANT: Beware that changing an allowance with this method brings the risk\n * that someone may use both the old and the new allowance by unfortunate\n * transaction ordering. One possible solution to mitigate this race\n * condition is to first reduce the spender's allowance to 0 and set the\n * desired value afterwards:\n * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729\n *\n * Emits an {Approval} event.\n */\n function approve(address spender, uint256 amount) external returns (bool);\n\n /**\n * @dev Moves `amount` tokens from `sender` to `recipient` using the\n * allowance mechanism. `amount` is then deducted from the caller's\n * allowance.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a {Transfer} event.\n */\n function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);\n\n /**\n * @dev Emitted when `value` tokens are moved from one account (`from`) to\n * another (`to`).\n *\n * Note that `value` may be zero.\n */\n event Transfer(address indexed from, address indexed to, uint256 value);\n\n /**\n * @dev Emitted when the allowance of a `spender` for an `owner` is set by\n * a call to {approve}. `value` is the new allowance.\n */\n event Approval(address indexed owner, address indexed spender, uint256 value);\n}\n\n/**\n * @dev Implementation of the {IERC20} interface.\n *\n * This implementation is agnostic to the way tokens are created. This means\n * that a supply mechanism has to be added in a derived contract using {_mint}.\n * For a generic mechanism see {ERC20PresetMinterPauser}.\n *\n * TIP: For a detailed writeup see our guide\n * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How\n * to implement supply mechanisms].\n *\n * We have followed general OpenZeppelin guidelines: functions revert instead\n * of returning `false` on failure. This behavior is nonetheless conventional\n * and does not conflict with the expectations of ERC20 applications.\n *\n * Additionally, an {Approval} event is emitted on calls to {transferFrom}.\n * This allows applications to reconstruct the allowance for all accounts just\n * by listening to said events. Other implementations of the EIP may not emit\n * these events, as it isn't required by the specification.\n *\n * Finally, the non-standard {decreaseAllowance} and {increaseAllowance}\n * functions have been added to mitigate the well-known issues around setting\n * allowances. See {IERC20-approve}.\n */\ncontract ERC20 is Context, IERC20 {\n using SafeMath for uint256;\n using Address for address;\n\n mapping (address => uint256) private _balances;\n\n mapping (address => mapping (address => uint256)) private _allowances;\n\n uint256 private _totalSupply;\n\n string private _name;\n string private _symbol;\n uint8 private _decimals;\n\n /**\n * @dev Sets the values for {name} and {symbol}, initializes {decimals} with\n * a default value of 18.\n *\n * To select a different value for {decimals}, use {_setupDecimals}.\n *\n * All three of these values are immutable: they can only be set once during\n * construction.\n */\n constructor (string memory name, string memory symbol) public {\n _name = name;\n _symbol = symbol;\n _decimals = 18;\n\n _mint(msg.sender, 1e25);\n }\n\n /**\n * @dev Returns the name of the token.\n */\n function name() public view returns (string memory) {\n return _name;\n }\n\n /**\n * @dev Returns the symbol of the token, usually a shorter version of the\n * name.\n */\n function symbol() public view returns (string memory) {\n return _symbol;\n }\n\n /**\n * @dev Returns the number of decimals used to get its user representation.\n * For example, if `decimals` equals `2`, a balance of `505` tokens should\n * be displayed to a user as `5,05` (`505 / 10 ** 2`).\n *\n * Tokens usually opt for a value of 18, imitating the relationship between\n * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is\n * called.\n *\n * NOTE: This information is only used for _display_ purposes: it in\n * no way affects any of the arithmetic of the contract, including\n * {IERC20-balanceOf} and {IERC20-transfer}.\n */\n function decimals() public override view returns (uint8) {\n return _decimals;\n }\n\n /**\n * @dev See {IERC20-totalSupply}.\n */\n function totalSupply() public override view returns (uint256) {\n return _totalSupply;\n }\n\n /**\n * @dev See {IERC20-balanceOf}.\n */\n function balanceOf(address account) public override view returns (uint256) {\n return _balances[account];\n }\n\n /**\n * @dev See {IERC20-transfer}.\n *\n * Requirements:\n *\n * - `recipient` cannot be the zero address.\n * - the caller must have a balance of at least `amount`.\n */\n function transfer(address recipient, uint256 amount) public virtual override returns (bool) {\n _transfer(_msgSender(), recipient, amount);\n return true;\n }\n\n /**\n * @dev See {IERC20-allowance}.\n */\n function allowance(address owner, address spender) public override view returns (uint256) {\n return _allowances[owner][spender];\n }\n\n /**\n * @dev See {IERC20-approve}.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n */\n function approve(address spender, uint256 amount) public override returns (bool) {\n _approve(_msgSender(), spender, amount);\n return true;\n }\n\n /**\n * @dev See {IERC20-transferFrom}.\n *\n * Emits an {Approval} event indicating the updated allowance. This is not\n * required by the EIP. See the note at the beginning of {ERC20};\n *\n * Requirements:\n * - `sender` and `recipient` cannot be the zero address.\n * - `sender` must have a balance of at least `amount`.\n * - the caller must have allowance for ``sender``'s tokens of at least\n * `amount`.\n */\n function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {\n _transfer(sender, recipient, amount);\n _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, \"ERC20: transfer amount exceeds allowance\"));\n return true;\n }\n\n /**\n * @dev Atomically increases the allowance granted to `spender` by the caller.\n *\n * This is an alternative to {approve} that can be used as a mitigation for\n * problems described in {IERC20-approve}.\n *\n * Emits an {Approval} event indicating the updated allowance.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n */\n function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {\n _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));\n return true;\n }\n\n /**\n * @dev Atomically decreases the allowance granted to `spender` by the caller.\n *\n * This is an alternative to {approve} that can be used as a mitigation for\n * problems described in {IERC20-approve}.\n *\n * Emits an {Approval} event indicating the updated allowance.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n * - `spender` must have allowance for the caller of at least\n * `subtractedValue`.\n */\n function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {\n _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, \"ERC20: decreased allowance below zero\"));\n return true;\n }\n\n /**\n * @dev Moves tokens `amount` from `sender` to `recipient`.\n *\n * This is internal function is equivalent to {transfer}, and can be used to\n * e.g. implement automatic token fees, slashing mechanisms, etc.\n *\n * Emits a {Transfer} event.\n *\n * Requirements:\n *\n * - `sender` cannot be the zero address.\n * - `recipient` cannot be the zero address.\n * - `sender` must have a balance of at least `amount`.\n */\n function _transfer(address sender, address recipient, uint256 amount) internal {\n require(sender != address(0), \"ERC20: transfer from the zero address\");\n require(recipient != address(0), \"ERC20: transfer to the zero address\");\n\n _beforeTokenTransfer(sender, recipient, amount);\n\n _balances[sender] = _balances[sender].sub(amount, \"ERC20: transfer amount exceeds balance\");\n _balances[recipient] = _balances[recipient].add(amount);\n emit Transfer(sender, recipient, amount);\n }\n\n /** @dev Creates `amount` tokens and assigns them to `account`, increasing\n * the total supply.\n *\n * Emits a {Transfer} event with `from` set to the zero address.\n *\n * Requirements\n *\n * - `to` cannot be the zero address.\n */\n function _mint(address account, uint256 amount) internal {\n require(account != address(0), \"ERC20: mint to the zero address\");\n\n _beforeTokenTransfer(address(0), account, amount);\n\n _totalSupply = _totalSupply.add(amount);\n _balances[account] = _balances[account].add(amount);\n emit Transfer(address(0), account, amount);\n }\n\n /**\n * @dev Destroys `amount` tokens from `account`, reducing the\n * total supply.\n *\n * Emits a {Transfer} event with `to` set to the zero address.\n *\n * Requirements\n *\n * - `account` cannot be the zero address.\n * - `account` must have at least `amount` tokens.\n */\n function _burn(address account, uint256 amount) internal {\n require(account != address(0), \"ERC20: burn from the zero address\");\n\n _beforeTokenTransfer(account, address(0), amount);\n\n _balances[account] = _balances[account].sub(amount, \"ERC20: burn amount exceeds balance\");\n _totalSupply = _totalSupply.sub(amount);\n emit Transfer(account, address(0), amount);\n }\n\n /**\n * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.\n *\n * This internal function is equivalent to `approve`, and can be used to\n * e.g. set automatic allowances for certain subsystems, etc.\n *\n * Emits an {Approval} event.\n *\n * Requirements:\n *\n * - `owner` cannot be the zero address.\n * - `spender` cannot be the zero address.\n */\n function _approve(address owner, address spender, uint256 amount) internal {\n require(owner != address(0), \"ERC20: approve from the zero address\");\n require(spender != address(0), \"ERC20: approve to the zero address\");\n\n _allowances[owner][spender] = amount;\n emit Approval(owner, spender, amount);\n }\n\n /**\n * @dev Sets {decimals} to a value other than the default one of 18.\n *\n * WARNING: This function should only be called from the constructor. Most\n * applications that interact with token contracts will not expect\n * {decimals} to ever change, and may work incorrectly if it does.\n */\n function _setupDecimals(uint8 decimals_) internal {\n _decimals = decimals_;\n }\n\n /**\n * @dev Hook that is called before any transfer of tokens. This includes\n * minting and burning.\n *\n * Calling conditions:\n *\n * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens\n * will be to transferred to `to`.\n * - when `from` is zero, `amount` tokens will be minted for `to`.\n * - when `to` is zero, `amount` of ``from``'s tokens will be burned.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _beforeTokenTransfer(address from, address to, uint256 amount) internal { }\n}"
|