File size: 70,956 Bytes
f998fcd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
{
  "language": "Solidity",
  "sources": {
    "contracts/BrewlabsFarm.sol": {
      "content": "// SPDX-License-Identifier: MIT\r\npragma solidity ^0.8.0;\r\n\r\nimport '@openzeppelin/contracts/access/Ownable.sol';\r\nimport '@openzeppelin/contracts/utils/math/SafeMath.sol';\r\nimport '@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol';\r\nimport \"@openzeppelin/contracts/security/ReentrancyGuard.sol\";\r\n\r\nimport \"./libs/IUniRouter02.sol\";\r\nimport \"./libs/IWETH.sol\";\r\n\r\n// BrewlabsFarm is the master of brews. He can make brews and he is a fair guy.\r\n//\r\n// Note that it's ownable and the owner wields tremendous power. The ownership\r\n// will be transferred to a governance smart contract once brews is sufficiently\r\n// distributed and the community can show to govern itself.\r\n//\r\n// Have fun reading it. Hopefully it's bug-free. God bless.\r\ncontract BrewlabsFarm is Ownable, ReentrancyGuard {\r\n    using SafeMath for uint256;\r\n    using SafeERC20 for IERC20;\r\n\r\n    // Info of each user.\r\n    struct UserInfo {\r\n        uint256 amount;         // How many LP tokens the user has provided.\r\n        uint256 rewardDebt;     // Reward debt. See explanation below.\r\n        uint256 reflectionDebt;     // Reflection debt. See explanation below.\r\n        //\r\n        // We do some fancy math here. Basically, any point in time, the amount of brewss\r\n        // entitled to a user but is pending to be distributed is:\r\n        //\r\n        //   pending reward = (user.amount * pool.accTokenPerShare) - user.rewardDebt\r\n        //\r\n        // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens:\r\n        //   1. The pool's `accTokenPerShare` (and `lastRewardBlock`) gets updated.\r\n        //   2. User receives the pending reward sent to his/her address.\r\n        //   3. User's `amount` gets updated.\r\n        //   4. User's `rewardDebt` gets updated.\r\n    }\r\n\r\n    // Info of each pool.\r\n    struct PoolInfo {\r\n        IERC20 lpToken;           // Address of LP token contract.\r\n        uint256 allocPoint;       // How many allocation points assigned to this pool. brewss to distribute per block.\r\n        uint256 duration;\r\n        uint256 startBlock;\r\n        uint256 bonusEndBlock;\r\n        uint256 lastRewardBlock;  // Last block number that brewss distribution occurs.\r\n        uint256 accTokenPerShare;   // Accumulated brewss per share, times 1e12. See below.\r\n        uint256 accReflectionPerShare;   // Accumulated brewss per share, times 1e12. See below.\r\n        uint256 lastReflectionPerPoint;\r\n        uint16 depositFee;      // Deposit fee in basis points\r\n        uint16 withdrawFee;      // Deposit fee in basis points\r\n    }\r\n\r\n    struct SwapSetting {\r\n        IERC20 lpToken;\r\n        address swapRouter;\r\n        address[] earnedToToken0;\r\n        address[] earnedToToken1;\r\n        address[] reflectionToToken0;\r\n        address[] reflectionToToken1;\r\n        bool enabled;\r\n    }\r\n\r\n    // The brews TOKEN!\r\n    IERC20 public brews;\r\n    // Reflection Token\r\n    address public reflectionToken;\r\n    uint256 public accReflectionPerPoint;\r\n    bool public hasDividend;\r\n\r\n    // brews tokens created per block.\r\n    uint256 public rewardPerBlock;\r\n    // Bonus muliplier for early brews makers.\r\n    uint256 public constant BONUS_MULTIPLIER = 1;\r\n    // Deposit Fee address\r\n    address public feeAddress;\r\n    address public buyBackWallet = 0xE1f1dd010BBC2860F81c8F90Ea4E38dB949BB16F;\r\n    uint256 public performanceFee = 0.00089 ether;\r\n\r\n    // Info of each pool.\r\n    PoolInfo[] public poolInfo;\r\n    SwapSetting[] public swapSettings;\r\n    uint256[] public totalStaked;\r\n\r\n    // Info of each user that stakes LP tokens.\r\n    mapping(uint256 => mapping(address => UserInfo)) public userInfo;\r\n    // Total allocation points. Must be the sum of all allocation points in all pools.\r\n    uint256 public totalAllocPoint = 0;\r\n    // The block number when brews mining starts.\r\n    uint256 public startBlock;\r\n\r\n    uint256 private totalEarned;\r\n    uint256 private totalRewardStaked;\r\n    uint256 private totalReflectionStaked;\r\n    uint256 private totalReflections;\r\n    uint256 private reflectionDebt;\r\n\r\n    event Deposit(address indexed user, uint256 indexed pid, uint256 amount);\r\n    event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);\r\n    event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount);\r\n    event SetFeeAddress(address indexed user, address indexed newAddress);\r\n    event SetBuyBackWallet(address indexed user, address newAddress);\r\n    event SetPerformanceFee(uint256 fee);\r\n    event UpdateEmissionRate(address indexed user, uint256 rewardPerBlock);\r\n\r\n    constructor(IERC20 _brews, address _reflectionToken, uint256 _rewardPerBlock, bool _hasDividend) {\r\n        brews = _brews;\r\n        reflectionToken = _reflectionToken;\r\n        rewardPerBlock = _rewardPerBlock;\r\n        hasDividend = _hasDividend;\r\n\r\n        feeAddress = msg.sender;\r\n        startBlock = block.number.add(30 * 6426); // after 30 days\r\n    }\r\n\r\n    mapping(IERC20 => bool) public poolExistence;\r\n    modifier nonDuplicated(IERC20 _lpToken) {\r\n        require(poolExistence[_lpToken] == false, \"nonDuplicated: duplicated\");\r\n        _;\r\n    }\r\n\r\n    function poolLength() external view returns (uint256) {\r\n        return poolInfo.length;\r\n    }\r\n\r\n    // Add a new lp to the pool. Can only be called by the owner.\r\n    function add(uint256 _allocPoint, IERC20 _lpToken, uint16 _depositFee, uint16 _withdrawFee, uint256 _duration, bool _withUpdate) external onlyOwner nonDuplicated(_lpToken) {\r\n        require(_depositFee <= 10000, \"add: invalid deposit fee basis points\");\r\n        require(_withdrawFee <= 10000, \"add: invalid withdraw fee basis points\");\r\n\r\n        if (_withUpdate) {\r\n            massUpdatePools();\r\n        }\r\n        \r\n        uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock;\r\n        totalAllocPoint = totalAllocPoint.add(_allocPoint);\r\n        poolExistence[_lpToken] = true;\r\n        poolInfo.push(PoolInfo({\r\n            lpToken : _lpToken,\r\n            allocPoint : _allocPoint,\r\n            duration: _duration,\r\n            startBlock: lastRewardBlock,\r\n            bonusEndBlock: lastRewardBlock.add(_duration.mul(6426)),\r\n            lastRewardBlock : lastRewardBlock,\r\n            accTokenPerShare : 0,\r\n            accReflectionPerShare : 0,\r\n            lastReflectionPerPoint: 0,\r\n            depositFee : _depositFee,\r\n            withdrawFee: _withdrawFee\r\n        }));\r\n\r\n        swapSettings.push();\r\n        swapSettings[swapSettings.length - 1].lpToken = _lpToken;\r\n\r\n        totalStaked.push(0);\r\n    }\r\n\r\n    // Update the given pool's brews allocation point and deposit fee. Can only be called by the owner.\r\n    function set(uint256 _pid, uint256 _allocPoint, uint16 _depositFee, uint16 _withdrawFee, uint256 _duration, bool _withUpdate) external onlyOwner {\r\n        require(_depositFee <= 10000, \"set: invalid deposit fee basis points\");\r\n        require(_withdrawFee <= 10000, \"set: invalid deposit fee basis points\");\r\n        if(poolInfo[_pid].bonusEndBlock > block.number) {\r\n            require(poolInfo[_pid].startBlock.add(_duration.mul(6426)) > block.number, \"set: invalid duration\");\r\n        }\r\n\r\n        if (_withUpdate) {\r\n            massUpdatePools();\r\n        }\r\n        \r\n        totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint);\r\n\r\n        poolInfo[_pid].allocPoint = _allocPoint;\r\n        poolInfo[_pid].depositFee = _depositFee;\r\n        poolInfo[_pid].withdrawFee = _withdrawFee;\r\n        poolInfo[_pid].duration = _duration;\r\n\r\n        if(poolInfo[_pid].bonusEndBlock < block.number) {\r\n            if (!_withUpdate) updatePool(_pid);\r\n            \r\n            poolInfo[_pid].startBlock = block.number;\r\n            poolInfo[_pid].bonusEndBlock = block.number.add(_duration.mul(6426));\r\n        } else {\r\n            poolInfo[_pid].bonusEndBlock = poolInfo[_pid].startBlock.add(_duration.mul(6426));\r\n        }\r\n    }\r\n\r\n    // Update the given pool's compound parameters. Can only be called by the owner.\r\n    function setSwapSetting(\r\n        uint256 _pid, \r\n        address _uniRouter, \r\n        address[] memory _earnedToToken0, \r\n        address[] memory _earnedToToken1, \r\n        address[] memory _reflectionToToken0, \r\n        address[] memory _reflectionToToken1, \r\n        bool _enabled\r\n    ) external onlyOwner {\r\n        SwapSetting storage swapSetting = swapSettings[_pid];\r\n\r\n        swapSetting.enabled = _enabled;\r\n        swapSetting.swapRouter = _uniRouter;\r\n        swapSetting.earnedToToken0 = _earnedToToken0;\r\n        swapSetting.earnedToToken1 = _earnedToToken1;\r\n        swapSetting.reflectionToToken0 = _reflectionToToken0;\r\n        swapSetting.reflectionToToken1 = _reflectionToToken1;\r\n    }\r\n\r\n    // Return reward multiplier over the given _from to _to block.\r\n    function getMultiplier(uint256 _from, uint256 _to, uint256 _endBlock) public pure returns (uint256) {\r\n        if(_from > _endBlock) return 0;\r\n        if(_to > _endBlock) {\r\n            return _endBlock.sub(_from).mul(BONUS_MULTIPLIER);    \r\n        }\r\n\r\n        return _to.sub(_from).mul(BONUS_MULTIPLIER);\r\n    }\r\n\r\n    // View function to see pending brews on frontend.\r\n    function pendingRewards(uint256 _pid, address _user) external view returns (uint256) {\r\n        PoolInfo storage pool = poolInfo[_pid];\r\n        UserInfo storage user = userInfo[_pid][_user];\r\n\r\n        uint256 accTokenPerShare = pool.accTokenPerShare;\r\n        uint256 lpSupply = pool.lpToken.balanceOf(address(this));\r\n        if (block.number > pool.lastRewardBlock && lpSupply != 0) {\r\n            uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number, pool.bonusEndBlock);\r\n            uint256 brewsReward = multiplier.mul(rewardPerBlock).mul(pool.allocPoint).div(totalAllocPoint);\r\n            accTokenPerShare = accTokenPerShare.add(brewsReward.mul(1e12).div(lpSupply));\r\n        }\r\n        return user.amount.mul(accTokenPerShare).div(1e12).sub(user.rewardDebt);\r\n    }\r\n\r\n    function pendingReflections(uint256 _pid, address _user) external view returns (uint256) {\r\n        PoolInfo storage pool = poolInfo[_pid];\r\n        UserInfo storage user = userInfo[_pid][_user];\r\n\r\n        uint256 accReflectionPerShare = pool.accReflectionPerShare;\r\n        uint256 lpSupply = pool.lpToken.balanceOf(address(this));\r\n        if(reflectionToken == address(pool.lpToken)) lpSupply = totalReflectionStaked;\r\n        if (block.number > pool.lastRewardBlock && lpSupply != 0 && hasDividend) {\r\n            uint256 reflectionAmt = availableDividendTokens();\r\n            if(reflectionAmt > totalReflections) {\r\n                reflectionAmt = reflectionAmt.sub(totalReflections);\r\n            } else reflectionAmt = 0;\r\n            \r\n            uint256 _accReflectionPerPoint = accReflectionPerPoint.add(reflectionAmt.mul(1e12).div(totalAllocPoint));\r\n            \r\n            accReflectionPerShare = pool.accReflectionPerShare.add(\r\n                pool.allocPoint.mul(_accReflectionPerPoint.sub(pool.lastReflectionPerPoint)).div(lpSupply)\r\n            );\r\n        }\r\n        return user.amount.mul(accReflectionPerShare).div(1e12).sub(user.reflectionDebt);\r\n    } \r\n\r\n    // Update reward variables for all pools. Be careful of gas spending!\r\n    function massUpdatePools() public {\r\n        uint256 length = poolInfo.length;\r\n        for (uint256 pid = 0; pid < length; pid++) {\r\n            updatePool(pid);\r\n        }\r\n    }\r\n\r\n    // Update reward variables of the given pool to be up-to-date.\r\n    function updatePool(uint256 _pid) public {\r\n        PoolInfo storage pool = poolInfo[_pid];\r\n        if (block.number <= pool.lastRewardBlock) {\r\n            return;\r\n        }\r\n        uint256 lpSupply = pool.lpToken.balanceOf(address(this));\r\n        if(reflectionToken == address(pool.lpToken)) lpSupply = totalReflectionStaked;\r\n        if (lpSupply == 0 || pool.allocPoint == 0) {\r\n            pool.lastRewardBlock = block.number;\r\n            return;\r\n        }\r\n\r\n        uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number, pool.bonusEndBlock);\r\n        uint256 brewsReward = multiplier.mul(rewardPerBlock).mul(pool.allocPoint).div(totalAllocPoint);\r\n        pool.accTokenPerShare = pool.accTokenPerShare.add(brewsReward.mul(1e12).div(lpSupply));\r\n\r\n        if(hasDividend) {\r\n            uint256 reflectionAmt = availableDividendTokens();\r\n            if(reflectionAmt > totalReflections) {\r\n                reflectionAmt = reflectionAmt.sub(totalReflections);\r\n            } else reflectionAmt = 0;\r\n\r\n            accReflectionPerPoint = accReflectionPerPoint.add(reflectionAmt.mul(1e12).div(totalAllocPoint));\r\n            pool.accReflectionPerShare = pool.accReflectionPerShare.add(\r\n                pool.allocPoint.mul(accReflectionPerPoint.sub(pool.lastReflectionPerPoint)).div(lpSupply)\r\n            );\r\n            pool.lastReflectionPerPoint = accReflectionPerPoint;\r\n\r\n            totalReflections = totalReflections.add(reflectionAmt);\r\n        }\r\n\r\n        pool.lastRewardBlock = block.number;\r\n    }\r\n\r\n    // Deposit LP tokens to BrewlabsFarm for brews allocation.\r\n    function deposit(uint256 _pid, uint256 _amount) external payable nonReentrant {\r\n        _transferPerformanceFee();\r\n\r\n        PoolInfo storage pool = poolInfo[_pid];\r\n        UserInfo storage user = userInfo[_pid][msg.sender];\r\n\r\n        if(pool.bonusEndBlock < block.number) {\r\n            massUpdatePools();\r\n\r\n            totalAllocPoint = totalAllocPoint.sub(pool.allocPoint);\r\n            pool.allocPoint = 0;\r\n        } else {\r\n            updatePool(_pid);\r\n        }\r\n\r\n        if (user.amount > 0) {\r\n            uint256 pending = user.amount.mul(pool.accTokenPerShare).div(1e12).sub(user.rewardDebt);\r\n            if (pending > 0) {\r\n                require(availableRewardTokens() >= pending, \"Insufficient reward tokens\");\r\n                safeTokenTransfer(msg.sender, pending);\r\n\r\n                if(totalEarned > pending) {\r\n                    totalEarned = totalEarned.sub(pending);\r\n                } else {\r\n                    totalEarned = 0;\r\n                }\r\n            }\r\n\r\n            uint256 pendingReflection = user.amount.mul(pool.accReflectionPerShare).div(1e12).sub(user.reflectionDebt);\r\n            pendingReflection = _estimateDividendAmount(pendingReflection);\r\n            if (pendingReflection > 0 && hasDividend) {\r\n                if(address(reflectionToken) == address(0x0)) {\r\n                    payable(msg.sender).transfer(pendingReflection);\r\n                } else {\r\n                    IERC20(reflectionToken).safeTransfer(msg.sender, pendingReflection);\r\n                }\r\n                totalReflections = totalReflections.sub(pendingReflection);\r\n            }\r\n        }\r\n        if (_amount > 0) {\r\n            uint256 beforeAmt = pool.lpToken.balanceOf(address(this));\r\n            pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);\r\n            uint256 afterAmt = pool.lpToken.balanceOf(address(this));\r\n            uint256 amount = afterAmt.sub(beforeAmt);\r\n\r\n            if (pool.depositFee > 0) {\r\n                uint256 depositFee = amount.mul(pool.depositFee).div(10000);\r\n                pool.lpToken.safeTransfer(feeAddress, depositFee);\r\n                user.amount = user.amount.add(amount).sub(depositFee);\r\n            } else {\r\n                user.amount = user.amount.add(amount);\r\n            }\r\n\r\n            _calculateTotalStaked(_pid, pool.lpToken, amount, true);\r\n        }\r\n\r\n        user.rewardDebt = user.amount.mul(pool.accTokenPerShare).div(1e12);\r\n        user.reflectionDebt = user.amount.mul(pool.accReflectionPerShare).div(1e12);\r\n\r\n        emit Deposit(msg.sender, _pid, _amount);\r\n    }\r\n    \r\n    // Withdraw LP tokens from BrewlabsFarm.\r\n    function withdraw(uint256 _pid, uint256 _amount) external payable nonReentrant {\r\n        PoolInfo storage pool = poolInfo[_pid];\r\n        UserInfo storage user = userInfo[_pid][msg.sender];\r\n        require(user.amount >= _amount, \"withdraw: not good\");\r\n        require(_amount > 0, \"Amount should be greator than 0\");\r\n\r\n        _transferPerformanceFee();\r\n\r\n        if(pool.bonusEndBlock < block.number) {\r\n            massUpdatePools();\r\n            \r\n            totalAllocPoint = totalAllocPoint.sub(pool.allocPoint);\r\n            pool.allocPoint = 0;\r\n        } else {\r\n            updatePool(_pid);\r\n        }\r\n\r\n        uint256 pending = user.amount.mul(pool.accTokenPerShare).div(1e12).sub(user.rewardDebt);\r\n        if (pending > 0) {\r\n            require(availableRewardTokens() >= pending, \"Insufficient reward tokens\");\r\n            safeTokenTransfer(msg.sender, pending);\r\n\r\n            if(totalEarned > pending) {\r\n                totalEarned = totalEarned.sub(pending);\r\n            } else {\r\n                totalEarned = 0;\r\n            }\r\n        }\r\n        \r\n        uint256 pendingReflection = user.amount.mul(pool.accReflectionPerShare).div(1e12).sub(user.reflectionDebt);\r\n        pendingReflection = _estimateDividendAmount(pendingReflection);\r\n        if (pendingReflection > 0 && hasDividend) {\r\n            if(address(reflectionToken) == address(0x0)) {\r\n                payable(msg.sender).transfer(pendingReflection);\r\n            } else {\r\n                IERC20(reflectionToken).safeTransfer(msg.sender, pendingReflection);\r\n            }\r\n            totalReflections = totalReflections.sub(pendingReflection);\r\n        }\r\n\r\n        if (_amount > 0) {\r\n            user.amount = user.amount.sub(_amount);\r\n            if (pool.withdrawFee > 0) {\r\n                uint256 withdrawFee = _amount.mul(pool.withdrawFee).div(10000);\r\n                pool.lpToken.safeTransfer(feeAddress, withdrawFee);\r\n                pool.lpToken.safeTransfer(address(msg.sender), _amount.sub(withdrawFee));\r\n            } else {\r\n                pool.lpToken.safeTransfer(address(msg.sender), _amount);\r\n            }\r\n\r\n            _calculateTotalStaked(_pid, pool.lpToken, _amount, false);\r\n        }\r\n        user.rewardDebt = user.amount.mul(pool.accTokenPerShare).div(1e12);\r\n        user.reflectionDebt = user.amount.mul(pool.accReflectionPerShare).div(1e12);\r\n\r\n        emit Withdraw(msg.sender, _pid, _amount);\r\n    }\r\n\r\n    function claimReward(uint256 _pid) external payable nonReentrant {\r\n        PoolInfo memory pool = poolInfo[_pid];\r\n        UserInfo storage user = userInfo[_pid][msg.sender];\r\n        if(user.amount < 0) return;\r\n\r\n        updatePool(_pid);\r\n        _transferPerformanceFee();\r\n\r\n        uint256 pending = user.amount.mul(pool.accTokenPerShare).div(1e12).sub(user.rewardDebt);\r\n        if (pending > 0) {\r\n            require(availableRewardTokens() >= pending, \"Insufficient reward tokens\");\r\n            safeTokenTransfer(msg.sender, pending);\r\n\r\n            if(totalEarned > pending) {\r\n                totalEarned = totalEarned.sub(pending);\r\n            } else {\r\n                totalEarned = 0;\r\n            }\r\n        }\r\n        user.rewardDebt = user.amount.mul(pool.accTokenPerShare).div(1e12);\r\n    }\r\n\r\n    function compoundReward(uint256 _pid) external payable nonReentrant {\r\n        PoolInfo memory pool = poolInfo[_pid];\r\n        SwapSetting memory swapSetting = swapSettings[_pid];\r\n        UserInfo storage user = userInfo[_pid][msg.sender];\r\n        if(user.amount < 0) return;\r\n        if(!swapSetting.enabled) return;\r\n\r\n        updatePool(_pid);\r\n        _transferPerformanceFee();\r\n\r\n        uint256 pending = user.amount.mul(pool.accTokenPerShare).div(1e12).sub(user.rewardDebt);\r\n        if (pending > 0) {\r\n            require(availableRewardTokens() >= pending, \"Insufficient reward tokens\");\r\n            if(totalEarned > pending) {\r\n                totalEarned = totalEarned.sub(pending);\r\n            } else {\r\n                totalEarned = 0;\r\n            }\r\n        }\r\n\r\n        if(address(brews) != address(pool.lpToken)) {\r\n            uint256 tokenAmt = pending / 2;\r\n            uint256 tokenAmt0 = tokenAmt;\r\n            address token0 = address(brews);\r\n            if(swapSetting.earnedToToken0.length > 0) {\r\n                token0 = swapSetting.earnedToToken0[swapSetting.earnedToToken0.length - 1];\r\n                tokenAmt0 = _safeSwap(swapSetting.swapRouter, tokenAmt, swapSetting.earnedToToken0, address(this));\r\n            }\r\n            uint256 tokenAmt1 = tokenAmt;\r\n            address token1 = address(brews);\r\n            if(swapSetting.earnedToToken1.length > 0) {\r\n                token0 = swapSetting.earnedToToken1[swapSetting.earnedToToken1.length - 1];\r\n                tokenAmt1 = _safeSwap(swapSetting.swapRouter, tokenAmt, swapSetting.earnedToToken1, address(this));\r\n            }\r\n\r\n            uint256 beforeAmt = pool.lpToken.balanceOf(address(this));\r\n            _addLiquidity(swapSetting.swapRouter, token0, token1, tokenAmt0, tokenAmt1, address(this));\r\n            uint256 afterAmt = pool.lpToken.balanceOf(address(this));\r\n\r\n            pending = afterAmt - beforeAmt;\r\n        }\r\n\r\n        user.amount = user.amount + pending;\r\n        user.rewardDebt = user.amount.mul(pool.accTokenPerShare).div(1e12);\r\n        user.reflectionDebt = user.reflectionDebt + pending * pool.accReflectionPerShare / 1e12;\r\n        \r\n        _calculateTotalStaked(_pid, pool.lpToken, pending, true);\r\n        emit Deposit(msg.sender, _pid, pending);\r\n    }\r\n\r\n    function claimDividend(uint256 _pid) external payable nonReentrant {\r\n        PoolInfo memory pool = poolInfo[_pid];\r\n        UserInfo storage user = userInfo[_pid][msg.sender];\r\n        if(user.amount < 0) return;\r\n        if(!hasDividend) return;\r\n        \r\n        updatePool(_pid);\r\n        _transferPerformanceFee();\r\n\r\n        uint256 pendingReflection = user.amount.mul(pool.accReflectionPerShare).div(1e12).sub(user.reflectionDebt);\r\n        pendingReflection = _estimateDividendAmount(pendingReflection);\r\n        if (pendingReflection > 0) {\r\n            if(address(reflectionToken) == address(0x0)) {\r\n                payable(msg.sender).transfer(pendingReflection);\r\n            } else {\r\n                IERC20(reflectionToken).safeTransfer(msg.sender, pendingReflection);\r\n            }\r\n            totalReflections = totalReflections.sub(pendingReflection);\r\n        }\r\n\r\n        user.reflectionDebt = user.amount.mul(pool.accReflectionPerShare).div(1e12);\r\n    }\r\n\r\n    function compoundDividend(uint256 _pid) external payable nonReentrant {\r\n        PoolInfo memory pool = poolInfo[_pid];\r\n        SwapSetting memory swapSetting = swapSettings[_pid];\r\n        UserInfo storage user = userInfo[_pid][msg.sender];\r\n        if(user.amount < 0) return;\r\n        if(!hasDividend) return;\r\n        \r\n        updatePool(_pid);\r\n        _transferPerformanceFee();\r\n\r\n        uint256 pending = user.amount.mul(pool.accReflectionPerShare).div(1e12).sub(user.reflectionDebt);\r\n        pending = _estimateDividendAmount(pending);\r\n        if (pending > 0) {\r\n            totalReflections = totalReflections.sub(pending);\r\n        }\r\n\r\n        if(reflectionToken != address(pool.lpToken)) {\r\n            if(reflectionToken == address(0x0)) {\r\n                address wethAddress = IUniRouter02(swapSetting.swapRouter).WETH();\r\n                IWETH(wethAddress).deposit{ value: pending }();\r\n            }\r\n\r\n            uint256 tokenAmt = pending / 2;\r\n            uint256 tokenAmt0 = tokenAmt;\r\n            address token0 = reflectionToken;\r\n            if(swapSetting.reflectionToToken0.length > 0) {\r\n                token0 = swapSetting.reflectionToToken0[swapSetting.reflectionToToken0.length - 1];\r\n                tokenAmt0 = _safeSwap(swapSetting.swapRouter, tokenAmt, swapSetting.reflectionToToken0, address(this));\r\n            }\r\n            uint256 tokenAmt1 = tokenAmt;\r\n            address token1 = reflectionToken;\r\n            if(swapSetting.reflectionToToken1.length > 0) {\r\n                token0 = swapSetting.reflectionToToken1[swapSetting.reflectionToToken1.length - 1];\r\n                tokenAmt1 = _safeSwap(swapSetting.swapRouter, tokenAmt, swapSetting.reflectionToToken1, address(this));\r\n            }\r\n\r\n            uint256 beforeAmt = pool.lpToken.balanceOf(address(this));\r\n            _addLiquidity(swapSetting.swapRouter, token0, token1, tokenAmt0, tokenAmt1, address(this));\r\n            uint256 afterAmt = pool.lpToken.balanceOf(address(this));\r\n\r\n            pending = afterAmt - beforeAmt;\r\n        }\r\n\r\n        user.amount = user.amount + pending;\r\n        user.rewardDebt = user.rewardDebt + pending.mul(pool.accTokenPerShare).div(1e12);\r\n        user.reflectionDebt = user.amount.mul(pool.accReflectionPerShare).div(1e12);\r\n\r\n        _calculateTotalStaked(_pid, pool.lpToken, pending, true);        \r\n        emit Deposit(msg.sender, _pid, pending);\r\n    }\r\n\r\n    // Withdraw without caring about rewards. EMERGENCY ONLY.\r\n    function emergencyWithdraw(uint256 _pid) external nonReentrant {\r\n        PoolInfo storage pool = poolInfo[_pid];\r\n        UserInfo storage user = userInfo[_pid][msg.sender];\r\n        uint256 amount = user.amount;\r\n        user.amount = 0;\r\n        user.rewardDebt = 0;\r\n        pool.lpToken.safeTransfer(address(msg.sender), amount);\r\n\r\n        _calculateTotalStaked(_pid, pool.lpToken, amount, false);\r\n        \r\n        emit EmergencyWithdraw(msg.sender, _pid, amount);\r\n    }\r\n\r\n    function _transferPerformanceFee() internal {\r\n        require(msg.value >= performanceFee, 'should pay small gas');\r\n\r\n        payable(buyBackWallet).transfer(performanceFee);\r\n        if(msg.value > performanceFee) {\r\n            payable(msg.sender).transfer(msg.value - performanceFee);\r\n        }\r\n    }\r\n\r\n    function _calculateTotalStaked(uint256 _pid, IERC20 _lpToken, uint256 _amount, bool _deposit) internal {\r\n        if(_deposit) {\r\n            totalStaked[_pid] = totalStaked[_pid].add(_amount);\r\n            if(address(_lpToken) == address(brews)) {\r\n                totalRewardStaked = totalRewardStaked + _amount;\r\n            }\r\n            if(address(_lpToken) == reflectionToken) {\r\n                totalReflectionStaked = totalReflectionStaked + _amount;\r\n            }\r\n        } else {\r\n            totalStaked[_pid] = totalStaked[_pid] - _amount;\r\n            if(address(_lpToken) == address(brews)) {\r\n                if(totalRewardStaked < _amount) totalRewardStaked = _amount;\r\n                totalRewardStaked = totalRewardStaked - _amount;\r\n            }\r\n            if(address(_lpToken) == reflectionToken) {\r\n                if(totalReflectionStaked < _amount) totalReflectionStaked = _amount;\r\n                totalReflectionStaked = totalReflectionStaked - _amount;\r\n            }\r\n        }        \r\n    }\r\n\r\n    function _estimateDividendAmount(uint256 amount) internal view returns(uint256) {\r\n        uint256 dTokenBal = availableDividendTokens();\r\n        if(amount > totalReflections) amount = totalReflections;\r\n        if(amount > dTokenBal) amount = dTokenBal;\r\n        return amount;\r\n    }\r\n\r\n    /**\r\n     * @notice Available amount of reward token\r\n     */\r\n    function availableRewardTokens() public view returns (uint256) {\r\n        if(address(brews) == reflectionToken) return totalEarned;\r\n\r\n        uint256 _amount = brews.balanceOf(address(this));\r\n        return _amount - totalRewardStaked;\r\n    }\r\n\r\n    /**\r\n     * @notice Available amount of reflection token\r\n     */\r\n    function availableDividendTokens() public view returns (uint256) {\r\n        if(hasDividend == false) return 0;\r\n        if(address(reflectionToken) == address(0x0)) {\r\n            return address(this).balance;\r\n        }\r\n\r\n        uint256 _amount = IERC20(reflectionToken).balanceOf(address(this));      \r\n        if(address(reflectionToken) == address(brews)) {\r\n            if(_amount < totalEarned) return 0;\r\n            _amount = _amount - totalEarned;\r\n        }\r\n        return _amount - totalReflectionStaked;\r\n    }    \r\n\r\n    // Safe brews transfer function, just in case if rounding error causes pool to not have enough brewss.\r\n    function safeTokenTransfer(address _to, uint256 _amount) internal {\r\n        uint256 brewsBal = brews.balanceOf(address(this));\r\n        bool transferSuccess = false;\r\n        if (_amount > brewsBal) {\r\n            transferSuccess = brews.transfer(_to, brewsBal);\r\n        } else {\r\n            transferSuccess = brews.transfer(_to, _amount);\r\n        }\r\n        require(transferSuccess, \"safeTokenTransfer: transfer failed\");\r\n    }\r\n\r\n    function setFeeAddress(address _feeAddress) external onlyOwner {\r\n        feeAddress = _feeAddress;\r\n        emit SetFeeAddress(msg.sender, _feeAddress);\r\n    }\r\n\r\n    function setPerformanceFee(uint256 _fee) external {\r\n        require(msg.sender == buyBackWallet, \"setPerformanceFee: FORBIDDEN\");\r\n\r\n        performanceFee = _fee;\r\n        emit SetPerformanceFee(_fee);\r\n    }\r\n    \r\n    function setBuyBackWallet(address _addr) external {\r\n        require(msg.sender == buyBackWallet, \"setBuyBackWallet: FORBIDDEN\");\r\n        buyBackWallet = _addr;\r\n        emit SetBuyBackWallet(msg.sender, _addr);\r\n    }\r\n\r\n    //Brews has to add hidden dummy pools inorder to alter the emission, here we make it simple and transparent to all.\r\n    function updateEmissionRate(uint256 _rewardPerBlock) external onlyOwner {\r\n        massUpdatePools();\r\n        rewardPerBlock = _rewardPerBlock;\r\n        emit UpdateEmissionRate(msg.sender, _rewardPerBlock);\r\n    }\r\n\r\n    function updateStartBlock(uint256 _startBlock) external onlyOwner {\r\n        require(startBlock > block.number, \"farm is running now\");\r\n        require(_startBlock > block.number, \"should be greater than current block\");\r\n\r\n        startBlock = _startBlock;\r\n        for(uint pid = 0; pid < poolInfo.length; pid++) {\r\n            poolInfo[pid].startBlock = startBlock;\r\n            poolInfo[pid].lastRewardBlock = startBlock;\r\n            poolInfo[pid].bonusEndBlock = startBlock.add(poolInfo[pid].duration.mul(6426));\r\n        }\r\n    }\r\n\r\n    /*\r\n     * @notice Deposit reward token\r\n     * @dev Only call by owner. Needs to be for deposit of reward token when reflection token is same with reward token.\r\n     */\r\n    function depositRewards(uint _amount) external nonReentrant {\r\n        require(_amount > 0);\r\n\r\n        uint256 beforeAmt = brews.balanceOf(address(this));\r\n        brews.safeTransferFrom(msg.sender, address(this), _amount);\r\n        uint256 afterAmt = brews.balanceOf(address(this));\r\n\r\n        totalEarned = totalEarned.add(afterAmt).sub(beforeAmt);\r\n    }\r\n\r\n    function emergencyWithdrawRewards(uint256 _amount) external onlyOwner {\r\n        if(_amount == 0) {\r\n            uint256 amount = brews.balanceOf(address(this));\r\n            safeTokenTransfer(msg.sender, amount);\r\n        } else {\r\n            safeTokenTransfer(msg.sender, _amount);\r\n        }\r\n    }\r\n\r\n    function emergencyWithdrawReflections() external onlyOwner {\r\n        if(address(reflectionToken) == address(0x0)) {\r\n            uint256 amount = address(this).balance;\r\n            payable(address(this)).transfer(amount);\r\n        } else {\r\n            uint256 amount = IERC20(reflectionToken).balanceOf(address(this));\r\n            IERC20(reflectionToken).transfer(msg.sender, amount);\r\n        }\r\n    }\r\n\r\n    function recoverWrongToken(address _token) external onlyOwner {\r\n        require(_token != address(brews) && _token != reflectionToken, \"cannot recover reward token or reflection token\");\r\n        require(poolExistence[IERC20(_token)] == false, \"token is using on pool\");\r\n\r\n        if(_token == address(0x0)) {\r\n            uint256 amount = address(this).balance;\r\n            payable(address(this)).transfer(amount);\r\n        } else {\r\n            uint256 amount = IERC20(_token).balanceOf(address(this));\r\n            if(amount > 0) {\r\n                IERC20(_token).transfer(msg.sender, amount);\r\n            }\r\n        }\r\n    }\r\n\r\n    function _safeSwap(\r\n        address _uniRouter,\r\n        uint256 _amountIn,\r\n        address[] memory _path,\r\n        address _to\r\n    ) internal returns (uint256) {\r\n        uint256 beforeAmt = IERC20(_path[_path.length - 1]).balanceOf(address(this));\r\n        IERC20(_path[0]).safeApprove(_uniRouter, _amountIn);\r\n        IUniRouter02(_uniRouter).swapExactTokensForTokensSupportingFeeOnTransferTokens(\r\n            _amountIn,\r\n            0,\r\n            _path,\r\n            _to,\r\n            block.timestamp + 600\r\n        );\r\n        uint256 afterAmt = IERC20(_path[_path.length - 1]).balanceOf(address(this));\r\n        return afterAmt - beforeAmt;\r\n    }\r\n\r\n    function _addLiquidity(\r\n        address _uniRouter,\r\n        address _token0,\r\n        address _token1,\r\n        uint256 _tokenAmt0,\r\n        uint256 _tokenAmt1,\r\n        address _to\r\n    ) internal returns(uint256 amountA, uint256 amountB, uint256 liquidity) {\r\n        IERC20(_token0).safeIncreaseAllowance(_uniRouter, _tokenAmt0);\r\n        IERC20(_token1).safeIncreaseAllowance(_uniRouter, _tokenAmt1);\r\n\r\n        (amountA, amountB, liquidity) = IUniRouter02(_uniRouter).addLiquidity(\r\n            _token0,\r\n            _token1,\r\n            _tokenAmt0,\r\n            _tokenAmt1,\r\n            0,\r\n            0,\r\n            _to,\r\n            block.timestamp + 600\r\n        );\r\n\r\n        IERC20(_token0).safeApprove(_uniRouter, uint256(0));\r\n        IERC20(_token1).safeApprove(_uniRouter, uint256(0));\r\n    }\r\n    receive() external payable {}\r\n}"
    },
    "@openzeppelin/contracts/access/Ownable.sol": {
      "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../utils/Context.sol\";\n\n/**\n * @dev Contract module which provides a basic access control mechanism, where\n * there is an account (an owner) that can be granted exclusive access to\n * specific functions.\n *\n * By default, the owner account will be the one that deploys the contract. This\n * can later be changed with {transferOwnership}.\n *\n * This module is used through inheritance. It will make available the modifier\n * `onlyOwner`, which can be applied to your functions to restrict their use to\n * the owner.\n */\nabstract contract Ownable is Context {\n    address private _owner;\n\n    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);\n\n    /**\n     * @dev Initializes the contract setting the deployer as the initial owner.\n     */\n    constructor() {\n        _transferOwnership(_msgSender());\n    }\n\n    /**\n     * @dev Returns the address of the current owner.\n     */\n    function owner() public view virtual returns (address) {\n        return _owner;\n    }\n\n    /**\n     * @dev Throws if called by any account other than the owner.\n     */\n    modifier onlyOwner() {\n        require(owner() == _msgSender(), \"Ownable: caller is not the owner\");\n        _;\n    }\n\n    /**\n     * @dev Leaves the contract without owner. It will not be possible to call\n     * `onlyOwner` functions anymore. Can only be called by the current owner.\n     *\n     * NOTE: Renouncing ownership will leave the contract without an owner,\n     * thereby removing any functionality that is only available to the owner.\n     */\n    function renounceOwnership() public virtual onlyOwner {\n        _transferOwnership(address(0));\n    }\n\n    /**\n     * @dev Transfers ownership of the contract to a new account (`newOwner`).\n     * Can only be called by the current owner.\n     */\n    function transferOwnership(address newOwner) public virtual onlyOwner {\n        require(newOwner != address(0), \"Ownable: new owner is the zero address\");\n        _transferOwnership(newOwner);\n    }\n\n    /**\n     * @dev Transfers ownership of the contract to a new account (`newOwner`).\n     * Internal function without access restriction.\n     */\n    function _transferOwnership(address newOwner) internal virtual {\n        address oldOwner = _owner;\n        _owner = newOwner;\n        emit OwnershipTransferred(oldOwner, newOwner);\n    }\n}\n"
    },
    "@openzeppelin/contracts/utils/math/SafeMath.sol": {
      "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/math/SafeMath.sol)\n\npragma solidity ^0.8.0;\n\n// CAUTION\n// This version of SafeMath should only be used with Solidity 0.8 or later,\n// because it relies on the compiler's built in overflow checks.\n\n/**\n * @dev Wrappers over Solidity's arithmetic operations.\n *\n * NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler\n * now has built in overflow checking.\n */\nlibrary SafeMath {\n    /**\n     * @dev Returns the addition of two unsigned integers, with an overflow flag.\n     *\n     * _Available since v3.4._\n     */\n    function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {\n        unchecked {\n            uint256 c = a + b;\n            if (c < a) return (false, 0);\n            return (true, c);\n        }\n    }\n\n    /**\n     * @dev Returns the substraction of two unsigned integers, with an overflow flag.\n     *\n     * _Available since v3.4._\n     */\n    function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {\n        unchecked {\n            if (b > a) return (false, 0);\n            return (true, a - b);\n        }\n    }\n\n    /**\n     * @dev Returns the multiplication of two unsigned integers, with an overflow flag.\n     *\n     * _Available since v3.4._\n     */\n    function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {\n        unchecked {\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) return (true, 0);\n            uint256 c = a * b;\n            if (c / a != b) return (false, 0);\n            return (true, c);\n        }\n    }\n\n    /**\n     * @dev Returns the division of two unsigned integers, with a division by zero flag.\n     *\n     * _Available since v3.4._\n     */\n    function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {\n        unchecked {\n            if (b == 0) return (false, 0);\n            return (true, a / b);\n        }\n    }\n\n    /**\n     * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.\n     *\n     * _Available since v3.4._\n     */\n    function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {\n        unchecked {\n            if (b == 0) return (false, 0);\n            return (true, a % b);\n        }\n    }\n\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        return a + b;\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 a - b;\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        return a * b;\n    }\n\n    /**\n     * @dev Returns the integer division of two unsigned integers, reverting on\n     * division by zero. The result is rounded towards zero.\n     *\n     * Counterpart to Solidity's `/` operator.\n     *\n     * Requirements:\n     *\n     * - The divisor cannot be zero.\n     */\n    function div(uint256 a, uint256 b) internal pure returns (uint256) {\n        return a / b;\n    }\n\n    /**\n     * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),\n     * reverting 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 a % b;\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     * CAUTION: This function is deprecated because it requires allocating memory for the error\n     * message unnecessarily. For custom revert reasons use {trySub}.\n     *\n     * Counterpart to Solidity's `-` operator.\n     *\n     * Requirements:\n     *\n     * - Subtraction cannot overflow.\n     */\n    function sub(\n        uint256 a,\n        uint256 b,\n        string memory errorMessage\n    ) internal pure returns (uint256) {\n        unchecked {\n            require(b <= a, errorMessage);\n            return a - b;\n        }\n    }\n\n    /**\n     * @dev Returns the integer division of two unsigned integers, reverting 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(\n        uint256 a,\n        uint256 b,\n        string memory errorMessage\n    ) internal pure returns (uint256) {\n        unchecked {\n            require(b > 0, errorMessage);\n            return a / b;\n        }\n    }\n\n    /**\n     * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),\n     * reverting with custom message when dividing by zero.\n     *\n     * CAUTION: This function is deprecated because it requires allocating memory for the error\n     * message unnecessarily. For custom revert reasons use {tryMod}.\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(\n        uint256 a,\n        uint256 b,\n        string memory errorMessage\n    ) internal pure returns (uint256) {\n        unchecked {\n            require(b > 0, errorMessage);\n            return a % b;\n        }\n    }\n}\n"
    },
    "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol": {
      "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../IERC20.sol\";\nimport \"../../../utils/Address.sol\";\n\n/**\n * @title SafeERC20\n * @dev Wrappers around ERC20 operations that throw on failure (when the token\n * contract returns false). Tokens that return no value (and instead revert or\n * throw on failure) are also supported, non-reverting calls are assumed to be\n * successful.\n * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,\n * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.\n */\nlibrary SafeERC20 {\n    using Address for address;\n\n    function safeTransfer(\n        IERC20 token,\n        address to,\n        uint256 value\n    ) internal {\n        _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));\n    }\n\n    function safeTransferFrom(\n        IERC20 token,\n        address from,\n        address to,\n        uint256 value\n    ) internal {\n        _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));\n    }\n\n    /**\n     * @dev Deprecated. This function has issues similar to the ones found in\n     * {IERC20-approve}, and its usage is discouraged.\n     *\n     * Whenever possible, use {safeIncreaseAllowance} and\n     * {safeDecreaseAllowance} instead.\n     */\n    function safeApprove(\n        IERC20 token,\n        address spender,\n        uint256 value\n    ) internal {\n        // safeApprove should only be called when setting an initial allowance,\n        // or when resetting it to zero. To increase and decrease it, use\n        // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'\n        require(\n            (value == 0) || (token.allowance(address(this), spender) == 0),\n            \"SafeERC20: approve from non-zero to non-zero allowance\"\n        );\n        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));\n    }\n\n    function safeIncreaseAllowance(\n        IERC20 token,\n        address spender,\n        uint256 value\n    ) internal {\n        uint256 newAllowance = token.allowance(address(this), spender) + value;\n        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));\n    }\n\n    function safeDecreaseAllowance(\n        IERC20 token,\n        address spender,\n        uint256 value\n    ) internal {\n        unchecked {\n            uint256 oldAllowance = token.allowance(address(this), spender);\n            require(oldAllowance >= value, \"SafeERC20: decreased allowance below zero\");\n            uint256 newAllowance = oldAllowance - value;\n            _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));\n        }\n    }\n\n    /**\n     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement\n     * on the return value: the return value is optional (but if data is returned, it must not be false).\n     * @param token The token targeted by the call.\n     * @param data The call data (encoded using abi.encode or one of its variants).\n     */\n    function _callOptionalReturn(IERC20 token, bytes memory data) private {\n        // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since\n        // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that\n        // the target address contains contract code and also asserts for success in the low-level call.\n\n        bytes memory returndata = address(token).functionCall(data, \"SafeERC20: low-level call failed\");\n        if (returndata.length > 0) {\n            // Return data is optional\n            require(abi.decode(returndata, (bool)), \"SafeERC20: ERC20 operation did not succeed\");\n        }\n    }\n}\n"
    },
    "@openzeppelin/contracts/security/ReentrancyGuard.sol": {
      "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Contract module that helps prevent reentrant calls to a function.\n *\n * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier\n * available, which can be applied to functions to make sure there are no nested\n * (reentrant) calls to them.\n *\n * Note that because there is a single `nonReentrant` guard, functions marked as\n * `nonReentrant` may not call one another. This can be worked around by making\n * those functions `private`, and then adding `external` `nonReentrant` entry\n * points to them.\n *\n * TIP: If you would like to learn more about reentrancy and alternative ways\n * to protect against it, check out our blog post\n * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].\n */\nabstract contract ReentrancyGuard {\n    // Booleans are more expensive than uint256 or any type that takes up a full\n    // word because each write operation emits an extra SLOAD to first read the\n    // slot's contents, replace the bits taken up by the boolean, and then write\n    // back. This is the compiler's defense against contract upgrades and\n    // pointer aliasing, and it cannot be disabled.\n\n    // The values being non-zero value makes deployment a bit more expensive,\n    // but in exchange the refund on every call to nonReentrant will be lower in\n    // amount. Since refunds are capped to a percentage of the total\n    // transaction's gas, it is best to keep them low in cases like this one, to\n    // increase the likelihood of the full refund coming into effect.\n    uint256 private constant _NOT_ENTERED = 1;\n    uint256 private constant _ENTERED = 2;\n\n    uint256 private _status;\n\n    constructor() {\n        _status = _NOT_ENTERED;\n    }\n\n    /**\n     * @dev Prevents a contract from calling itself, directly or indirectly.\n     * Calling a `nonReentrant` function from another `nonReentrant`\n     * function is not supported. It is possible to prevent this from happening\n     * by making the `nonReentrant` function external, and making it call a\n     * `private` function that does the actual work.\n     */\n    modifier nonReentrant() {\n        // On the first call to nonReentrant, _notEntered will be true\n        require(_status != _ENTERED, \"ReentrancyGuard: reentrant call\");\n\n        // Any calls to nonReentrant after this point will fail\n        _status = _ENTERED;\n\n        _;\n\n        // By storing the original value once again, a refund is triggered (see\n        // https://eips.ethereum.org/EIPS/eip-2200)\n        _status = _NOT_ENTERED;\n    }\n}\n"
    },
    "contracts/libs/IUniRouter02.sol": {
      "content": "// SPDX-License-Identifier: MIT\r\n\r\npragma solidity ^0.8.0;\r\n\r\nimport \"./IUniRouter01.sol\";\r\n\r\ninterface IUniRouter02 is IUniRouter01 {\r\n    function removeLiquidityETHSupportingFeeOnTransferTokens(\r\n        address token,\r\n        uint256 liquidity,\r\n        uint256 amountTokenMin,\r\n        uint256 amountETHMin,\r\n        address to,\r\n        uint256 deadline\r\n    ) external returns (uint256 amountETH);\r\n\r\n    function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(\r\n        address token,\r\n        uint256 liquidity,\r\n        uint256 amountTokenMin,\r\n        uint256 amountETHMin,\r\n        address to,\r\n        uint256 deadline,\r\n        bool approveMax,\r\n        uint8 v,\r\n        bytes32 r,\r\n        bytes32 s\r\n    ) external returns (uint256 amountETH);\r\n\r\n    function swapExactTokensForTokensSupportingFeeOnTransferTokens(\r\n        uint256 amountIn,\r\n        uint256 amountOutMin,\r\n        address[] calldata path,\r\n        address to,\r\n        uint256 deadline\r\n    ) external;\r\n\r\n    function swapExactETHForTokensSupportingFeeOnTransferTokens(\r\n        uint256 amountOutMin,\r\n        address[] calldata path,\r\n        address to,\r\n        uint256 deadline\r\n    ) external payable;\r\n\r\n    function swapExactTokensForETHSupportingFeeOnTransferTokens(\r\n        uint256 amountIn,\r\n        uint256 amountOutMin,\r\n        address[] calldata path,\r\n        address to,\r\n        uint256 deadline\r\n    ) external;\r\n}"
    },
    "contracts/libs/IWETH.sol": {
      "content": "// SPDX-License-Identifier: MIT\r\n\r\npragma solidity >=0.5.0;\r\n\r\ninterface IWETH {\r\n    function deposit() external payable;\r\n    function transfer(address to, uint value) external returns (bool);\r\n    function withdraw(uint) external;\r\n}"
    },
    "@openzeppelin/contracts/utils/Context.sol": {
      "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Provides information about the current execution context, including the\n * sender of the transaction and its data. While these are generally available\n * via msg.sender and msg.data, they should not be accessed in such a direct\n * manner, since when dealing with meta-transactions the account sending and\n * paying for execution may not be the actual sender (as far as an application\n * is concerned).\n *\n * This contract is only required for intermediate, library-like contracts.\n */\nabstract contract Context {\n    function _msgSender() internal view virtual returns (address) {\n        return msg.sender;\n    }\n\n    function _msgData() internal view virtual returns (bytes calldata) {\n        return msg.data;\n    }\n}\n"
    },
    "@openzeppelin/contracts/token/ERC20/IERC20.sol": {
      "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol)\n\npragma solidity ^0.8.0;\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    /**\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(\n        address sender,\n        address recipient,\n        uint256 amount\n    ) 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"
    },
    "@openzeppelin/contracts/utils/Address.sol": {
      "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/Address.sol)\n\npragma solidity ^0.8.0;\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 on 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        assembly {\n            size := extcodesize(account)\n        }\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        (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(\n        address target,\n        bytes memory data,\n        string memory errorMessage\n    ) 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(\n        address target,\n        bytes memory data,\n        uint256 value\n    ) 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(\n        address target,\n        bytes memory data,\n        uint256 value,\n        string memory errorMessage\n    ) internal returns (bytes memory) {\n        require(address(this).balance >= value, \"Address: insufficient balance for call\");\n        require(isContract(target), \"Address: call to non-contract\");\n\n        (bool success, bytes memory returndata) = target.call{value: value}(data);\n        return verifyCallResult(success, returndata, errorMessage);\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n     * but performing a static call.\n     *\n     * _Available since v3.3._\n     */\n    function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {\n        return functionStaticCall(target, data, \"Address: low-level static call failed\");\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n     * but performing a static call.\n     *\n     * _Available since v3.3._\n     */\n    function functionStaticCall(\n        address target,\n        bytes memory data,\n        string memory errorMessage\n    ) internal view returns (bytes memory) {\n        require(isContract(target), \"Address: static call to non-contract\");\n\n        (bool success, bytes memory returndata) = target.staticcall(data);\n        return verifyCallResult(success, returndata, errorMessage);\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n     * but performing a delegate call.\n     *\n     * _Available since v3.4._\n     */\n    function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {\n        return functionDelegateCall(target, data, \"Address: low-level delegate call failed\");\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n     * but performing a delegate call.\n     *\n     * _Available since v3.4._\n     */\n    function functionDelegateCall(\n        address target,\n        bytes memory data,\n        string memory errorMessage\n    ) internal returns (bytes memory) {\n        require(isContract(target), \"Address: delegate call to non-contract\");\n\n        (bool success, bytes memory returndata) = target.delegatecall(data);\n        return verifyCallResult(success, returndata, errorMessage);\n    }\n\n    /**\n     * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the\n     * revert reason using the provided one.\n     *\n     * _Available since v4.3._\n     */\n    function verifyCallResult(\n        bool success,\n        bytes memory returndata,\n        string memory errorMessage\n    ) internal pure returns (bytes memory) {\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                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"
    },
    "contracts/libs/IUniRouter01.sol": {
      "content": "// SPDX-License-Identifier: MIT\r\n\r\npragma solidity ^0.8.0;\r\n\r\ninterface IUniRouter01 {\r\n    function factory() external pure returns (address);\r\n\r\n    function WETH() external pure returns (address);\r\n\r\n    function addLiquidity(\r\n        address tokenA,\r\n        address tokenB,\r\n        uint256 amountADesired,\r\n        uint256 amountBDesired,\r\n        uint256 amountAMin,\r\n        uint256 amountBMin,\r\n        address to,\r\n        uint256 deadline\r\n    )\r\n        external\r\n        returns (\r\n            uint256 amountA,\r\n            uint256 amountB,\r\n            uint256 liquidity\r\n        );\r\n\r\n    function addLiquidityETH(\r\n        address token,\r\n        uint256 amountTokenDesired,\r\n        uint256 amountTokenMin,\r\n        uint256 amountETHMin,\r\n        address to,\r\n        uint256 deadline\r\n    )\r\n        external\r\n        payable\r\n        returns (\r\n            uint256 amountToken,\r\n            uint256 amountETH,\r\n            uint256 liquidity\r\n        );\r\n\r\n    function removeLiquidity(\r\n        address tokenA,\r\n        address tokenB,\r\n        uint256 liquidity,\r\n        uint256 amountAMin,\r\n        uint256 amountBMin,\r\n        address to,\r\n        uint256 deadline\r\n    ) external returns (uint256 amountA, uint256 amountB);\r\n\r\n    function removeLiquidityETH(\r\n        address token,\r\n        uint256 liquidity,\r\n        uint256 amountTokenMin,\r\n        uint256 amountETHMin,\r\n        address to,\r\n        uint256 deadline\r\n    ) external returns (uint256 amountToken, uint256 amountETH);\r\n\r\n    function removeLiquidityWithPermit(\r\n        address tokenA,\r\n        address tokenB,\r\n        uint256 liquidity,\r\n        uint256 amountAMin,\r\n        uint256 amountBMin,\r\n        address to,\r\n        uint256 deadline,\r\n        bool approveMax,\r\n        uint8 v,\r\n        bytes32 r,\r\n        bytes32 s\r\n    ) external returns (uint256 amountA, uint256 amountB);\r\n\r\n    function removeLiquidityETHWithPermit(\r\n        address token,\r\n        uint256 liquidity,\r\n        uint256 amountTokenMin,\r\n        uint256 amountETHMin,\r\n        address to,\r\n        uint256 deadline,\r\n        bool approveMax,\r\n        uint8 v,\r\n        bytes32 r,\r\n        bytes32 s\r\n    ) external returns (uint256 amountToken, uint256 amountETH);\r\n\r\n    function swapExactTokensForTokens(\r\n        uint256 amountIn,\r\n        uint256 amountOutMin,\r\n        address[] calldata path,\r\n        address to,\r\n        uint256 deadline\r\n    ) external returns (uint256[] memory amounts);\r\n\r\n    function swapTokensForExactTokens(\r\n        uint256 amountOut,\r\n        uint256 amountInMax,\r\n        address[] calldata path,\r\n        address to,\r\n        uint256 deadline\r\n    ) external returns (uint256[] memory amounts);\r\n\r\n    function swapExactETHForTokens(\r\n        uint256 amountOutMin,\r\n        address[] calldata path,\r\n        address to,\r\n        uint256 deadline\r\n    ) external payable returns (uint256[] memory amounts);\r\n\r\n    function swapTokensForExactETH(\r\n        uint256 amountOut,\r\n        uint256 amountInMax,\r\n        address[] calldata path,\r\n        address to,\r\n        uint256 deadline\r\n    ) external returns (uint256[] memory amounts);\r\n\r\n    function swapExactTokensForETH(\r\n        uint256 amountIn,\r\n        uint256 amountOutMin,\r\n        address[] calldata path,\r\n        address to,\r\n        uint256 deadline\r\n    ) external returns (uint256[] memory amounts);\r\n\r\n    function swapETHForExactTokens(\r\n        uint256 amountOut,\r\n        address[] calldata path,\r\n        address to,\r\n        uint256 deadline\r\n    ) external payable returns (uint256[] memory amounts);\r\n\r\n    function quote(\r\n        uint256 amountA,\r\n        uint256 reserveA,\r\n        uint256 reserveB\r\n    ) external pure returns (uint256 amountB);\r\n\r\n    function getAmountOut(\r\n        uint256 amountIn,\r\n        uint256 reserveIn,\r\n        uint256 reserveOut\r\n    ) external pure returns (uint256 amountOut);\r\n\r\n    function getAmountIn(\r\n        uint256 amountOut,\r\n        uint256 reserveIn,\r\n        uint256 reserveOut\r\n    ) external pure returns (uint256 amountIn);\r\n\r\n    function getAmountsOut(uint256 amountIn, address[] calldata path)\r\n        external\r\n        view\r\n        returns (uint256[] memory amounts);\r\n\r\n    function getAmountsIn(uint256 amountOut, address[] calldata path)\r\n        external\r\n        view\r\n        returns (uint256[] memory amounts);\r\n}"
    }
  },
  "settings": {
    "optimizer": {
      "enabled": true,
      "runs": 100
    },
    "outputSelection": {
      "*": {
        "*": [
          "evm.bytecode",
          "evm.deployedBytecode",
          "devdoc",
          "userdoc",
          "metadata",
          "abi"
        ]
      }
    },
    "metadata": {
      "useLiteralContent": true
    },
    "libraries": {}
  }
}