ETH Price: $2,249.92 (-1.07%)
Gas: 1.34 Gwei

Transaction Decoder

Block:
20661582 at Sep-02-2024 08:06:23 AM +UTC
Transaction Fee:
0.00043423643049745 ETH $0.98
Gas Used:
149,975 Gas / 2.895392102 Gwei

Account State Difference:

  Address   Before After State Difference Code
0x3f170496...5Fbcd1db9
0.08561391062480537 Eth
Nonce: 2168
0.08517967419430792 Eth
Nonce: 2169
0.00043423643049745
(Titan Builder)
8.027215059742836953 Eth8.027325437099594278 Eth0.000110377356757325

Execution Trace

ETH 0.044096573980327128 EtherVistaRouter.swapExactETHForTokensSupportingFeeOnTransferTokens( amountOutMin=7353349058519410688, path=[0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, 0xC9bCa88B04581699fAb5aa276CCafF7Df957cbbf], to=0x3f170496f84c11668e00c572F391DFC5Fbcd1db9, deadline=1725464326 )
  • EtherVistaPair.STATICCALL( )
  • EACAggregatorProxy.STATICCALL( )
    • AccessControlledOffchainAggregator.STATICCALL( )
    • EtherVistaPair.STATICCALL( )
    • EACAggregatorProxy.STATICCALL( )
      • AccessControlledOffchainAggregator.STATICCALL( )
      • ETH 0.040000000000000002 WETH9.CALL( )
      • WETH9.transfer( dst=0xfdd05552F1377aA488AFed744c8024358AF02041, wad=40000000000000002 ) => ( True )
      • Ethervista.balanceOf( account=0x3f170496f84c11668e00c572F391DFC5Fbcd1db9 ) => ( 284689111104 )
      • EtherVistaPair.STATICCALL( )
      • WETH9.balanceOf( 0xfdd05552F1377aA488AFed744c8024358AF02041 ) => ( 325804598810832583224 )
      • EtherVistaPair.swap( amount0Out=0, amount1Out=7339400629548575566, to=0x3f170496f84c11668e00c572F391DFC5Fbcd1db9, data=0x )
        • EtherVistaFactory.STATICCALL( )
        • Ethervista.transfer( to=0x3f170496f84c11668e00c572F391DFC5Fbcd1db9, value=7339400629548575566 ) => ( True )
        • WETH9.balanceOf( 0xfdd05552F1377aA488AFed744c8024358AF02041 ) => ( 325804598810832583224 )
        • Ethervista.balanceOf( account=0xfdd05552F1377aA488AFed744c8024358AF02041 ) => ( 59772922539921592330183 )
        • Ethervista.balanceOf( account=0x3f170496f84c11668e00c572F391DFC5Fbcd1db9 ) => ( 7339400914237686670 )
          swapExactETHForTokensSupportingFeeOnTransferTokens[EtherVistaRouter (ln:441)]
          File 1 of 7: EtherVistaRouter
          pragma solidity =0.6.6;
          import './interfaces/IEtherVistaRouter.sol';
          interface IEtherVistaPair {
              event Approval(address indexed owner, address indexed spender, uint value);
              event Transfer(address indexed from, address indexed to, uint value);
              
              function setMetadata(string calldata website, string calldata image, string calldata description, string calldata chat, string calldata social) external; 
              function websiteUrl() external view returns (string memory);
              function imageUrl() external view returns (string memory);
              function tokenDescription() external view returns (string memory);
              function chatUrl() external view returns (string memory);
              function socialUrl() external view returns (string memory);
              function name() external pure returns (string memory);
              function symbol() external pure returns (string memory);
              function decimals() external pure returns (uint8);
              function totalSupply() external view returns (uint);
              function balanceOf(address owner) external view returns (uint);
              function allowance(address owner, address spender) external view returns (uint);
              function updateProvider(address user) external;
              function euler(uint) external view returns (uint256);
              function viewShare() external view returns (uint256 share);
              function claimShare() external;
              function poolBalance() external view returns (uint);
              function totalCollected() external view returns (uint);
              
              function setProtocol(address) external;
              function protocol() external view returns (address);
              function payableProtocol() external view returns (address payable origin);
              function creator() external view returns (address);
              function renounce() external;
              function setFees() external;
              function updateFees(uint8, uint8, uint8, uint8) external;
              function buyLpFee() external view returns (uint8);
              function sellLpFee() external view returns (uint8);
              function buyProtocolFee() external view returns (uint8);
              function sellProtocolFee() external view returns (uint8);
              function buyTotalFee() external view returns (uint8);
              function sellTotalFee() external view returns (uint8);
              function approve(address spender, uint value) external returns (bool);
              function transfer(address to, uint value) external returns (bool);
              function transferFrom(address from, address to, uint value) external returns (bool);
              function DOMAIN_SEPARATOR() external view returns (bytes32);
              function PERMIT_TYPEHASH() external pure returns (bytes32);
              function nonces(address owner) external view returns (uint);
              function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
              event Mint(address indexed sender, uint amount0, uint amount1);
              event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
              event Swap(
                  address indexed sender,
                  uint amount0In,
                  uint amount1In,
                  uint amount0Out,
                  uint amount1Out,
                  address indexed to
              );
              event Sync(uint112 reserve0, uint112 reserve1);
              function MINIMUM_LIQUIDITY() external pure returns (uint);
              function factory() external view returns (address);
              function token0() external view returns (address);
              function token1() external view returns (address);
              function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
              function price0CumulativeLast() external view returns (uint);
              function price1CumulativeLast() external view returns (uint);
              function kLast() external view returns (uint);
              function first_mint(address to, uint8 buyLp, uint8 sellLp, uint8 buyProtocol, uint8 sellProtocol, address protocolAddress) external returns (uint liquidity);   
              function mint(address to) external returns (uint liquidity);
              function burn(address to) external returns (uint amount0, uint amount1);
              function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
              function skim(address to) external;
              function sync() external;
              function initialize(address _token0, address _token1) external;
          }
          library SafeMath {
              function add(uint x, uint y) internal pure returns (uint z) {
                  require((z = x + y) >= x, 'ds-math-add-overflow');
              }
              function sub(uint x, uint y) internal pure returns (uint z) {
                  require((z = x - y) <= x, 'ds-math-sub-underflow');
              }
              function mul(uint x, uint y) internal pure returns (uint z) {
                  require(y == 0 || (z = x * y) / y == x, 'ds-math-mul-overflow');
              }
          }
          library UniswapV2Library {
              using SafeMath for uint;
              // returns sorted token addresses, used to handle return values from pairs sorted in this order
              function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) {
                  require(tokenA != tokenB, 'UniswapV2Library: IDENTICAL_ADDRESSES');
                  (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
                  require(token0 != address(0), 'UniswapV2Library: ZERO_ADDRESS');
              }
              // calculates the CREATE2 address for a pair without making any external calls
              function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
                  (address token0, address token1) = sortTokens(tokenA, tokenB);
                  pair = address(uint(keccak256(abi.encodePacked(
                          hex'ff',
                          factory,
                          keccak256(abi.encodePacked(token0, token1)),
                          hex'e260b72768e8ec6814aa811c576f346d208ba00840f835949d65c6424ac80a8d' // init code hash
                      ))));
              }
              // fetches and sorts the reserves for a pair
              function getReserves(address factory, address tokenA, address tokenB) internal view returns (uint reserveA, uint reserveB) {
                  (address token0,) = sortTokens(tokenA, tokenB);
                  (uint reserve0, uint reserve1,) = IEtherVistaPair(pairFor(factory, tokenA, tokenB)).getReserves();
                  (reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0);
              }
              // given some amount of an asset and pair reserves, returns an equivalent amount of the other asset
              function quote(uint amountA, uint reserveA, uint reserveB) internal pure returns (uint amountB) {
                  require(amountA > 0, 'UniswapV2Library: INSUFFICIENT_AMOUNT');
                  require(reserveA > 0 && reserveB > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY');
                  amountB = amountA.mul(reserveB) / reserveA;
              }
              // given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset
              function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) internal pure returns (uint amountOut) {
                  require(amountIn > 0, 'UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT');
                  require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY');
                  uint amountInWithFee = amountIn.mul(1000); //997
                  uint numerator = amountInWithFee.mul(reserveOut);
                  uint denominator = reserveIn.mul(1000).add(amountInWithFee);
                  amountOut = numerator / denominator;
              }
              // given an output amount of an asset and pair reserves, returns a required input amount of the other asset
              function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) internal pure returns (uint amountIn) {
                  require(amountOut > 0, 'UniswapV2Library: INSUFFICIENT_OUTPUT_AMOUNT');
                  require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY');
                  uint numerator = reserveIn.mul(amountOut).mul(1000);
                  uint denominator = reserveOut.sub(amountOut).mul(1000); //997
                  amountIn = (numerator / denominator).add(1);
              }
              // performs chained getAmountOut calculations on any number of pairs
              function getAmountsOut(address factory, uint amountIn, address[] memory path) internal view returns (uint[] memory amounts) {
                  require(path.length >= 2, 'UniswapV2Library: INVALID_PATH');
                  amounts = new uint[](path.length);
                  amounts[0] = amountIn;
                  for (uint i; i < path.length - 1; i++) {
                      (uint reserveIn, uint reserveOut) = getReserves(factory, path[i], path[i + 1]);
                      amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut);
                  }
              }
              // performs chained getAmountIn calculations on any number of pairs
              function getAmountsIn(address factory, uint amountOut, address[] memory path) internal view returns (uint[] memory amounts) {
                  require(path.length >= 2, 'UniswapV2Library: INVALID_PATH');
                  amounts = new uint[](path.length);
                  amounts[amounts.length - 1] = amountOut;
                  for (uint i = path.length - 1; i > 0; i--) {
                      (uint reserveIn, uint reserveOut) = getReserves(factory, path[i - 1], path[i]);
                      amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut);
                  }
              }
          }
          interface IEtherVistaFactory {
              event PairCreated(address indexed token0, address indexed token1, address pair, uint);
              function feeTo() external view returns (address);
              function feeToSetter() external view returns (address);
              function routerSetter() external view returns (address);
              function router() external view returns (address);
              function getPair(address tokenA, address tokenB) external view returns (address pair);
              function allPairs(uint) external view returns (address pair);
              function allPairsLength() external view returns (uint);
              function createPair(address tokenA, address tokenB) external returns (address pair);
              function setFeeTo(address) external;
              function setFeeToSetter(address) external;
              function setRouterSetter(address) external;
              function setRouter(address) external;
          }
          library TransferHelper {
              function safeApprove(
                  address token,
                  address to,
                  uint256 value
              ) internal {
                  // bytes4(keccak256(bytes('approve(address,uint256)')));
                  (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value));
                  require(
                      success && (data.length == 0 || abi.decode(data, (bool))),
                      'TransferHelper::safeApprove: approve failed'
                  );
              }
              function safeTransfer(
                  address token,
                  address to,
                  uint256 value
              ) internal {
                  // bytes4(keccak256(bytes('transfer(address,uint256)')));
                  (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));
                  require(
                      success && (data.length == 0 || abi.decode(data, (bool))),
                      'TransferHelper::safeTransfer: transfer failed'
                  );
              }
              function safeTransferFrom(
                  address token,
                  address from,
                  address to,
                  uint256 value
              ) internal {
                  // bytes4(keccak256(bytes('transferFrom(address,address,uint256)')));
                  (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value));
                  require(
                      success && (data.length == 0 || abi.decode(data, (bool))),
                      'TransferHelper::transferFrom: transferFrom failed'
                  );
              }
              function safeTransferETH(address to, uint256 value) internal {
                  (bool success, ) = to.call{value: value}(new bytes(0));
                  require(success, 'TransferHelper::safeTransferETH: ETH transfer failed');
              }
          }
          interface IERC20 {
              event Approval(address indexed owner, address indexed spender, uint value);
              event Transfer(address indexed from, address indexed to, uint value);
              function name() external view returns (string memory);
              function symbol() external view returns (string memory);
              function decimals() external view returns (uint8);
              function totalSupply() external view returns (uint);
              function balanceOf(address owner) external view returns (uint);
              function allowance(address owner, address spender) external view returns (uint);
              function approve(address spender, uint value) external returns (bool);
              function transfer(address to, uint value) external returns (bool);
              function transferFrom(address from, address to, uint value) external returns (bool);
          }
          interface IWETH {
              function deposit() external payable;
              function transfer(address to, uint value) external returns (bool);
              function withdraw(uint) external;
          }
          interface AggregatorV3Interface {
            function decimals()
              external
              view
              returns (
                uint8
              );
            function description()
              external
              view
              returns (
                string memory
              );
            function version()
              external
              view
              returns (
                uint256
              );
            function getRoundData(
              uint80 _roundId
            )
              external
              view
              returns (
                uint80 roundId,
                int256 answer,
                uint256 startedAt,
                uint256 updatedAt,
                uint80 answeredInRound
              );
            function latestRoundData()
              external
              view
              returns (
                uint80 roundId,
                int256 answer,
                uint256 startedAt,
                uint256 updatedAt,
                uint80 answeredInRound
              );
          }
          contract EtherVistaRouter is IEtherVistaRouter {
              using SafeMath for uint;
              address public immutable override factory;
              address public immutable override WETH;
              address payable public treasury;
              AggregatorV3Interface internal priceFeed;
              modifier ensure(uint deadline) {
                  require(deadline >= block.timestamp, 'EtherVista: EXPIRED');
                  _;
              }
              constructor(address _factory, address _WETH, address _oracleAddress ) public {
                  factory = _factory;
                  WETH = _WETH;
                  priceFeed = AggregatorV3Interface(_oracleAddress);
                  treasury = msg.sender;
              }
              receive() external payable {
                  assert(msg.sender == WETH); // only accept ETH via fallback from the WETH contract
              }
              function getEthUsdcPrice() internal view returns (uint256) {
                  (, int256 price, , , ) = priceFeed.latestRoundData();
                  require(price > 0, "Invalid price");
                  return uint256(price/100); 
              }
              function usdcToEth(uint256 usdcAmount) public view returns (uint256) {
                  uint256 ethUsdcPrice = getEthUsdcPrice();
                  return (usdcAmount * 1e6*1e18 / ethUsdcPrice); 
              }
          // **** ADD LIQUIDITY ****
              function _addLiquidity(
                  address tokenA,
                  address tokenB,
                  uint amountADesired,
                  uint amountBDesired,
                  uint amountAMin,
                  uint amountBMin
              ) internal virtual returns (uint amountA, uint amountB) {
                  // create the pair if it doesn't exist yet
                  if (IEtherVistaFactory(factory).getPair(tokenA, tokenB) == address(0)) {
                      IEtherVistaFactory(factory).createPair(tokenA, tokenB);
                  }
                  (uint reserveA, uint reserveB) = UniswapV2Library.getReserves(factory, tokenA, tokenB);
                  if (reserveA == 0 && reserveB == 0) {
                      (amountA, amountB) = (amountADesired, amountBDesired);
                  } else {
                      uint amountBOptimal = UniswapV2Library.quote(amountADesired, reserveA, reserveB);
                      if (amountBOptimal <= amountBDesired) {
                          require(amountBOptimal >= amountBMin, 'EtherVistaRouter: INSUFFICIENT_B_AMOUNT');
                          (amountA, amountB) = (amountADesired, amountBOptimal);
                      } else {
                          uint amountAOptimal = UniswapV2Library.quote(amountBDesired, reserveB, reserveA);
                          assert(amountAOptimal <= amountADesired);
                          require(amountAOptimal >= amountAMin, 'EtherVistaRouter: INSUFFICIENT_A_AMOUNT');
                          (amountA, amountB) = (amountAOptimal, amountBDesired);
                      }
                  }
              }
              function launch(
                  address token,
                  uint amountTokenDesired,
                  uint amountTokenMin,
                  uint amountETHMin,
                  uint8 buyLpFee, 
                  uint8 sellLpFee, 
                  uint8 buyProtocolFee, 
                  uint8 sellProtocolFee, 
                  address protocolAddress
              ) external virtual override payable returns (uint amountToken, uint amountETH, uint liquidity) {
                  (amountToken, amountETH) = _addLiquidity(
                      token,
                      WETH,
                      amountTokenDesired,
                      msg.value,
                      amountTokenMin, 
                      amountETHMin
                  );
                  address pair = UniswapV2Library.pairFor(factory, token, WETH);
                  TransferHelper.safeTransferFrom(token, msg.sender, pair, amountToken);
                  IWETH(WETH).deposit{value: amountETH}();
                  assert(IWETH(WETH).transfer(pair, amountETH));
                  liquidity = IEtherVistaPair(pair).first_mint(msg.sender, buyLpFee, sellLpFee, buyProtocolFee, sellProtocolFee, protocolAddress);
                  IEtherVistaPair(UniswapV2Library.pairFor(factory, token, WETH)).updateProvider(msg.sender);
                  
                  // refund dust eth, if any
                  if (msg.value > amountETH) TransferHelper.safeTransferETH(msg.sender, msg.value - amountETH);
              }
              function addLiquidityETH(
                  address token,
                  uint amountTokenDesired,
                  uint amountTokenMin,
                  uint amountETHMin,
                  uint deadline
              ) external virtual override payable ensure(deadline) returns (uint amountToken, uint amountETH, uint liquidity) {
                  (amountToken, amountETH) = _addLiquidity(
                      token,
                      WETH,
                      amountTokenDesired,
                      msg.value,
                      amountTokenMin,
                      amountETHMin
                  );
                  address pair = UniswapV2Library.pairFor(factory, token, WETH);
                  TransferHelper.safeTransferFrom(token, msg.sender, pair, amountToken);
                  IWETH(WETH).deposit{value: amountETH}();
                  assert(IWETH(WETH).transfer(pair, amountETH));
                  liquidity = IEtherVistaPair(pair).mint(msg.sender);
                  IEtherVistaPair(UniswapV2Library.pairFor(factory, token, WETH)).updateProvider(msg.sender);
                  
                  // refund dust eth, if any
                  if (msg.value > amountETH) TransferHelper.safeTransferETH(msg.sender, msg.value - amountETH);
              }
          // **** REMOVE LIQUIDITY ****
              function removeLiquidity(
                  address tokenA,     
                  address tokenB,      
                  uint liquidity,
                  uint amountAMin,
                  uint amountBMin,
                  address to, 
                  uint deadline
              ) internal ensure(deadline) returns (uint amountA, uint amountB) {
                  address pair = UniswapV2Library.pairFor(factory, tokenA, tokenB);
                  IEtherVistaPair(pair).transferFrom(msg.sender, pair, liquidity); // send liquidity to pair
                  (uint amount0, uint amount1) = IEtherVistaPair(pair).burn(to);
                  (address token0,) = UniswapV2Library.sortTokens(tokenA, tokenB);
                  (amountA, amountB) = tokenA == token0 ? (amount0, amount1) : (amount1, amount0);
                  require(amountA >= amountAMin, 'EtherVistaRouter: INSUFFICIENT_A_AMOUNT');
                  require(amountB >= amountBMin, 'EtherVistaRouter: INSUFFICIENT_B_AMOUNT');
              }
          // **** REMOVE LIQUIDITY (supporting fee-on-transfer tokens) ****
              function removeLiquidityETHSupportingFeeOnTransferTokens(
                  address token,
                  uint liquidity,
                  uint amountTokenMin,
                  uint amountETHMin,
                  uint deadline
              ) public virtual override ensure(deadline) returns (uint amountETH) {
                  (, amountETH) = removeLiquidity(
                      token,
                      WETH,
                      liquidity,
                      amountTokenMin,
                      amountETHMin,
                      address(this),
                      deadline
                  );
                  IEtherVistaPair(UniswapV2Library.pairFor(factory, token, WETH)).updateProvider(msg.sender);
                  TransferHelper.safeTransfer(token, msg.sender, IERC20(token).balanceOf(address(this)));
                  IWETH(WETH).withdraw(amountETH);
                  TransferHelper.safeTransferETH(msg.sender, amountETH);
              }
          // **** SWAP (supporting fee-on-transfer tokens) ****
          // requires the initial amount to have already been sent to the first pair
              function _swapSupportingFeeOnTransferTokens(address[] memory path, address _to) internal virtual {
                  for (uint i; i < path.length - 1; i++) {
                      (address input, address output) = (path[i], path[i + 1]);
                      (address token0,) = UniswapV2Library.sortTokens(input, output);
                      IEtherVistaPair pair = IEtherVistaPair(UniswapV2Library.pairFor(factory, input, output));
                      uint amountInput;
                      uint amountOutput;
                      { // scope to avoid stack too deep errors
                      (uint reserve0, uint reserve1,) = pair.getReserves();
                      (uint reserveInput, uint reserveOutput) = input == token0 ? (reserve0, reserve1) : (reserve1, reserve0);
                      amountInput = IERC20(input).balanceOf(address(pair)).sub(reserveInput);
                      amountOutput = UniswapV2Library.getAmountOut(amountInput, reserveInput, reserveOutput);
                      }
                      (uint amount0Out, uint amount1Out) = input == token0 ? (uint(0), amountOutput) : (amountOutput, uint(0));
                      address to = i < path.length - 2 ? UniswapV2Library.pairFor(factory, output, path[i + 2]) : _to;
                      pair.swap(amount0Out, amount1Out, to, new bytes(0));
                  }
              }
              function swapExactETHForTokensSupportingFeeOnTransferTokens(
                  uint amountOutMin,
                  address[] calldata path,
                  address to,
                  uint deadline
              )
                  external
                  virtual
                  override
                  payable
                  ensure(deadline)
              {
                  IEtherVistaPair Pair = IEtherVistaPair(UniswapV2Library.pairFor(factory, path[0], path[1]));
                  require(path[0] == WETH, 'EtherVistaRouter: INVALID_PATH');
                  require(msg.value > usdcToEth(Pair.buyTotalFee()), 'EtherVistaRouter: INSUFFICIENT_ETH_FEE'); 
                  uint amountIn = msg.value-usdcToEth(Pair.buyTotalFee());
                  IWETH(WETH).deposit{value: amountIn}();
                  assert(IWETH(WETH).transfer(UniswapV2Library.pairFor(factory, path[0], path[1]), amountIn));
                  uint balanceBefore = IERC20(path[path.length - 1]).balanceOf(to);
                  _swapSupportingFeeOnTransferTokens(path, to);
                  require(
                      IERC20(path[path.length - 1]).balanceOf(to).sub(balanceBefore) >= amountOutMin,
                      'EtherVistaRouter: INSUFFICIENT_OUTPUT_AMOUNT'
                  );
                  treasury.transfer(usdcToEth(1)); 
                  (bool sent1, ) = IEtherVistaPair(UniswapV2Library.pairFor(factory, path[0], path[1])).payableProtocol().call{value: usdcToEth(Pair.buyProtocolFee())}("");
                  (bool sent2,) = UniswapV2Library.pairFor(factory, path[0], path[1]).call{value: usdcToEth(Pair.buyLpFee())}("");
                  require(sent1 && sent2, "Failed to send Ether"); 
              }
              function swapExactTokensForETHSupportingFeeOnTransferTokens(
                  uint amountIn,
                  uint amountOutMin,
                  address[] calldata path,
                  address to,
                  uint deadline
              )
                  external
                  payable
                  virtual
                  override
                  ensure(deadline)
              {
                  IEtherVistaPair Pair = IEtherVistaPair(UniswapV2Library.pairFor(factory, path[0], path[1]));
                  require(path[path.length - 1] == WETH, 'EtherVistaRouter: INVALID_PATH');
                  require(msg.value >= usdcToEth(Pair.sellTotalFee()), 'EtherVistaRouter: INSUFFICIENT_ETH_FEE'); 
                  TransferHelper.safeTransferFrom(
                      path[0], msg.sender, UniswapV2Library.pairFor(factory, path[0], path[1]), amountIn
                  );
                  _swapSupportingFeeOnTransferTokens(path, address(this));
                  uint amountOut = IERC20(WETH).balanceOf(address(this));
                  require(amountOut >= amountOutMin, 'EtherVistaRouter: INSUFFICIENT_OUTPUT_AMOUNT');
                  treasury.transfer(usdcToEth(1)); 
                  (bool sent1, ) = IEtherVistaPair(UniswapV2Library.pairFor(factory, path[0], path[1])).payableProtocol().call{value: usdcToEth(Pair.sellProtocolFee())}("");
                  (bool sent2,) = UniswapV2Library.pairFor(factory, path[0], path[1]).call{value: usdcToEth(Pair.sellLpFee())}("");
                  require(sent1 && sent2, "Failed to send Ether"); 
                  IWETH(WETH).withdraw(amountOut);
                  TransferHelper.safeTransferETH(to, amountOut);
              }
          // **** LIBRARY FUNCTIONS ****
              function quote(uint amountA, uint reserveA, uint reserveB) public pure virtual override returns (uint amountB) {
                  return UniswapV2Library.quote(amountA, reserveA, reserveB);
              }
              function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut)
                  public
                  pure
                  virtual
                  override
                  returns (uint amountOut)
              {
                  return UniswapV2Library.getAmountOut(amountIn, reserveIn, reserveOut);
              }
              function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut)
                  public
                  pure
                  virtual
                  override
                  returns (uint amountIn)
              {
                  return UniswapV2Library.getAmountIn(amountOut, reserveIn, reserveOut);
              }
              function getAmountsOut(uint amountIn, address[] memory path)
                  public
                  view
                  virtual
                  override
                  returns (uint[] memory amounts)
              {
                  return UniswapV2Library.getAmountsOut(factory, amountIn, path);
              }
              function getAmountsIn(uint amountOut, address[] memory path)
                  public
                  view
                  virtual
                  override
                  returns (uint[] memory amounts)
              {
                  return UniswapV2Library.getAmountsIn(factory, amountOut, path);
              }
          }
          pragma solidity >=0.6.2;
          interface IEtherVistaRouter {
              function factory() external pure returns (address);
              function WETH() external pure returns (address);
              function addLiquidityETH(
                  address token,
                  uint amountTokenDesired,
                  uint amountTokenMin,
                  uint amountETHMin,
                  uint deadline
              ) external payable returns (uint amountToken, uint amountETH, uint liquidity);
              function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
              function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
              function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
              function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
              function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
              function removeLiquidityETHSupportingFeeOnTransferTokens(
                  address token,
                  uint liquidity,
                  uint amountTokenMin,
                  uint amountETHMin,
                  uint deadline
              ) external returns (uint amountETH);
           
              function swapExactETHForTokensSupportingFeeOnTransferTokens(
                  uint amountOutMin,
                  address[] calldata path,
                  address to,
                  uint deadline
              ) external payable;
              function swapExactTokensForETHSupportingFeeOnTransferTokens(
                  uint amountIn,
                  uint amountOutMin,
                  address[] calldata path,
                  address to,
                  uint deadline
              ) external payable;
              function launch(
                  address token,
                  uint amountTokenDesired,
                  uint amountTokenMin,
                  uint amountETHMin,
                  uint8 buyLpFee, 
                  uint8 sellLpFee, 
                  uint8 buyProtocolFee, 
                  uint8 sellProtocolFee, 
                  address protocolAddress
              ) external payable returns (uint amountToken, uint amountETH, uint liquidity);
          }

          File 2 of 7: EtherVistaPair
          pragma solidity =0.5.16;
          interface IEtherVistaPair {
              event Approval(address indexed owner, address indexed spender, uint value);
              event Transfer(address indexed from, address indexed to, uint value);
              
              function setMetadata(string calldata website, string calldata image, string calldata description, string calldata chat, string calldata social) external;
              function fetchMetadata() external view returns(string memory, string memory, string memory, string memory, string memory);
              function name() external pure returns (string memory);
              function symbol() external pure returns (string memory);
              function decimals() external pure returns (uint8);
              function totalSupply() external view returns (uint);
              function balanceOf(address owner) external view returns (uint);
              function allowance(address owner, address spender) external view returns (uint);
              function updateProvider(address user) external;
              function euler(uint) external view returns (uint256);
              function viewShare() external view returns (uint256 share);
              function claimShare() external;
              function poolBalance() external view returns (uint);
              function totalCollected() external view returns (uint);
              
              function updateProtocol(address) external;
              function setProtocol() external;
              function protocol() external view returns (address);
              function payableProtocol() external view returns (address payable origin);
              function creator() external view returns (address);
              function renounce() external;
              function setFees() external;
              function updateFees(uint8, uint8, uint8, uint8) external;
              function buyLpFee() external view returns (uint8);
              function sellLpFee() external view returns (uint8);
              function buyProtocolFee() external view returns (uint8);
              function sellProtocolFee() external view returns (uint8);
              function buyTotalFee() external view returns (uint8);
              function sellTotalFee() external view returns (uint8);
              function approve(address spender, uint value) external returns (bool);
              function transfer(address to, uint value) external returns (bool);
              function transferFrom(address from, address to, uint value) external returns (bool);
              function DOMAIN_SEPARATOR() external view returns (bytes32);
              function PERMIT_TYPEHASH() external pure returns (bytes32);
              function nonces(address owner) external view returns (uint);
              function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
              event Mint(address indexed sender, uint amount0, uint amount1);
              event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
              event Swap(
                  address indexed sender,
                  uint amount0In,
                  uint amount1In,
                  uint amount0Out,
                  uint amount1Out,
                  address indexed to
              );
              event Sync(uint112 reserve0, uint112 reserve1);
              function MINIMUM_LIQUIDITY() external pure returns (uint);
              function factory() external view returns (address);
              function token0() external view returns (address);
              function token1() external view returns (address);
              function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
              function price0CumulativeLast() external view returns (uint);
              function price1CumulativeLast() external view returns (uint);
              function kLast() external view returns (uint);
              function first_mint(address to, uint8 buyLp, uint8 sellLp, uint8 buyProtocol, uint8 sellProtocol, address protocolAddress) external returns (uint liquidity);   
              function mint(address to) external returns (uint liquidity);
              function burn(address to) external returns (uint amount0, uint amount1);
              function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
              function skim(address to) external;
              function sync() external;
              function initialize(address _token0, address _token1) external;
          }
          interface IEtherVistaERC20 {
              event Approval(address indexed owner, address indexed spender, uint value);
              event Transfer(address indexed from, address indexed to, uint value);
              function name() external pure returns (string memory);
              function symbol() external pure returns (string memory);
              function decimals() external pure returns (uint8);
              function totalSupply() external view returns (uint);
              function balanceOf(address owner) external view returns (uint);
              function allowance(address owner, address spender) external view returns (uint);
              function approve(address spender, uint value) external returns (bool);
              function transfer(address to, uint value) external returns (bool);
              function transferFrom(address from, address to, uint value) external returns (bool);
              function DOMAIN_SEPARATOR() external view returns (bytes32);
              function PERMIT_TYPEHASH() external pure returns (bytes32);
              function nonces(address owner) external view returns (uint);
              function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
          }
          interface IERC20 {
              event Approval(address indexed owner, address indexed spender, uint value);
              event Transfer(address indexed from, address indexed to, uint value);
              function name() external view returns (string memory);
              function symbol() external view returns (string memory);
              function decimals() external view returns (uint8);
              function totalSupply() external view returns (uint);
              function balanceOf(address owner) external view returns (uint);
              function allowance(address owner, address spender) external view returns (uint);
              function approve(address spender, uint value) external returns (bool);
              function transfer(address to, uint value) external returns (bool);
              function transferFrom(address from, address to, uint value) external returns (bool);
          }
          interface IEtherVistaFactory {
              event PairCreated(address indexed token0, address indexed token1, address pair, uint);
              function feeTo() external view returns (address);
              function feeToSetter() external view returns (address);
              function routerSetter() external view returns (address);
              function router() external view returns (address);
              function getPair(address tokenA, address tokenB) external view returns (address pair);
              function allPairs(uint) external view returns (address pair);
              function allPairsLength() external view returns (uint);
              function createPair(address tokenA, address tokenB) external returns (address pair);
              function setFeeTo(address) external;
              function setFeeToSetter(address) external;
              function setRouterSetter(address) external;
              function setRouter(address) external;
          }
          interface IUniswapV2Callee {
              function uniswapV2Call(address sender, uint amount0, uint amount1, bytes calldata data) external;
          }
          library SafeMath {
              function add(uint x, uint y) internal pure returns (uint z) {
                  require((z = x + y) >= x, 'ds-math-add-overflow');
              }
              function sub(uint x, uint y) internal pure returns (uint z) {
                  require((z = x - y) <= x, 'ds-math-sub-underflow');
              }
              function mul(uint x, uint y) internal pure returns (uint z) {
                  require(y == 0 || (z = x * y) / y == x, 'ds-math-mul-overflow');
              }
          }
          library Math {
              function min(uint x, uint y) internal pure returns (uint z) {
                  z = x < y ? x : y;
              }
              // babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method)
              function sqrt(uint y) internal pure returns (uint z) {
                  if (y > 3) {
                      z = y;
                      uint x = y / 2 + 1;
                      while (x < z) {
                          z = x;
                          x = (y / x + x) / 2;
                      }
                  } else if (y != 0) {
                      z = 1;
                  }
              }
          }
          library UQ112x112 {
              uint224 constant Q112 = 2**112;
              // encode a uint112 as a UQ112x112
              function encode(uint112 y) internal pure returns (uint224 z) {
                  z = uint224(y) * Q112; // never overflows
              }
              // divide a UQ112x112 by a uint112, returning a UQ112x112
              function uqdiv(uint224 x, uint112 y) internal pure returns (uint224 z) {
                  z = x / uint224(y);
              }
          }
          contract EtherVistaERC20 is IEtherVistaERC20 {
              using SafeMath for uint;
              string public constant name = 'VISTA';
              string public constant symbol = 'VISTA-LP';
              uint8 public constant decimals = 18;
              uint public totalSupply;
              address public factory;
              mapping(address => uint) public balanceOf;
              mapping(address => mapping(address => uint)) public allowance;
              bytes32 public DOMAIN_SEPARATOR;
              // keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
              bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
              mapping(address => uint) public nonces;
              event Approval(address indexed owner, address indexed spender, uint value);
              event Transfer(address indexed from, address indexed to, uint value);
              constructor() public {
                  uint chainId;
                  assembly {
                      chainId := chainid
                  }
                  factory = msg.sender;
                  DOMAIN_SEPARATOR = keccak256(
                      abi.encode(
                          keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)'),
                          keccak256(bytes(name)),
                          keccak256(bytes('1')),
                          chainId,
                          address(this)
                      )
                  );
              }
              function _mint(address to, uint value) internal {
                  totalSupply = totalSupply.add(value);
                  balanceOf[to] = balanceOf[to].add(value);
                  emit Transfer(address(0), to, value);
              }
              function _burn(address from, uint value) internal {
                  balanceOf[from] = balanceOf[from].sub(value);
                  totalSupply = totalSupply.sub(value);
                  emit Transfer(from, address(0), value);
              }
              function _approve(address owner, address spender, uint value) private {
                  allowance[owner][spender] = value;
                  emit Approval(owner, spender, value);
              }
              function _transfer(address from, address to, uint value) private {
                  balanceOf[from] = balanceOf[from].sub(value);
                  balanceOf[to] = balanceOf[to].add(value);
                  emit Transfer(from, to, value);
              }
              function transfer(address to, uint value) external returns (bool) {
                  if (to != 0x000000000000000000000000000000000000dEaD) {
                  require(msg.sender == IEtherVistaFactory(factory).router(), 'EtherVistaPair: FORBIDDEN');
                  }
                  _transfer(msg.sender, to, value);
                  return true;
              }
              function approve(address spender, uint value) external returns (bool) {
                  require(spender == IEtherVistaFactory(factory).router(), 'EtherVistaPair: FORBIDDEN');
                  _approve(msg.sender, spender, value);
                  return true;
              }
              function transferFrom(address from, address to, uint value) external returns (bool) {
                  require(msg.sender == IEtherVistaFactory(factory).router(), 'EtherVistaPair: FORBIDDEN');
                  if (allowance[from][msg.sender] != uint(-1)) {
                      allowance[from][msg.sender] = allowance[from][msg.sender].sub(value);
                  }
                  _transfer(from, to, value);
                  return true;
              }
              function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external {
                  require(deadline >= block.timestamp, 'EtherVista: EXPIRED');
                  require(spender == IEtherVistaFactory(factory).router(), 'EtherVistaPair: FORBIDDEN');
                  bytes32 digest = keccak256(
                      abi.encodePacked(
                          '\\x19\\x01',
                          DOMAIN_SEPARATOR,
                          keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline))
                      )
                  );
                  address recoveredAddress = ecrecover(digest, v, r, s);
                  require(recoveredAddress != address(0) && recoveredAddress == owner, 'EtherVista: INVALID_SIGNATURE');
                  _approve(owner, spender, value);
              }
          }
          contract EtherVistaPair is IEtherVistaPair, EtherVistaERC20 {
              using SafeMath  for uint;
              using UQ112x112 for uint224;
              uint public constant MINIMUM_LIQUIDITY = 10**3;
              uint256 private bigNumber = 10**20; //prevents liqFee/totalSupply from rounding to 0.
              bytes4 private constant SELECTOR = bytes4(keccak256(bytes('transfer(address,uint256)')));
              address public factory;
              address public token0;
              address public token1;
              uint8 public buyLpFee;
              uint8 public sellLpFee;
              uint8 public buyProtocolFee; 
              uint8 public sellProtocolFee;
              uint8 public buyTotalFee;
              uint8 public sellTotalFee;
              uint256 public startTime_fees = 0; 
              uint8 public future_buyLpFee;
              uint8 public future_sellLpFee;
              uint8 public future_buyProtocolFee;
              uint8 public future_sellProtocolFee ;
              uint256 public totalCollected;
              uint public poolBalance;
              uint256 public startTime_protocol = 0;
              address public protocol;
              address public future_protocol;
              address public creator; 
              uint256 public creation_time; 
              string public websiteUrl = "Null";
              string public imageUrl = "Null"; //IPFS link
              string public tokenDescription = "Null";
              string public chatUrl = "Null";
              string public socialUrl = "Null";
              struct Provider {
                  uint256 lp;
                  uint256 euler0;
              }
              uint256[] public euler; 
              mapping(address => Provider) public Providers;
              uint112 private reserve0;           // uses single storage slot, accessible via getReserves
              uint112 private reserve1;           // uses single storage slot, accessible via getReserves
              uint32  private blockTimestampLast; // uses single storage slot, accessible via getReserves
              uint public price0CumulativeLast;
              uint public price1CumulativeLast;
              uint public kLast; // reserve0 * reserve1, as of immediately after the most recent liquidity event
              uint private unlocked = 1;
              modifier lock() {
                  require(unlocked == 1, 'EtherVista: LOCKED');
                  unlocked = 0;
                  _;
                  unlocked = 1;
              }
              //called everytime a swap is performed
              function() external payable {
                  require(msg.sender == IEtherVistaFactory(factory).router(), 'EtherVistaPair: FORBIDDEN');
                  poolBalance += msg.value;
                  totalCollected += msg.value;
                  updateEuler(msg.value);
              }
              //updates the euler constant - occurs everytime a swap is performed
              function updateEuler(uint256 liqFee) internal { 
                  if (euler.length == 0){
                      euler.push((liqFee*bigNumber)/totalSupply);
                  }else{
                      euler.push(euler[euler.length - 1] + (liqFee*bigNumber)/totalSupply); 
                  }
              }
              //called everytime liquidity is added/removed by the user
              function updateProvider(address user) external  { 
                  require(msg.sender == IEtherVistaFactory(factory).router(), 'EtherVistaPair: FORBIDDEN');
                  if (euler.length == 0){
                      Providers[user] = Provider(balanceOf[user], 0); 
                  }else{
                      Providers[user] = Provider(balanceOf[user], euler[euler.length - 1]);
                  }
              }
              function claimShare() public lock {
                  require(euler.length > 0, 'EtherVistaPair: Nothing to Claim');
                  uint256 share = (Providers[msg.sender].lp * (euler[euler.length - 1] - Providers[msg.sender].euler0))/bigNumber;
                  Providers[msg.sender] = Provider(balanceOf[msg.sender], euler[euler.length - 1]);
                  poolBalance -= share;
                  (bool sent,) = msg.sender.call.value(share)("");
                  require(sent, "Failed to send Ether"); 
              }
              
              function viewShare() public view returns (uint256 share) {
                  if (euler.length == 0){
                      return 0;
                  }else{
                      return Providers[msg.sender].lp * (euler[euler.length - 1] - Providers[msg.sender].euler0)/bigNumber;
                  }
              }
              function updateFees(uint8 buyLpFuture, uint8 sellLpFuture, uint8 buyProtocolFuture, uint8 sellProtocolFuture) external {
                  require(msg.sender == creator);
                  startTime_fees = block.timestamp;
                  future_buyLpFee = buyLpFuture;  
                  future_sellLpFee = sellLpFuture;  
                  future_buyProtocolFee = buyProtocolFuture;
                  future_sellProtocolFee = sellProtocolFuture;
              }
              function setFees() external {
                  require(startTime_fees != 0);
                  require(msg.sender == creator && block.timestamp - startTime_fees >= 3 days);
                  buyLpFee = future_buyLpFee;
                  sellLpFee = future_sellLpFee;
                  buyProtocolFee = future_buyProtocolFee;
                  sellProtocolFee = future_sellProtocolFee;
                  buyTotalFee =  future_buyLpFee + future_buyProtocolFee + 1;
                  sellTotalFee = future_sellLpFee + future_sellProtocolFee + 1;
              }
              function updateProtocol(address protocolFuture) external {
                  require(msg.sender == creator);
                  startTime_protocol = block.timestamp;
                  future_protocol = protocolFuture;
              }
              function setProtocol() external {
                  require(startTime_protocol != 0);
                  require(msg.sender == creator && block.timestamp - startTime_protocol >= 3 days);
                  protocol = future_protocol;
              }
              function payableProtocol() external view returns (address payable) {
                  return address(uint160(protocol));
              }
              function setMetadata(string calldata website, string calldata image, string calldata description, string calldata chat, string calldata social) external {
                  require(msg.sender == creator);
                  websiteUrl = website;
                  imageUrl = image;
                  tokenDescription = description;
                  chatUrl = chat;
                  socialUrl = social;
              }
              function fetchMetadata() public view returns(string memory, string memory, string memory, string memory, string memory) {
                  return (websiteUrl, imageUrl, tokenDescription, chatUrl, socialUrl);
              }
              function renounce() external {
                  require(msg.sender == creator);
                  creator = 0x000000000000000000000000000000000000dEaD;
              }
              function getReserves() public view returns (uint112 _reserve0, uint112 _reserve1, uint32 _blockTimestampLast) {
                  _reserve0 = reserve0;
                  _reserve1 = reserve1;
                  _blockTimestampLast = blockTimestampLast;
              }
              function _safeTransfer(address token, address to, uint value) private {
                  (bool success, bytes memory data) = token.call(abi.encodeWithSelector(SELECTOR, to, value));
                  require(success && (data.length == 0 || abi.decode(data, (bool))), 'EtherVista: TRANSFER_FAILED');
              }
              event Mint(address indexed sender, uint amount0, uint amount1);
              event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
              event Swap(
                  address indexed sender,
                  uint amount0In,
                  uint amount1In,
                  uint amount0Out,
                  uint amount1Out,
                  address indexed to
              );
              event Sync(uint112 reserve0, uint112 reserve1);
              constructor() public {
                  factory = msg.sender;
              }
              // called once by the factory at time of deployment
              function initialize(address _token0, address _token1) external {
                  require(msg.sender == factory, 'EtherVistaPair: FORBIDDEN'); // sufficient check
                  token0 = _token0;
                  token1 = _token1;
              }
              // update reserves and, on the first call per block, price accumulators
              function _update(uint balance0, uint balance1, uint112 _reserve0, uint112 _reserve1) private {
                  require(balance0 <= uint112(-1) && balance1 <= uint112(-1), 'EtherVistaPair: OVERFLOW');
                  uint32 blockTimestamp = uint32(block.timestamp % 2**32);
                  uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired
                  if (timeElapsed > 0 && _reserve0 != 0 && _reserve1 != 0) {
                      // * never overflows, and + overflow is desired
                      price0CumulativeLast += uint(UQ112x112.encode(_reserve1).uqdiv(_reserve0)) * timeElapsed;
                      price1CumulativeLast += uint(UQ112x112.encode(_reserve0).uqdiv(_reserve1)) * timeElapsed;
                  }
                  reserve0 = uint112(balance0);
                  reserve1 = uint112(balance1);
                  blockTimestampLast = blockTimestamp;
                  emit Sync(reserve0, reserve1);
              }
              // if fee is on, mint liquidity equivalent to 1/6th of the growth in sqrt(k). This will never be on.
              function _mintFee(uint112 _reserve0, uint112 _reserve1) private returns (bool feeOn) {
                  address feeTo = IEtherVistaFactory(factory).feeTo();
                  feeOn = feeTo != address(0);
                  uint _kLast = kLast; // gas savings
                  if (feeOn) {
                      if (_kLast != 0) {
                          uint rootK = Math.sqrt(uint(_reserve0).mul(_reserve1));
                          uint rootKLast = Math.sqrt(_kLast);
                          if (rootK > rootKLast) {
                              uint numerator = totalSupply.mul(rootK.sub(rootKLast));
                              uint denominator = rootK.mul(5).add(rootKLast);
                              uint liquidity = numerator / denominator;
                              if (liquidity > 0) _mint(feeTo, liquidity);
                          }
                      }
                  } else if (_kLast != 0) {
                      kLast = 0;
                  }
              }
              // this low-level function should be called from a contract which performs important safety checks
              function first_mint(address to, uint8 buyLp, uint8 sellLp, uint8 buyProtocol, uint8 sellProtocol, address protocolAddress) external lock returns (uint liquidity) {
                  require(msg.sender == IEtherVistaFactory(factory).router(), 'EtherVistaPair: FORBIDDEN');
                  (uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
                  uint balance0 = IERC20(token0).balanceOf(address(this));
                  uint balance1 = IERC20(token1).balanceOf(address(this));
                  uint amount0 = balance0.sub(_reserve0);
                  uint amount1 = balance1.sub(_reserve1);
                  bool feeOn = _mintFee(_reserve0, _reserve1);
                  uint _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee
                  require(_totalSupply == 0);
                  liquidity = Math.sqrt(amount0.mul(amount1)).sub(MINIMUM_LIQUIDITY);
                  _mint(address(0), MINIMUM_LIQUIDITY); // permanently lock the first MINIMUM_LIQUIDITY tokens
                  creator = to;
                  creation_time = block.timestamp;
                  protocol = protocolAddress;
                  buyLpFee = buyLp;
                  sellLpFee = sellLp;
                  buyProtocolFee = buyProtocol;
                  sellProtocolFee = sellProtocol;
                  buyTotalFee =  buyLp + buyProtocol + 1;
                  sellTotalFee = sellLp + sellProtocol + 1;
                  
                  require(liquidity > 0, 'EtherVistaPair: INSUFFICIENT_LIQUIDITY_MINTED');
                  _mint(to, liquidity);
                  _update(balance0, balance1, _reserve0, _reserve1);
                  if (feeOn) kLast = uint(reserve0).mul(reserve1); // reserve0 and reserve1 are up-to-date
                  emit Mint(msg.sender, amount0, amount1);
              }
              // this low-level function should be called from a contract which performs important safety checks
              function mint(address to) external lock returns (uint liquidity) {
                  require(msg.sender == IEtherVistaFactory(factory).router(), 'EtherVistaPair: FORBIDDEN');
                  (uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
                  uint balance0 = IERC20(token0).balanceOf(address(this));
                  uint balance1 = IERC20(token1).balanceOf(address(this));
                  uint amount0 = balance0.sub(_reserve0);
                  uint amount1 = balance1.sub(_reserve1);
                  bool feeOn = _mintFee(_reserve0, _reserve1);
                  uint _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee
                  if (_totalSupply == 0) {
                      revert('Use first_mint instead');
                  } else {
                      liquidity = Math.min(amount0.mul(_totalSupply) / _reserve0, amount1.mul(_totalSupply) / _reserve1);
                  }
                  require(liquidity > 0, 'EtherVistaPair: INSUFFICIENT_LIQUIDITY_MINTED');
                  _mint(to, liquidity);
                  _update(balance0, balance1, _reserve0, _reserve1);
                  if (feeOn) kLast = uint(reserve0).mul(reserve1); // reserve0 and reserve1 are up-to-date
                  emit Mint(msg.sender, amount0, amount1);
              }
              // this low-level function should be called from a contract which performs important safety checks
              function burn(address to) external lock returns (uint amount0, uint amount1) {
                  require(msg.sender == IEtherVistaFactory(factory).router(), 'EtherVistaPair: FORBIDDEN');   
                  require(block.timestamp - creation_time >= 5 days, 'EtherVistaPair: FORBIDDEN RUGPULL');
                  (uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
                  address _token0 = token0;                                // gas savings
                  address _token1 = token1;                                // gas savings
                  uint balance0 = IERC20(_token0).balanceOf(address(this));
                  uint balance1 = IERC20(_token1).balanceOf(address(this));
                  uint liquidity = balanceOf[address(this)];
                  bool feeOn = _mintFee(_reserve0, _reserve1);
                  uint _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee
                  amount0 = liquidity.mul(balance0) / _totalSupply; // using balances ensures pro-rata distribution
                  amount1 = liquidity.mul(balance1) / _totalSupply; // using balances ensures pro-rata distribution
                  require(amount0 > 0 && amount1 > 0, 'EtherVistaPair: INSUFFICIENT_LIQUIDITY_BURNED');
                  _burn(address(this), liquidity);
                  _safeTransfer(_token0, to, amount0);
                  _safeTransfer(_token1, to, amount1);
                  balance0 = IERC20(_token0).balanceOf(address(this));
                  balance1 = IERC20(_token1).balanceOf(address(this));
                  _update(balance0, balance1, _reserve0, _reserve1);
                  if (feeOn) kLast = uint(reserve0).mul(reserve1); // reserve0 and reserve1 are up-to-date
                  emit Burn(msg.sender, amount0, amount1, to);
              }
              // this low-level function should be called from a contract which performs important safety checks
              function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external lock {
                  require(msg.sender == IEtherVistaFactory(factory).router(), 'EtherVistaPair: FORBIDDEN');
                  require(amount0Out > 0 || amount1Out > 0, 'EtherVistaPair: INSUFFICIENT_OUTPUT_AMOUNT');
                  (uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
                  require(amount0Out < _reserve0 && amount1Out < _reserve1, 'EtherVista: INSUFFICIENT_LIQUIDITY');
                  uint balance0;
                  uint balance1;
                  { // scope for _token{0,1}, avoids stack too deep errors
                  address _token0 = token0;
                  address _token1 = token1;
                  require(to != _token0 && to != _token1, 'EtherVistaPair: INVALID_TO');
                  if (amount0Out > 0) _safeTransfer(_token0, to, amount0Out); // optimistically transfer tokens
                  if (amount1Out > 0) _safeTransfer(_token1, to, amount1Out); // optimistically transfer tokens
                  if (data.length > 0) IUniswapV2Callee(to).uniswapV2Call(msg.sender, amount0Out, amount1Out, data);
                  balance0 = IERC20(_token0).balanceOf(address(this));
                  balance1 = IERC20(_token1).balanceOf(address(this));
                  }
                  uint amount0In = balance0 > _reserve0 - amount0Out ? balance0 - (_reserve0 - amount0Out) : 0;
                  uint amount1In = balance1 > _reserve1 - amount1Out ? balance1 - (_reserve1 - amount1Out) : 0;
                  require(amount0In > 0 || amount1In > 0, 'EtherVista: INSUFFICIENT_INPUT_AMOUNT');
                  { 
                  require(balance0 * balance1 >= reserve0 * reserve1, "K");
                  }
                  _update(balance0, balance1, _reserve0, _reserve1);
                  emit Swap(msg.sender, amount0In, amount1In, amount0Out, amount1Out, to);
              }
              // force balances to match reserves
              function skim(address to) external lock {
                  address _token0 = token0; // gas savings
                  address _token1 = token1; // gas savings
                  _safeTransfer(_token0, to, IERC20(_token0).balanceOf(address(this)).sub(reserve0));
                  _safeTransfer(_token1, to, IERC20(_token1).balanceOf(address(this)).sub(reserve1));
              }
              // force reserves to match balances
              function sync() external lock {
                  _update(IERC20(token0).balanceOf(address(this)), IERC20(token1).balanceOf(address(this)), reserve0, reserve1);
              }
          }
          

          File 3 of 7: EACAggregatorProxy
          pragma solidity 0.6.6;
          
          
          /**
           * @title The Owned contract
           * @notice A contract with helpers for basic contract ownership.
           */
          contract Owned {
          
            address payable public owner;
            address private pendingOwner;
          
            event OwnershipTransferRequested(
              address indexed from,
              address indexed to
            );
            event OwnershipTransferred(
              address indexed from,
              address indexed to
            );
          
            constructor() public {
              owner = msg.sender;
            }
          
            /**
             * @dev Allows an owner to begin transferring ownership to a new address,
             * pending.
             */
            function transferOwnership(address _to)
              external
              onlyOwner()
            {
              pendingOwner = _to;
          
              emit OwnershipTransferRequested(owner, _to);
            }
          
            /**
             * @dev Allows an ownership transfer to be completed by the recipient.
             */
            function acceptOwnership()
              external
            {
              require(msg.sender == pendingOwner, "Must be proposed owner");
          
              address oldOwner = owner;
              owner = msg.sender;
              pendingOwner = address(0);
          
              emit OwnershipTransferred(oldOwner, msg.sender);
            }
          
            /**
             * @dev Reverts if called by anyone other than the contract owner.
             */
            modifier onlyOwner() {
              require(msg.sender == owner, "Only callable by owner");
              _;
            }
          
          }
          
          interface AggregatorInterface {
            function latestAnswer() external view returns (int256);
            function latestTimestamp() external view returns (uint256);
            function latestRound() external view returns (uint256);
            function getAnswer(uint256 roundId) external view returns (int256);
            function getTimestamp(uint256 roundId) external view returns (uint256);
          
            event AnswerUpdated(int256 indexed current, uint256 indexed roundId, uint256 updatedAt);
            event NewRound(uint256 indexed roundId, address indexed startedBy, uint256 startedAt);
          }
          
          interface AggregatorV3Interface {
          
            function decimals() external view returns (uint8);
            function description() external view returns (string memory);
            function version() external view returns (uint256);
          
            // getRoundData and latestRoundData should both raise "No data present"
            // if they do not have data to report, instead of returning unset values
            // which could be misinterpreted as actual reported values.
            function getRoundData(uint80 _roundId)
              external
              view
              returns (
                uint80 roundId,
                int256 answer,
                uint256 startedAt,
                uint256 updatedAt,
                uint80 answeredInRound
              );
            function latestRoundData()
              external
              view
              returns (
                uint80 roundId,
                int256 answer,
                uint256 startedAt,
                uint256 updatedAt,
                uint80 answeredInRound
              );
          
          }
          
          interface AggregatorV2V3Interface is AggregatorInterface, AggregatorV3Interface
          {
          }
          
          /**
           * @title A trusted proxy for updating where current answers are read from
           * @notice This contract provides a consistent address for the
           * CurrentAnwerInterface but delegates where it reads from to the owner, who is
           * trusted to update it.
           */
          contract AggregatorProxy is AggregatorV2V3Interface, Owned {
          
            struct Phase {
              uint16 id;
              AggregatorV2V3Interface aggregator;
            }
            Phase private currentPhase;
            AggregatorV2V3Interface public proposedAggregator;
            mapping(uint16 => AggregatorV2V3Interface) public phaseAggregators;
          
            uint256 constant private PHASE_OFFSET = 64;
            uint256 constant private PHASE_SIZE = 16;
            uint256 constant private MAX_ID = 2**(PHASE_OFFSET+PHASE_SIZE) - 1;
          
            constructor(address _aggregator) public Owned() {
              setAggregator(_aggregator);
            }
          
            /**
             * @notice Reads the current answer from aggregator delegated to.
             *
             * @dev #[deprecated] Use latestRoundData instead. This does not error if no
             * answer has been reached, it will simply return 0. Either wait to point to
             * an already answered Aggregator or use the recommended latestRoundData
             * instead which includes better verification information.
             */
            function latestAnswer()
              public
              view
              virtual
              override
              returns (int256 answer)
            {
              return currentPhase.aggregator.latestAnswer();
            }
          
            /**
             * @notice Reads the last updated height from aggregator delegated to.
             *
             * @dev #[deprecated] Use latestRoundData instead. This does not error if no
             * answer has been reached, it will simply return 0. Either wait to point to
             * an already answered Aggregator or use the recommended latestRoundData
             * instead which includes better verification information.
             */
            function latestTimestamp()
              public
              view
              virtual
              override
              returns (uint256 updatedAt)
            {
              return currentPhase.aggregator.latestTimestamp();
            }
          
            /**
             * @notice get past rounds answers
             * @param _roundId the answer number to retrieve the answer for
             *
             * @dev #[deprecated] Use getRoundData instead. This does not error if no
             * answer has been reached, it will simply return 0. Either wait to point to
             * an already answered Aggregator or use the recommended getRoundData
             * instead which includes better verification information.
             */
            function getAnswer(uint256 _roundId)
              public
              view
              virtual
              override
              returns (int256 answer)
            {
              if (_roundId > MAX_ID) return 0;
          
              (uint16 phaseId, uint64 aggregatorRoundId) = parseIds(_roundId);
              AggregatorV2V3Interface aggregator = phaseAggregators[phaseId];
              if (address(aggregator) == address(0)) return 0;
          
              return aggregator.getAnswer(aggregatorRoundId);
            }
          
            /**
             * @notice get block timestamp when an answer was last updated
             * @param _roundId the answer number to retrieve the updated timestamp for
             *
             * @dev #[deprecated] Use getRoundData instead. This does not error if no
             * answer has been reached, it will simply return 0. Either wait to point to
             * an already answered Aggregator or use the recommended getRoundData
             * instead which includes better verification information.
             */
            function getTimestamp(uint256 _roundId)
              public
              view
              virtual
              override
              returns (uint256 updatedAt)
            {
              if (_roundId > MAX_ID) return 0;
          
              (uint16 phaseId, uint64 aggregatorRoundId) = parseIds(_roundId);
              AggregatorV2V3Interface aggregator = phaseAggregators[phaseId];
              if (address(aggregator) == address(0)) return 0;
          
              return aggregator.getTimestamp(aggregatorRoundId);
            }
          
            /**
             * @notice get the latest completed round where the answer was updated. This
             * ID includes the proxy's phase, to make sure round IDs increase even when
             * switching to a newly deployed aggregator.
             *
             * @dev #[deprecated] Use latestRoundData instead. This does not error if no
             * answer has been reached, it will simply return 0. Either wait to point to
             * an already answered Aggregator or use the recommended latestRoundData
             * instead which includes better verification information.
             */
            function latestRound()
              public
              view
              virtual
              override
              returns (uint256 roundId)
            {
              Phase memory phase = currentPhase; // cache storage reads
              return addPhase(phase.id, uint64(phase.aggregator.latestRound()));
            }
          
            /**
             * @notice get data about a round. Consumers are encouraged to check
             * that they're receiving fresh data by inspecting the updatedAt and
             * answeredInRound return values.
             * Note that different underlying implementations of AggregatorV3Interface
             * have slightly different semantics for some of the return values. Consumers
             * should determine what implementations they expect to receive
             * data from and validate that they can properly handle return data from all
             * of them.
             * @param _roundId the requested round ID as presented through the proxy, this
             * is made up of the aggregator's round ID with the phase ID encoded in the
             * two highest order bytes
             * @return roundId is the round ID from the aggregator for which the data was
             * retrieved combined with an phase to ensure that round IDs get larger as
             * time moves forward.
             * @return answer is the answer for the given round
             * @return startedAt is the timestamp when the round was started.
             * (Only some AggregatorV3Interface implementations return meaningful values)
             * @return updatedAt is the timestamp when the round last was updated (i.e.
             * answer was last computed)
             * @return answeredInRound is the round ID of the round in which the answer
             * was computed.
             * (Only some AggregatorV3Interface implementations return meaningful values)
             * @dev Note that answer and updatedAt may change between queries.
             */
            function getRoundData(uint80 _roundId)
              public
              view
              virtual
              override
              returns (
                uint80 roundId,
                int256 answer,
                uint256 startedAt,
                uint256 updatedAt,
                uint80 answeredInRound
              )
            {
              (uint16 phaseId, uint64 aggregatorRoundId) = parseIds(_roundId);
          
              (
                uint80 roundId,
                int256 answer,
                uint256 startedAt,
                uint256 updatedAt,
                uint80 ansIn
              ) = phaseAggregators[phaseId].getRoundData(aggregatorRoundId);
          
              return addPhaseIds(roundId, answer, startedAt, updatedAt, ansIn, phaseId);
            }
          
            /**
             * @notice get data about the latest round. Consumers are encouraged to check
             * that they're receiving fresh data by inspecting the updatedAt and
             * answeredInRound return values.
             * Note that different underlying implementations of AggregatorV3Interface
             * have slightly different semantics for some of the return values. Consumers
             * should determine what implementations they expect to receive
             * data from and validate that they can properly handle return data from all
             * of them.
             * @return roundId is the round ID from the aggregator for which the data was
             * retrieved combined with an phase to ensure that round IDs get larger as
             * time moves forward.
             * @return answer is the answer for the given round
             * @return startedAt is the timestamp when the round was started.
             * (Only some AggregatorV3Interface implementations return meaningful values)
             * @return updatedAt is the timestamp when the round last was updated (i.e.
             * answer was last computed)
             * @return answeredInRound is the round ID of the round in which the answer
             * was computed.
             * (Only some AggregatorV3Interface implementations return meaningful values)
             * @dev Note that answer and updatedAt may change between queries.
             */
            function latestRoundData()
              public
              view
              virtual
              override
              returns (
                uint80 roundId,
                int256 answer,
                uint256 startedAt,
                uint256 updatedAt,
                uint80 answeredInRound
              )
            {
              Phase memory current = currentPhase; // cache storage reads
          
              (
                uint80 roundId,
                int256 answer,
                uint256 startedAt,
                uint256 updatedAt,
                uint80 ansIn
              ) = current.aggregator.latestRoundData();
          
              return addPhaseIds(roundId, answer, startedAt, updatedAt, ansIn, current.id);
            }
          
            /**
             * @notice Used if an aggregator contract has been proposed.
             * @param _roundId the round ID to retrieve the round data for
             * @return roundId is the round ID for which data was retrieved
             * @return answer is the answer for the given round
             * @return startedAt is the timestamp when the round was started.
             * (Only some AggregatorV3Interface implementations return meaningful values)
             * @return updatedAt is the timestamp when the round last was updated (i.e.
             * answer was last computed)
             * @return answeredInRound is the round ID of the round in which the answer
             * was computed.
            */
            function proposedGetRoundData(uint80 _roundId)
              public
              view
              virtual
              hasProposal()
              returns (
                uint80 roundId,
                int256 answer,
                uint256 startedAt,
                uint256 updatedAt,
                uint80 answeredInRound
              )
            {
              return proposedAggregator.getRoundData(_roundId);
            }
          
            /**
             * @notice Used if an aggregator contract has been proposed.
             * @return roundId is the round ID for which data was retrieved
             * @return answer is the answer for the given round
             * @return startedAt is the timestamp when the round was started.
             * (Only some AggregatorV3Interface implementations return meaningful values)
             * @return updatedAt is the timestamp when the round last was updated (i.e.
             * answer was last computed)
             * @return answeredInRound is the round ID of the round in which the answer
             * was computed.
            */
            function proposedLatestRoundData()
              public
              view
              virtual
              hasProposal()
              returns (
                uint80 roundId,
                int256 answer,
                uint256 startedAt,
                uint256 updatedAt,
                uint80 answeredInRound
              )
            {
              return proposedAggregator.latestRoundData();
            }
          
            /**
             * @notice returns the current phase's aggregator address.
             */
            function aggregator()
              external
              view
              returns (address)
            {
              return address(currentPhase.aggregator);
            }
          
            /**
             * @notice returns the current phase's ID.
             */
            function phaseId()
              external
              view
              returns (uint16)
            {
              return currentPhase.id;
            }
          
            /**
             * @notice represents the number of decimals the aggregator responses represent.
             */
            function decimals()
              external
              view
              override
              returns (uint8)
            {
              return currentPhase.aggregator.decimals();
            }
          
            /**
             * @notice the version number representing the type of aggregator the proxy
             * points to.
             */
            function version()
              external
              view
              override
              returns (uint256)
            {
              return currentPhase.aggregator.version();
            }
          
            /**
             * @notice returns the description of the aggregator the proxy points to.
             */
            function description()
              external
              view
              override
              returns (string memory)
            {
              return currentPhase.aggregator.description();
            }
          
            /**
             * @notice Allows the owner to propose a new address for the aggregator
             * @param _aggregator The new address for the aggregator contract
             */
            function proposeAggregator(address _aggregator)
              external
              onlyOwner()
            {
              proposedAggregator = AggregatorV2V3Interface(_aggregator);
            }
          
            /**
             * @notice Allows the owner to confirm and change the address
             * to the proposed aggregator
             * @dev Reverts if the given address doesn't match what was previously
             * proposed
             * @param _aggregator The new address for the aggregator contract
             */
            function confirmAggregator(address _aggregator)
              external
              onlyOwner()
            {
              require(_aggregator == address(proposedAggregator), "Invalid proposed aggregator");
              delete proposedAggregator;
              setAggregator(_aggregator);
            }
          
          
            /*
             * Internal
             */
          
            function setAggregator(address _aggregator)
              internal
            {
              uint16 id = currentPhase.id + 1;
              currentPhase = Phase(id, AggregatorV2V3Interface(_aggregator));
              phaseAggregators[id] = AggregatorV2V3Interface(_aggregator);
            }
          
            function addPhase(
              uint16 _phase,
              uint64 _originalId
            )
              internal
              view
              returns (uint80)
            {
              return uint80(uint256(_phase) << PHASE_OFFSET | _originalId);
            }
          
            function parseIds(
              uint256 _roundId
            )
              internal
              view
              returns (uint16, uint64)
            {
              uint16 phaseId = uint16(_roundId >> PHASE_OFFSET);
              uint64 aggregatorRoundId = uint64(_roundId);
          
              return (phaseId, aggregatorRoundId);
            }
          
            function addPhaseIds(
                uint80 roundId,
                int256 answer,
                uint256 startedAt,
                uint256 updatedAt,
                uint80 answeredInRound,
                uint16 phaseId
            )
              internal
              view
              returns (uint80, int256, uint256, uint256, uint80)
            {
              return (
                addPhase(phaseId, uint64(roundId)),
                answer,
                startedAt,
                updatedAt,
                addPhase(phaseId, uint64(answeredInRound))
              );
            }
          
            /*
             * Modifiers
             */
          
            modifier hasProposal() {
              require(address(proposedAggregator) != address(0), "No proposed aggregator present");
              _;
            }
          
          }
          
          interface AccessControllerInterface {
            function hasAccess(address user, bytes calldata data) external view returns (bool);
          }
          
          /**
           * @title External Access Controlled Aggregator Proxy
           * @notice A trusted proxy for updating where current answers are read from
           * @notice This contract provides a consistent address for the
           * Aggregator and AggregatorV3Interface but delegates where it reads from to the owner, who is
           * trusted to update it.
           * @notice Only access enabled addresses are allowed to access getters for
           * aggregated answers and round information.
           */
          contract EACAggregatorProxy is AggregatorProxy {
          
            AccessControllerInterface public accessController;
          
            constructor(
              address _aggregator,
              address _accessController
            )
              public
              AggregatorProxy(_aggregator)
            {
              setController(_accessController);
            }
          
            /**
             * @notice Allows the owner to update the accessController contract address.
             * @param _accessController The new address for the accessController contract
             */
            function setController(address _accessController)
              public
              onlyOwner()
            {
              accessController = AccessControllerInterface(_accessController);
            }
          
            /**
             * @notice Reads the current answer from aggregator delegated to.
             * @dev overridden function to add the checkAccess() modifier
             *
             * @dev #[deprecated] Use latestRoundData instead. This does not error if no
             * answer has been reached, it will simply return 0. Either wait to point to
             * an already answered Aggregator or use the recommended latestRoundData
             * instead which includes better verification information.
             */
            function latestAnswer()
              public
              view
              override
              checkAccess()
              returns (int256)
            {
              return super.latestAnswer();
            }
          
            /**
             * @notice get the latest completed round where the answer was updated. This
             * ID includes the proxy's phase, to make sure round IDs increase even when
             * switching to a newly deployed aggregator.
             *
             * @dev #[deprecated] Use latestRoundData instead. This does not error if no
             * answer has been reached, it will simply return 0. Either wait to point to
             * an already answered Aggregator or use the recommended latestRoundData
             * instead which includes better verification information.
             */
            function latestTimestamp()
              public
              view
              override
              checkAccess()
              returns (uint256)
            {
              return super.latestTimestamp();
            }
          
            /**
             * @notice get past rounds answers
             * @param _roundId the answer number to retrieve the answer for
             * @dev overridden function to add the checkAccess() modifier
             *
             * @dev #[deprecated] Use getRoundData instead. This does not error if no
             * answer has been reached, it will simply return 0. Either wait to point to
             * an already answered Aggregator or use the recommended getRoundData
             * instead which includes better verification information.
             */
            function getAnswer(uint256 _roundId)
              public
              view
              override
              checkAccess()
              returns (int256)
            {
              return super.getAnswer(_roundId);
            }
          
            /**
             * @notice get block timestamp when an answer was last updated
             * @param _roundId the answer number to retrieve the updated timestamp for
             * @dev overridden function to add the checkAccess() modifier
             *
             * @dev #[deprecated] Use getRoundData instead. This does not error if no
             * answer has been reached, it will simply return 0. Either wait to point to
             * an already answered Aggregator or use the recommended getRoundData
             * instead which includes better verification information.
             */
            function getTimestamp(uint256 _roundId)
              public
              view
              override
              checkAccess()
              returns (uint256)
            {
              return super.getTimestamp(_roundId);
            }
          
            /**
             * @notice get the latest completed round where the answer was updated
             * @dev overridden function to add the checkAccess() modifier
             *
             * @dev #[deprecated] Use latestRoundData instead. This does not error if no
             * answer has been reached, it will simply return 0. Either wait to point to
             * an already answered Aggregator or use the recommended latestRoundData
             * instead which includes better verification information.
             */
            function latestRound()
              public
              view
              override
              checkAccess()
              returns (uint256)
            {
              return super.latestRound();
            }
          
            /**
             * @notice get data about a round. Consumers are encouraged to check
             * that they're receiving fresh data by inspecting the updatedAt and
             * answeredInRound return values.
             * Note that different underlying implementations of AggregatorV3Interface
             * have slightly different semantics for some of the return values. Consumers
             * should determine what implementations they expect to receive
             * data from and validate that they can properly handle return data from all
             * of them.
             * @param _roundId the round ID to retrieve the round data for
             * @return roundId is the round ID from the aggregator for which the data was
             * retrieved combined with a phase to ensure that round IDs get larger as
             * time moves forward.
             * @return answer is the answer for the given round
             * @return startedAt is the timestamp when the round was started.
             * (Only some AggregatorV3Interface implementations return meaningful values)
             * @return updatedAt is the timestamp when the round last was updated (i.e.
             * answer was last computed)
             * @return answeredInRound is the round ID of the round in which the answer
             * was computed.
             * (Only some AggregatorV3Interface implementations return meaningful values)
             * @dev Note that answer and updatedAt may change between queries.
             */
            function getRoundData(uint80 _roundId)
              public
              view
              checkAccess()
              override
              returns (
                uint80 roundId,
                int256 answer,
                uint256 startedAt,
                uint256 updatedAt,
                uint80 answeredInRound
              )
            {
              return super.getRoundData(_roundId);
            }
          
            /**
             * @notice get data about the latest round. Consumers are encouraged to check
             * that they're receiving fresh data by inspecting the updatedAt and
             * answeredInRound return values.
             * Note that different underlying implementations of AggregatorV3Interface
             * have slightly different semantics for some of the return values. Consumers
             * should determine what implementations they expect to receive
             * data from and validate that they can properly handle return data from all
             * of them.
             * @return roundId is the round ID from the aggregator for which the data was
             * retrieved combined with a phase to ensure that round IDs get larger as
             * time moves forward.
             * @return answer is the answer for the given round
             * @return startedAt is the timestamp when the round was started.
             * (Only some AggregatorV3Interface implementations return meaningful values)
             * @return updatedAt is the timestamp when the round last was updated (i.e.
             * answer was last computed)
             * @return answeredInRound is the round ID of the round in which the answer
             * was computed.
             * (Only some AggregatorV3Interface implementations return meaningful values)
             * @dev Note that answer and updatedAt may change between queries.
             */
            function latestRoundData()
              public
              view
              checkAccess()
              override
              returns (
                uint80 roundId,
                int256 answer,
                uint256 startedAt,
                uint256 updatedAt,
                uint80 answeredInRound
              )
            {
              return super.latestRoundData();
            }
          
            /**
             * @notice Used if an aggregator contract has been proposed.
             * @param _roundId the round ID to retrieve the round data for
             * @return roundId is the round ID for which data was retrieved
             * @return answer is the answer for the given round
             * @return startedAt is the timestamp when the round was started.
             * (Only some AggregatorV3Interface implementations return meaningful values)
             * @return updatedAt is the timestamp when the round last was updated (i.e.
             * answer was last computed)
             * @return answeredInRound is the round ID of the round in which the answer
             * was computed.
            */
            function proposedGetRoundData(uint80 _roundId)
              public
              view
              checkAccess()
              hasProposal()
              override
              returns (
                uint80 roundId,
                int256 answer,
                uint256 startedAt,
                uint256 updatedAt,
                uint80 answeredInRound
              )
            {
              return super.proposedGetRoundData(_roundId);
            }
          
            /**
             * @notice Used if an aggregator contract has been proposed.
             * @return roundId is the round ID for which data was retrieved
             * @return answer is the answer for the given round
             * @return startedAt is the timestamp when the round was started.
             * (Only some AggregatorV3Interface implementations return meaningful values)
             * @return updatedAt is the timestamp when the round last was updated (i.e.
             * answer was last computed)
             * @return answeredInRound is the round ID of the round in which the answer
             * was computed.
            */
            function proposedLatestRoundData()
              public
              view
              checkAccess()
              hasProposal()
              override
              returns (
                uint80 roundId,
                int256 answer,
                uint256 startedAt,
                uint256 updatedAt,
                uint80 answeredInRound
              )
            {
              return super.proposedLatestRoundData();
            }
          
            /**
             * @dev reverts if the caller does not have access by the accessController
             * contract or is the contract itself.
             */
            modifier checkAccess() {
              AccessControllerInterface ac = accessController;
              require(address(ac) == address(0) || ac.hasAccess(msg.sender, msg.data), "No access");
              _;
            }
          }

          File 4 of 7: AccessControlledOffchainAggregator
          // SPDX-License-Identifier: MIT
          pragma solidity 0.7.6;
          import "./OffchainAggregator.sol";
          import "./SimpleReadAccessController.sol";
          /**
           * @notice Wrapper of OffchainAggregator which checks read access on Aggregator-interface methods
           */
          contract AccessControlledOffchainAggregator is OffchainAggregator, SimpleReadAccessController {
            constructor(
              uint32 _maximumGasPrice,
              uint32 _reasonableGasPrice,
              uint32 _microLinkPerEth,
              uint32 _linkGweiPerObservation,
              uint32 _linkGweiPerTransmission,
              LinkTokenInterface _link,
              int192 _minAnswer,
              int192 _maxAnswer,
              AccessControllerInterface _billingAccessController,
              AccessControllerInterface _requesterAccessController,
              uint8 _decimals,
              string memory description
            )
              OffchainAggregator(
                _maximumGasPrice,
                _reasonableGasPrice,
                _microLinkPerEth,
                _linkGweiPerObservation,
                _linkGweiPerTransmission,
                _link,
                _minAnswer,
                _maxAnswer,
                _billingAccessController,
                _requesterAccessController,
                _decimals,
                description
              ) {
              }
            /*
             * Versioning
             */
            function typeAndVersion()
              external
              override
              pure
              virtual
              returns (string memory)
            {
              return "AccessControlledOffchainAggregator 4.0.0";
            }
            /*
             * v2 Aggregator interface
             */
            /// @inheritdoc OffchainAggregator
            function latestAnswer()
              public
              override
              view
              checkAccess()
              returns (int256)
            {
              return super.latestAnswer();
            }
            /// @inheritdoc OffchainAggregator
            function latestTimestamp()
              public
              override
              view
              checkAccess()
              returns (uint256)
            {
              return super.latestTimestamp();
            }
            /// @inheritdoc OffchainAggregator
            function latestRound()
              public
              override
              view
              checkAccess()
              returns (uint256)
            {
              return super.latestRound();
            }
            /// @inheritdoc OffchainAggregator
            function getAnswer(uint256 _roundId)
              public
              override
              view
              checkAccess()
              returns (int256)
            {
              return super.getAnswer(_roundId);
            }
            /// @inheritdoc OffchainAggregator
            function getTimestamp(uint256 _roundId)
              public
              override
              view
              checkAccess()
              returns (uint256)
            {
              return super.getTimestamp(_roundId);
            }
            /*
             * v3 Aggregator interface
             */
            /// @inheritdoc OffchainAggregator
            function description()
              public
              override
              view
              checkAccess()
              returns (string memory)
            {
              return super.description();
            }
            /// @inheritdoc OffchainAggregator
            function getRoundData(uint80 _roundId)
              public
              override
              view
              checkAccess()
              returns (
                uint80 roundId,
                int256 answer,
                uint256 startedAt,
                uint256 updatedAt,
                uint80 answeredInRound
              )
            {
              return super.getRoundData(_roundId);
            }
            /// @inheritdoc OffchainAggregator
            function latestRoundData()
              public
              override
              view
              checkAccess()
              returns (
                uint80 roundId,
                int256 answer,
                uint256 startedAt,
                uint256 updatedAt,
                uint80 answeredInRound
              )
            {
              return super.latestRoundData();
            }
          }
          // SPDX-License-Identifier: MIT
          pragma solidity ^0.7.0;
          interface AccessControllerInterface {
            function hasAccess(address user, bytes calldata data) external view returns (bool);
          }
          // SPDX-License-Identifier: MIT
          pragma solidity ^0.7.0;
          interface AggregatorInterface {
            function latestAnswer() external view returns (int256);
            function latestTimestamp() external view returns (uint256);
            function latestRound() external view returns (uint256);
            function getAnswer(uint256 roundId) external view returns (int256);
            function getTimestamp(uint256 roundId) external view returns (uint256);
            event AnswerUpdated(int256 indexed current, uint256 indexed roundId, uint256 updatedAt);
            event NewRound(uint256 indexed roundId, address indexed startedBy, uint256 startedAt);
          }
          // SPDX-License-Identifier: MIT
          pragma solidity ^0.7.0;
          import "./AggregatorInterface.sol";
          import "./AggregatorV3Interface.sol";
          interface AggregatorV2V3Interface is AggregatorInterface, AggregatorV3Interface
          {
          }// SPDX-License-Identifier: MIT
          pragma solidity ^0.7.0;
          interface AggregatorV3Interface {
            function decimals() external view returns (uint8);
            function description() external view returns (string memory);
            function version() external view returns (uint256);
            function getRoundData(uint80 _roundId)
              external
              view
              returns (
                uint80 roundId,
                int256 answer,
                uint256 startedAt,
                uint256 updatedAt,
                uint80 answeredInRound
              );
            function latestRoundData()
              external
              view
              returns (
                uint80 roundId,
                int256 answer,
                uint256 startedAt,
                uint256 updatedAt,
                uint80 answeredInRound
              );
          }
          // SPDX-License-Identifier: MIT
          pragma solidity ^0.7.0;
          interface AggregatorValidatorInterface {
            function validate(
              uint256 previousRoundId,
              int256 previousAnswer,
              uint256 currentRoundId,
              int256 currentAnswer
            ) external returns (bool);
          }// SPDX-License-Identifier: MIT
          pragma solidity ^0.7.0;
          interface LinkTokenInterface {
            function allowance(address owner, address spender) external view returns (uint256 remaining);
            function approve(address spender, uint256 value) external returns (bool success);
            function balanceOf(address owner) external view returns (uint256 balance);
            function decimals() external view returns (uint8 decimalPlaces);
            function decreaseApproval(address spender, uint256 addedValue) external returns (bool success);
            function increaseApproval(address spender, uint256 subtractedValue) external;
            function name() external view returns (string memory tokenName);
            function symbol() external view returns (string memory tokenSymbol);
            function totalSupply() external view returns (uint256 totalTokensIssued);
            function transfer(address to, uint256 value) external returns (bool success);
            function transferAndCall(address to, uint256 value, bytes calldata data) external returns (bool success);
            function transferFrom(address from, address to, uint256 value) external returns (bool success);
          }
          // SPDX-License-Identifier: MIT
          pragma solidity 0.7.6;
          import "./AccessControllerInterface.sol";
          import "./AggregatorV2V3Interface.sol";
          import "./AggregatorValidatorInterface.sol";
          import "./LinkTokenInterface.sol";
          import "./Owned.sol";
          import "./OffchainAggregatorBilling.sol";
          import "./TypeAndVersionInterface.sol";
          /**
            * @notice Onchain verification of reports from the offchain reporting protocol
            * @dev For details on its operation, see the offchain reporting protocol design
            * @dev doc, which refers to this contract as simply the "contract".
          */
          contract OffchainAggregator is Owned, OffchainAggregatorBilling, AggregatorV2V3Interface, TypeAndVersionInterface {
            uint256 constant private maxUint32 = (1 << 32) - 1;
            // Storing these fields used on the hot path in a HotVars variable reduces the
            // retrieval of all of them to a single SLOAD. If any further fields are
            // added, make sure that storage of the struct still takes at most 32 bytes.
            struct HotVars {
              // Provides 128 bits of security against 2nd pre-image attacks, but only
              // 64 bits against collisions. This is acceptable, since a malicious owner has
              // easier way of messing up the protocol than to find hash collisions.
              bytes16 latestConfigDigest;
              uint40 latestEpochAndRound; // 32 most sig bits for epoch, 8 least sig bits for round
              // Current bound assumed on number of faulty/dishonest oracles participating
              // in the protocol, this value is referred to as f in the design
              uint8 threshold;
              // Chainlink Aggregators expose a roundId to consumers. The offchain reporting
              // protocol does not use this id anywhere. We increment it whenever a new
              // transmission is made to provide callers with contiguous ids for successive
              // reports.
              uint32 latestAggregatorRoundId;
            }
            HotVars internal s_hotVars;
            // Transmission records the median answer from the transmit transaction at
            // time timestamp
            struct Transmission {
              int192 answer; // 192 bits ought to be enough for anyone
              uint64 timestamp;
            }
            mapping(uint32 /* aggregator round ID */ => Transmission) internal s_transmissions;
            // incremented each time a new config is posted. This count is incorporated
            // into the config digest, to prevent replay attacks.
            uint32 internal s_configCount;
            uint32 internal s_latestConfigBlockNumber; // makes it easier for offchain systems
                                                       // to extract config from logs.
            // Lowest answer the system is allowed to report in response to transmissions
            int192 immutable public minAnswer;
            // Highest answer the system is allowed to report in response to transmissions
            int192 immutable public maxAnswer;
            /*
             * @param _maximumGasPrice highest gas price for which transmitter will be compensated
             * @param _reasonableGasPrice transmitter will receive reward for gas prices under this value
             * @param _microLinkPerEth reimbursement per ETH of gas cost, in 1e-6LINK units
             * @param _linkGweiPerObservation reward to oracle for contributing an observation to a successfully transmitted report, in 1e-9LINK units
             * @param _linkGweiPerTransmission reward to transmitter of a successful report, in 1e-9LINK units
             * @param _link address of the LINK contract
             * @param _minAnswer lowest answer the median of a report is allowed to be
             * @param _maxAnswer highest answer the median of a report is allowed to be
             * @param _billingAccessController access controller for billing admin functions
             * @param _requesterAccessController access controller for requesting new rounds
             * @param _decimals answers are stored in fixed-point format, with this many digits of precision
             * @param _description short human-readable description of observable this contract's answers pertain to
             */
            constructor(
              uint32 _maximumGasPrice,
              uint32 _reasonableGasPrice,
              uint32 _microLinkPerEth,
              uint32 _linkGweiPerObservation,
              uint32 _linkGweiPerTransmission,
              LinkTokenInterface _link,
              int192 _minAnswer,
              int192 _maxAnswer,
              AccessControllerInterface _billingAccessController,
              AccessControllerInterface _requesterAccessController,
              uint8 _decimals,
              string memory _description
            )
              OffchainAggregatorBilling(_maximumGasPrice, _reasonableGasPrice, _microLinkPerEth,
                _linkGweiPerObservation, _linkGweiPerTransmission, _link,
                _billingAccessController
              )
            {
              decimals = _decimals;
              s_description = _description;
              setRequesterAccessController(_requesterAccessController);
              setValidatorConfig(AggregatorValidatorInterface(0x0), 0);
              minAnswer = _minAnswer;
              maxAnswer = _maxAnswer;
            }
            /*
             * Versioning
             */
            function typeAndVersion()
              external
              override
              pure
              virtual
              returns (string memory)
            {
              return "OffchainAggregator 4.0.0";
            }
            /*
             * Config logic
             */
            /**
             * @notice triggers a new run of the offchain reporting protocol
             * @param previousConfigBlockNumber block in which the previous config was set, to simplify historic analysis
             * @param configCount ordinal number of this config setting among all config settings over the life of this contract
             * @param signers ith element is address ith oracle uses to sign a report
             * @param transmitters ith element is address ith oracle uses to transmit a report via the transmit method
             * @param threshold maximum number of faulty/dishonest oracles the protocol can tolerate while still working correctly
             * @param encodedConfigVersion version of the serialization format used for "encoded" parameter
             * @param encoded serialized data used by oracles to configure their offchain operation
             */
            event ConfigSet(
              uint32 previousConfigBlockNumber,
              uint64 configCount,
              address[] signers,
              address[] transmitters,
              uint8 threshold,
              uint64 encodedConfigVersion,
              bytes encoded
            );
            // Reverts transaction if config args are invalid
            modifier checkConfigValid (
              uint256 _numSigners, uint256 _numTransmitters, uint256 _threshold
            ) {
              require(_numSigners <= maxNumOracles, "too many signers");
              require(_threshold > 0, "threshold must be positive");
              require(
                _numSigners == _numTransmitters,
                "oracle addresses out of registration"
              );
              require(_numSigners > 3*_threshold, "faulty-oracle threshold too high");
              _;
            }
            /**
             * @notice sets offchain reporting protocol configuration incl. participating oracles
             * @param _signers addresses with which oracles sign the reports
             * @param _transmitters addresses oracles use to transmit the reports
             * @param _threshold number of faulty oracles the system can tolerate
             * @param _encodedConfigVersion version number for offchainEncoding schema
             * @param _encoded encoded off-chain oracle configuration
             */
            function setConfig(
              address[] calldata _signers,
              address[] calldata _transmitters,
              uint8 _threshold,
              uint64 _encodedConfigVersion,
              bytes calldata _encoded
            )
              external
              checkConfigValid(_signers.length, _transmitters.length, _threshold)
              onlyOwner()
            {
              while (s_signers.length != 0) { // remove any old signer/transmitter addresses
                uint lastIdx = s_signers.length - 1;
                address signer = s_signers[lastIdx];
                address transmitter = s_transmitters[lastIdx];
                payOracle(transmitter);
                delete s_oracles[signer];
                delete s_oracles[transmitter];
                s_signers.pop();
                s_transmitters.pop();
              }
              for (uint i = 0; i < _signers.length; i++) { // add new signer/transmitter addresses
                require(
                  s_oracles[_signers[i]].role == Role.Unset,
                  "repeated signer address"
                );
                s_oracles[_signers[i]] = Oracle(uint8(i), Role.Signer);
                require(s_payees[_transmitters[i]] != address(0), "payee must be set");
                require(
                  s_oracles[_transmitters[i]].role == Role.Unset,
                  "repeated transmitter address"
                );
                s_oracles[_transmitters[i]] = Oracle(uint8(i), Role.Transmitter);
                s_signers.push(_signers[i]);
                s_transmitters.push(_transmitters[i]);
              }
              s_hotVars.threshold = _threshold;
              uint32 previousConfigBlockNumber = s_latestConfigBlockNumber;
              s_latestConfigBlockNumber = uint32(block.number);
              s_configCount += 1;
              uint64 configCount = s_configCount;
              {
                s_hotVars.latestConfigDigest = configDigestFromConfigData(
                  address(this),
                  configCount,
                  _signers,
                  _transmitters,
                  _threshold,
                  _encodedConfigVersion,
                  _encoded
                );
                s_hotVars.latestEpochAndRound = 0;
              }
              emit ConfigSet(
                previousConfigBlockNumber,
                configCount,
                _signers,
                _transmitters,
                _threshold,
                _encodedConfigVersion,
                _encoded
              );
            }
            function configDigestFromConfigData(
              address _contractAddress,
              uint64 _configCount,
              address[] calldata _signers,
              address[] calldata _transmitters,
              uint8 _threshold,
              uint64 _encodedConfigVersion,
              bytes calldata _encodedConfig
            ) internal pure returns (bytes16) {
              return bytes16(keccak256(abi.encode(_contractAddress, _configCount,
                _signers, _transmitters, _threshold, _encodedConfigVersion, _encodedConfig
              )));
            }
            /**
             * @notice information about current offchain reporting protocol configuration
             * @return configCount ordinal number of current config, out of all configs applied to this contract so far
             * @return blockNumber block at which this config was set
             * @return configDigest domain-separation tag for current config (see configDigestFromConfigData)
             */
            function latestConfigDetails()
              external
              view
              returns (
                uint32 configCount,
                uint32 blockNumber,
                bytes16 configDigest
              )
            {
              return (s_configCount, s_latestConfigBlockNumber, s_hotVars.latestConfigDigest);
            }
            /**
             * @return list of addresses permitted to transmit reports to this contract
             * @dev The list will match the order used to specify the transmitter during setConfig
             */
            function transmitters()
              external
              view
              returns(address[] memory)
            {
                return s_transmitters;
            }
            /*
             * On-chain validation logc
             */
            // Configuration for validator
            struct ValidatorConfig {
              AggregatorValidatorInterface validator;
              uint32 gasLimit;
            }
            ValidatorConfig private s_validatorConfig;
            /**
             * @notice indicates that the validator configuration has been set
             * @param previousValidator previous validator contract
             * @param previousGasLimit previous gas limit for validate calls
             * @param currentValidator current validator contract
             * @param currentGasLimit current gas limit for validate calls
             */
            event ValidatorConfigSet(
              AggregatorValidatorInterface indexed previousValidator,
              uint32 previousGasLimit,
              AggregatorValidatorInterface indexed currentValidator,
              uint32 currentGasLimit
            );
            /**
             * @notice validator configuration
             * @return validator validator contract
             * @return gasLimit gas limit for validate calls
             */
            function validatorConfig()
              external
              view
              returns (AggregatorValidatorInterface validator, uint32 gasLimit)
            {
              ValidatorConfig memory vc = s_validatorConfig;
              return (vc.validator, vc.gasLimit);
            }
            /**
             * @notice sets validator configuration
             * @dev set _newValidator to 0x0 to disable validate calls
             * @param _newValidator address of the new validator contract
             * @param _newGasLimit new gas limit for validate calls
             */
            function setValidatorConfig(AggregatorValidatorInterface _newValidator, uint32 _newGasLimit)
              public
              onlyOwner()
            {
              ValidatorConfig memory previous = s_validatorConfig;
              if (previous.validator != _newValidator || previous.gasLimit != _newGasLimit) {
                s_validatorConfig = ValidatorConfig({
                  validator: _newValidator,
                  gasLimit: _newGasLimit
                });
                emit ValidatorConfigSet(previous.validator, previous.gasLimit, _newValidator, _newGasLimit);
              }
            }
            function validateAnswer(
              uint32 _aggregatorRoundId,
              int256 _answer
            )
              private
            {
              ValidatorConfig memory vc = s_validatorConfig;
              if (address(vc.validator) == address(0)) {
                return;
              }
              uint32 prevAggregatorRoundId = _aggregatorRoundId - 1;
              int256 prevAggregatorRoundAnswer = s_transmissions[prevAggregatorRoundId].answer;
              require(
                callWithExactGasEvenIfTargetIsNoContract(
                  vc.gasLimit,
                  address(vc.validator),
                  abi.encodeWithSignature(
                    "validate(uint256,int256,uint256,int256)",
                    uint256(prevAggregatorRoundId),
                    prevAggregatorRoundAnswer,
                    uint256(_aggregatorRoundId),
                    _answer
                  )
                ),
                "insufficient gas"
              );
            }
            uint256 private constant CALL_WITH_EXACT_GAS_CUSHION = 5_000;
            /**
             * @dev calls target address with exactly gasAmount gas and data as calldata
             * or reverts if at least gasAmount gas is not available.
             */
            function callWithExactGasEvenIfTargetIsNoContract(
              uint256 _gasAmount,
              address _target,
              bytes memory _data
            )
              private
              returns (bool sufficientGas)
            {
              // solhint-disable-next-line no-inline-assembly
              assembly {
                let g := gas()
                // Compute g -= CALL_WITH_EXACT_GAS_CUSHION and check for underflow. We
                // need the cushion since the logic following the above call to gas also
                // costs gas which we cannot account for exactly. So cushion is a
                // conservative upper bound for the cost of this logic.
                if iszero(lt(g, CALL_WITH_EXACT_GAS_CUSHION)) {
                  g := sub(g, CALL_WITH_EXACT_GAS_CUSHION)
                  // If g - g//64 <= _gasAmount, we don't have enough gas. (We subtract g//64
                  // because of EIP-150.)
                  if gt(sub(g, div(g, 64)), _gasAmount) {
                    // Call and ignore success/return data. Note that we did not check
                    // whether a contract actually exists at the _target address.
                    pop(call(_gasAmount, _target, 0, add(_data, 0x20), mload(_data), 0, 0))
                    sufficientGas := true
                  }
                }
              }
            }
            /*
             * requestNewRound logic
             */
            AccessControllerInterface internal s_requesterAccessController;
            /**
             * @notice emitted when a new requester access controller contract is set
             * @param old the address prior to the current setting
             * @param current the address of the new access controller contract
             */
            event RequesterAccessControllerSet(AccessControllerInterface old, AccessControllerInterface current);
            /**
             * @notice emitted to immediately request a new round
             * @param requester the address of the requester
             * @param configDigest the latest transmission's configDigest
             * @param epoch the latest transmission's epoch
             * @param round the latest transmission's round
             */
            event RoundRequested(address indexed requester, bytes16 configDigest, uint32 epoch, uint8 round);
            /**
             * @notice address of the requester access controller contract
             * @return requester access controller address
             */
            function requesterAccessController()
              external
              view
              returns (AccessControllerInterface)
            {
              return s_requesterAccessController;
            }
            /**
             * @notice sets the requester access controller
             * @param _requesterAccessController designates the address of the new requester access controller
             */
            function setRequesterAccessController(AccessControllerInterface _requesterAccessController)
              public
              onlyOwner()
            {
              AccessControllerInterface oldController = s_requesterAccessController;
              if (_requesterAccessController != oldController) {
                s_requesterAccessController = AccessControllerInterface(_requesterAccessController);
                emit RequesterAccessControllerSet(oldController, _requesterAccessController);
              }
            }
            /**
             * @notice immediately requests a new round
             * @return the aggregatorRoundId of the next round. Note: The report for this round may have been
             * transmitted (but not yet mined) *before* requestNewRound() was even called. There is *no*
             * guarantee of causality between the request and the report at aggregatorRoundId.
             */
            function requestNewRound() external returns (uint80) {
              require(msg.sender == owner || s_requesterAccessController.hasAccess(msg.sender, msg.data),
                "Only owner&requester can call");
              HotVars memory hotVars = s_hotVars;
              emit RoundRequested(
                msg.sender,
                hotVars.latestConfigDigest,
                uint32(s_hotVars.latestEpochAndRound >> 8),
                uint8(s_hotVars.latestEpochAndRound)
              );
              return hotVars.latestAggregatorRoundId + 1;
            }
            /*
             * Transmission logic
             */
            /**
             * @notice indicates that a new report was transmitted
             * @param aggregatorRoundId the round to which this report was assigned
             * @param answer median of the observations attached this report
             * @param transmitter address from which the report was transmitted
             * @param observations observations transmitted with this report
             * @param rawReportContext signature-replay-prevention domain-separation tag
             */
            event NewTransmission(
              uint32 indexed aggregatorRoundId,
              int192 answer,
              address transmitter,
              int192[] observations,
              bytes observers,
              bytes32 rawReportContext
            );
            // decodeReport is used to check that the solidity and go code are using the
            // same format. See TestOffchainAggregator.testDecodeReport and TestReportParsing
            function decodeReport(bytes memory _report)
              internal
              pure
              returns (
                bytes32 rawReportContext,
                bytes32 rawObservers,
                int192[] memory observations
              )
            {
              (rawReportContext, rawObservers, observations) = abi.decode(_report,
                (bytes32, bytes32, int192[]));
            }
            // Used to relieve stack pressure in transmit
            struct ReportData {
              HotVars hotVars; // Only read from storage once
              bytes observers; // ith element is the index of the ith observer
              int192[] observations; // ith element is the ith observation
              bytes vs; // jth element is the v component of the jth signature
              bytes32 rawReportContext;
            }
            /*
             * @notice details about the most recent report
             * @return configDigest domain separation tag for the latest report
             * @return epoch epoch in which the latest report was generated
             * @return round OCR round in which the latest report was generated
             * @return latestAnswer median value from latest report
             * @return latestTimestamp when the latest report was transmitted
             */
            function latestTransmissionDetails()
              external
              view
              returns (
                bytes16 configDigest,
                uint32 epoch,
                uint8 round,
                int192 latestAnswer,
                uint64 latestTimestamp
              )
            {
              require(msg.sender == tx.origin, "Only callable by EOA");
              return (
                s_hotVars.latestConfigDigest,
                uint32(s_hotVars.latestEpochAndRound >> 8),
                uint8(s_hotVars.latestEpochAndRound),
                s_transmissions[s_hotVars.latestAggregatorRoundId].answer,
                s_transmissions[s_hotVars.latestAggregatorRoundId].timestamp
              );
            }
            // The constant-length components of the msg.data sent to transmit.
            // See the "If we wanted to call sam" example on for example reasoning
            // https://solidity.readthedocs.io/en/v0.7.2/abi-spec.html
            uint16 private constant TRANSMIT_MSGDATA_CONSTANT_LENGTH_COMPONENT =
              4 + // function selector
              32 + // word containing start location of abiencoded _report value
              32 + // word containing location start of abiencoded  _rs value
              32 + // word containing start location of abiencoded _ss value
              32 + // _rawVs value
              32 + // word containing length of _report
              32 + // word containing length _rs
              32 + // word containing length of _ss
              0; // placeholder
            function expectedMsgDataLength(
              bytes calldata _report, bytes32[] calldata _rs, bytes32[] calldata _ss
            ) private pure returns (uint256 length)
            {
              // calldata will never be big enough to make this overflow
              return uint256(TRANSMIT_MSGDATA_CONSTANT_LENGTH_COMPONENT) +
                _report.length + // one byte pure entry in _report
                _rs.length * 32 + // 32 bytes per entry in _rs
                _ss.length * 32 + // 32 bytes per entry in _ss
                0; // placeholder
            }
            /**
             * @notice transmit is called to post a new report to the contract
             * @param _report serialized report, which the signatures are signing. See parsing code below for format. The ith element of the observers component must be the index in s_signers of the address for the ith signature
             * @param _rs ith element is the R components of the ith signature on report. Must have at most maxNumOracles entries
             * @param _ss ith element is the S components of the ith signature on report. Must have at most maxNumOracles entries
             * @param _rawVs ith element is the the V component of the ith signature
             */
            function transmit(
              // NOTE: If these parameters are changed, expectedMsgDataLength and/or
              // TRANSMIT_MSGDATA_CONSTANT_LENGTH_COMPONENT need to be changed accordingly
              bytes calldata _report,
              bytes32[] calldata _rs, bytes32[] calldata _ss, bytes32 _rawVs // signatures
            )
              external
            {
              uint256 initialGas = gasleft(); // This line must come first
              // Make sure the transmit message-length matches the inputs. Otherwise, the
              // transmitter could append an arbitrarily long (up to gas-block limit)
              // string of 0 bytes, which we would reimburse at a rate of 16 gas/byte, but
              // which would only cost the transmitter 4 gas/byte. (Appendix G of the
              // yellow paper, p. 25, for G_txdatazero and EIP 2028 for G_txdatanonzero.)
              // This could amount to reimbursement profit of 36 million gas, given a 3MB
              // zero tail.
              require(msg.data.length == expectedMsgDataLength(_report, _rs, _ss),
                "transmit message too long");
              ReportData memory r; // Relieves stack pressure
              {
                r.hotVars = s_hotVars; // cache read from storage
                bytes32 rawObservers;
                (r.rawReportContext, rawObservers, r.observations) = abi.decode(
                  _report, (bytes32, bytes32, int192[])
                );
                // rawReportContext consists of:
                // 11-byte zero padding
                // 16-byte configDigest
                // 4-byte epoch
                // 1-byte round
                bytes16 configDigest = bytes16(r.rawReportContext << 88);
                require(
                  r.hotVars.latestConfigDigest == configDigest,
                  "configDigest mismatch"
                );
                uint40 epochAndRound = uint40(uint256(r.rawReportContext));
                // direct numerical comparison works here, because
                //
                //   ((e,r) <= (e',r')) implies (epochAndRound <= epochAndRound')
                //
                // because alphabetic ordering implies e <= e', and if e = e', then r<=r',
                // so e*256+r <= e'*256+r', because r, r' < 256
                require(r.hotVars.latestEpochAndRound < epochAndRound, "stale report");
                require(_rs.length > r.hotVars.threshold, "not enough signatures");
                require(_rs.length <= maxNumOracles, "too many signatures");
                require(_ss.length == _rs.length, "signatures out of registration");
                require(r.observations.length <= maxNumOracles,
                        "num observations out of bounds");
                require(r.observations.length > 2 * r.hotVars.threshold,
                        "too few values to trust median");
                // Copy signature parities in bytes32 _rawVs to bytes r.v
                r.vs = new bytes(_rs.length);
                for (uint8 i = 0; i < _rs.length; i++) {
                  r.vs[i] = _rawVs[i];
                }
                // Copy observer identities in bytes32 rawObservers to bytes r.observers
                r.observers = new bytes(r.observations.length);
                bool[maxNumOracles] memory seen;
                for (uint8 i = 0; i < r.observations.length; i++) {
                  uint8 observerIdx = uint8(rawObservers[i]);
                  require(!seen[observerIdx], "observer index repeated");
                  seen[observerIdx] = true;
                  r.observers[i] = rawObservers[i];
                }
                Oracle memory transmitter = s_oracles[msg.sender];
                require( // Check that sender is authorized to report
                  transmitter.role == Role.Transmitter &&
                  msg.sender == s_transmitters[transmitter.index],
                  "unauthorized transmitter"
                );
                // record epochAndRound here, so that we don't have to carry the local
                // variable in transmit. The change is reverted if something fails later.
                r.hotVars.latestEpochAndRound = epochAndRound;
              }
              { // Verify signatures attached to report
                bytes32 h = keccak256(_report);
                bool[maxNumOracles] memory signed;
                Oracle memory o;
                for (uint i = 0; i < _rs.length; i++) {
                  address signer = ecrecover(h, uint8(r.vs[i])+27, _rs[i], _ss[i]);
                  o = s_oracles[signer];
                  require(o.role == Role.Signer, "address not authorized to sign");
                  require(!signed[o.index], "non-unique signature");
                  signed[o.index] = true;
                }
              }
              { // Check the report contents, and record the result
                for (uint i = 0; i < r.observations.length - 1; i++) {
                  bool inOrder = r.observations[i] <= r.observations[i+1];
                  require(inOrder, "observations not sorted");
                }
                int192 median = r.observations[r.observations.length/2];
                require(minAnswer <= median && median <= maxAnswer, "median is out of min-max range");
                r.hotVars.latestAggregatorRoundId++;
                s_transmissions[r.hotVars.latestAggregatorRoundId] =
                  Transmission(median, uint64(block.timestamp));
                emit NewTransmission(
                  r.hotVars.latestAggregatorRoundId,
                  median,
                  msg.sender,
                  r.observations,
                  r.observers,
                  r.rawReportContext
                );
                // Emit these for backwards compatability with offchain consumers
                // that only support legacy events
                emit NewRound(
                  r.hotVars.latestAggregatorRoundId,
                  address(0x0), // use zero address since we don't have anybody "starting" the round here
                  block.timestamp
                );
                emit AnswerUpdated(
                  median,
                  r.hotVars.latestAggregatorRoundId,
                  block.timestamp
                );
                validateAnswer(r.hotVars.latestAggregatorRoundId, median);
              }
              s_hotVars = r.hotVars;
              assert(initialGas < maxUint32);
              reimburseAndRewardOracles(uint32(initialGas), r.observers);
            }
            /*
             * v2 Aggregator interface
             */
            /**
             * @notice median from the most recent report
             */
            function latestAnswer()
              public
              override
              view
              virtual
              returns (int256)
            {
              return s_transmissions[s_hotVars.latestAggregatorRoundId].answer;
            }
            /**
             * @notice timestamp of block in which last report was transmitted
             */
            function latestTimestamp()
              public
              override
              view
              virtual
              returns (uint256)
            {
              return s_transmissions[s_hotVars.latestAggregatorRoundId].timestamp;
            }
            /**
             * @notice Aggregator round (NOT OCR round) in which last report was transmitted
             */
            function latestRound()
              public
              override
              view
              virtual
              returns (uint256)
            {
              return s_hotVars.latestAggregatorRoundId;
            }
            /**
             * @notice median of report from given aggregator round (NOT OCR round)
             * @param _roundId the aggregator round of the target report
             */
            function getAnswer(uint256 _roundId)
              public
              override
              view
              virtual
              returns (int256)
            {
              if (_roundId > 0xFFFFFFFF) { return 0; }
              return s_transmissions[uint32(_roundId)].answer;
            }
            /**
             * @notice timestamp of block in which report from given aggregator round was transmitted
             * @param _roundId aggregator round (NOT OCR round) of target report
             */
            function getTimestamp(uint256 _roundId)
              public
              override
              view
              virtual
              returns (uint256)
            {
              if (_roundId > 0xFFFFFFFF) { return 0; }
              return s_transmissions[uint32(_roundId)].timestamp;
            }
            /*
             * v3 Aggregator interface
             */
            string constant private V3_NO_DATA_ERROR = "No data present";
            /**
             * @return answers are stored in fixed-point format, with this many digits of precision
             */
            uint8 immutable public override decimals;
            /**
             * @notice aggregator contract version
             */
            uint256 constant public override version = 4;
            string internal s_description;
            /**
             * @notice human-readable description of observable this contract is reporting on
             */
            function description()
              public
              override
              view
              virtual
              returns (string memory)
            {
              return s_description;
            }
            /**
             * @notice details for the given aggregator round
             * @param _roundId target aggregator round (NOT OCR round). Must fit in uint32
             * @return roundId _roundId
             * @return answer median of report from given _roundId
             * @return startedAt timestamp of block in which report from given _roundId was transmitted
             * @return updatedAt timestamp of block in which report from given _roundId was transmitted
             * @return answeredInRound _roundId
             */
            function getRoundData(uint80 _roundId)
              public
              override
              view
              virtual
              returns (
                uint80 roundId,
                int256 answer,
                uint256 startedAt,
                uint256 updatedAt,
                uint80 answeredInRound
              )
            {
              require(_roundId <= 0xFFFFFFFF, V3_NO_DATA_ERROR);
              Transmission memory transmission = s_transmissions[uint32(_roundId)];
              return (
                _roundId,
                transmission.answer,
                transmission.timestamp,
                transmission.timestamp,
                _roundId
              );
            }
            /**
             * @notice aggregator details for the most recently transmitted report
             * @return roundId aggregator round of latest report (NOT OCR round)
             * @return answer median of latest report
             * @return startedAt timestamp of block containing latest report
             * @return updatedAt timestamp of block containing latest report
             * @return answeredInRound aggregator round of latest report
             */
            function latestRoundData()
              public
              override
              view
              virtual
              returns (
                uint80 roundId,
                int256 answer,
                uint256 startedAt,
                uint256 updatedAt,
                uint80 answeredInRound
              )
            {
              roundId = s_hotVars.latestAggregatorRoundId;
              // Skipped for compatability with existing FluxAggregator in which latestRoundData never reverts.
              // require(roundId != 0, V3_NO_DATA_ERROR);
              Transmission memory transmission = s_transmissions[uint32(roundId)];
              return (
                roundId,
                transmission.answer,
                transmission.timestamp,
                transmission.timestamp,
                roundId
              );
            }
          }
          // SPDX-License-Identifier: MIT
          pragma solidity 0.7.6;
          import "./AccessControllerInterface.sol";
          import "./LinkTokenInterface.sol";
          import "./Owned.sol";
          /**
           * @notice tracks administration of oracle-reward and gas-reimbursement parameters.
           * @dev
           * If you read or change this, be sure to read or adjust the comments. They
           * track the units of the values under consideration, and are crucial to
           * the readability of the operations it specifies.
           * @notice
           * Trust Model:
           * Nothing in this contract prevents a billing admin from setting insane
           * values for the billing parameters in setBilling. Oracles
           * participating in this contract should regularly check that the
           * parameters make sense. Similarly, the outstanding obligations of this
           * contract to the oracles can exceed the funds held by the contract.
           * Oracles participating in this contract should regularly check that it
           * holds sufficient funds and stop interacting with it if funding runs
           * out.
           * This still leaves oracles with some risk due to TOCTOU issues.
           * However, since the sums involved are pretty small (Ethereum
           * transactions aren't that expensive in the end) and an oracle would
           * likely stop participating in a contract it repeatedly lost money on,
           * this risk is deemed acceptable. Oracles should also regularly
           * withdraw any funds in the contract to prevent issues where the
           * contract becomes underfunded at a later time, and different oracles
           * are competing for the left-over funds.
           * Finally, note that any change to the set of oracles or to the billing
           * parameters will trigger payout of all oracles first (using the old
           * parameters), a billing admin cannot take away funds that are already
           * marked for payment.
          */
          contract OffchainAggregatorBilling is Owned {
            // Maximum number of oracles the offchain reporting protocol is designed for
            uint256 constant internal maxNumOracles = 31;
            // Parameters for oracle payments
            struct Billing {
              // Highest compensated gas price, in ETH-gwei uints
              uint32 maximumGasPrice;
              // If gas price is less (in ETH-gwei units), transmitter gets half the savings
              uint32 reasonableGasPrice;
              // Pay transmitter back this much LINK per unit eth spent on gas
              // (1e-6LINK/ETH units)
              uint32 microLinkPerEth;
              // Fixed LINK reward for each observer, in LINK-gwei units
              uint32 linkGweiPerObservation;
              // Fixed reward for transmitter, in linkGweiPerObservation units
              uint32 linkGweiPerTransmission;
            }
            Billing internal s_billing;
            // We assume that the token contract is correct. This contract is not written
            // to handle misbehaving ERC20 tokens!
            LinkTokenInterface internal s_linkToken;
            AccessControllerInterface internal s_billingAccessController;
            // ith element is number of observation rewards due to ith process, plus one.
            // This is expected to saturate after an oracle has submitted 65,535
            // observations, or about 65535/(3*24*20) = 45 days, given a transmission
            // every 3 minutes.
            //
            // This is always one greater than the actual value, so that when the value is
            // reset to zero, we don't end up with a zero value in storage (which would
            // result in a higher gas cost, the next time the value is incremented.)
            // Calculations using this variable need to take that offset into account.
            uint16[maxNumOracles] internal s_oracleObservationsCounts;
            // Addresses at which oracles want to receive payments, by transmitter address
            mapping (address /* transmitter */ => address /* payment address */)
              internal
              s_payees;
            // Payee addresses which must be approved by the owner
            mapping (address /* transmitter */ => address /* payment address */)
              internal
              s_proposedPayees;
            // LINK-wei-denominated reimbursements for gas used by transmitters.
            //
            // This is always one greater than the actual value, so that when the value is
            // reset to zero, we don't end up with a zero value in storage (which would
            // result in a higher gas cost, the next time the value is incremented.)
            // Calculations using this variable need to take that offset into account.
            //
            // Argument for overflow safety:
            // We have the following maximum intermediate values:
            // - 2**40 additions to this variable (epochAndRound is a uint40)
            // - 2**32 gas price in ethgwei/gas
            // - 1e9 ethwei/ethgwei
            // - 2**32 gas since the block gas limit is at ~20 million
            // - 2**32 (microlink/eth)
            // And we have 2**40 * 2**32 * 1e9 * 2**32 * 2**32 < 2**166
            // (we also divide in some places, but that only makes the value smaller)
            // We can thus safely use uint256 intermediate values for the computation
            // updating this variable.
            uint256[maxNumOracles] internal s_gasReimbursementsLinkWei;
            // Used for s_oracles[a].role, where a is an address, to track the purpose
            // of the address, or to indicate that the address is unset.
            enum Role {
              // No oracle role has been set for address a
              Unset,
              // Signing address for the s_oracles[a].index'th oracle. I.e., report
              // signatures from this oracle should ecrecover back to address a.
              Signer,
              // Transmission address for the s_oracles[a].index'th oracle. I.e., if a
              // report is received by OffchainAggregator.transmit in which msg.sender is
              // a, it is attributed to the s_oracles[a].index'th oracle.
              Transmitter
            }
            struct Oracle {
              uint8 index; // Index of oracle in s_signers/s_transmitters
              Role role;   // Role of the address which mapped to this struct
            }
            mapping (address /* signer OR transmitter address */ => Oracle)
              internal s_oracles;
            // s_signers contains the signing address of each oracle
            address[] internal s_signers;
            // s_transmitters contains the transmission address of each oracle,
            // i.e. the address the oracle actually sends transactions to the contract from
            address[] internal s_transmitters;
            uint256 constant private  maxUint16 = (1 << 16) - 1;
            uint256 constant internal maxUint128 = (1 << 128) - 1;
            constructor(
              uint32 _maximumGasPrice,
              uint32 _reasonableGasPrice,
              uint32 _microLinkPerEth,
              uint32 _linkGweiPerObservation,
              uint32 _linkGweiPerTransmission,
              LinkTokenInterface _link,
              AccessControllerInterface _billingAccessController
            )
            {
              setBillingInternal(_maximumGasPrice, _reasonableGasPrice, _microLinkPerEth,
                _linkGweiPerObservation, _linkGweiPerTransmission);
              s_linkToken = _link;
              emit LinkTokenSet(LinkTokenInterface(address(0)), _link);
              setBillingAccessControllerInternal(_billingAccessController);
              uint16[maxNumOracles] memory counts; // See s_oracleObservationsCounts docstring
              uint256[maxNumOracles] memory gas; // see s_gasReimbursementsLinkWei docstring
              for (uint8 i = 0; i < maxNumOracles; i++) {
                counts[i] = 1;
                gas[i] = 1;
              }
              s_oracleObservationsCounts = counts;
              s_gasReimbursementsLinkWei = gas;
            }
            /*
             * @notice emitted when the LINK token contract is set
             * @param _oldLinkToken the address of the old LINK token contract
             * @param _newLinkToken the address of the new LINK token contract
             */
            event LinkTokenSet(
              LinkTokenInterface indexed _oldLinkToken,
              LinkTokenInterface indexed _newLinkToken
            );
            /*
             * @notice sets the LINK token contract used for paying oracles
             * @param _linkToken the address of the LINK token contract
             * @param _recipient remaining funds from the previous token contract are transfered
             * here
             * @dev this function will return early (without an error) without changing any state
             * if _linkToken equals getLinkToken().
             * @dev this will trigger a payout so that a malicious owner cannot take from oracles
             * what is already owed to them.
             * @dev we assume that the token contract is correct. This contract is not written
             * to handle misbehaving ERC20 tokens!
             */
            function setLinkToken(
              LinkTokenInterface _linkToken,
              address _recipient
            ) external
              onlyOwner()
            {
              LinkTokenInterface oldLinkToken = s_linkToken;
              if (_linkToken == oldLinkToken) {
                // No change, nothing to be done
                return;
              }
              // call balanceOf as a sanity check on whether we're talking to a token
              // contract
              _linkToken.balanceOf(address(this));
              // we break CEI here, but that's okay because we're dealing with a correct
              // token contract (by assumption).
              payOracles();
              uint256 remainingBalance = oldLinkToken.balanceOf(address(this));
              require(oldLinkToken.transfer(_recipient, remainingBalance), "transfer remaining funds failed");
              s_linkToken = _linkToken;
              emit LinkTokenSet(oldLinkToken, _linkToken);
            }
            /*
             * @notice gets the LINK token contract used for paying oracles
             * @return linkToken the address of the LINK token contract
             */
            function getLinkToken()
              external
              view
              returns(LinkTokenInterface linkToken)
            {
              return s_linkToken;
            }
            /**
             * @notice emitted when billing parameters are set
             * @param maximumGasPrice highest gas price for which transmitter will be compensated
             * @param reasonableGasPrice transmitter will receive reward for gas prices under this value
             * @param microLinkPerEth reimbursement per ETH of gas cost, in 1e-6LINK units
             * @param linkGweiPerObservation reward to oracle for contributing an observation to a successfully transmitted report, in 1e-9LINK units
             * @param linkGweiPerTransmission reward to transmitter of a successful report, in 1e-9LINK units
             */
            event BillingSet(
              uint32 maximumGasPrice,
              uint32 reasonableGasPrice,
              uint32 microLinkPerEth,
              uint32 linkGweiPerObservation,
              uint32 linkGweiPerTransmission
            );
            function setBillingInternal(
              uint32 _maximumGasPrice,
              uint32 _reasonableGasPrice,
              uint32 _microLinkPerEth,
              uint32 _linkGweiPerObservation,
              uint32 _linkGweiPerTransmission
            )
              internal
            {
              s_billing = Billing(_maximumGasPrice, _reasonableGasPrice, _microLinkPerEth,
                _linkGweiPerObservation, _linkGweiPerTransmission);
              emit BillingSet(_maximumGasPrice, _reasonableGasPrice, _microLinkPerEth,
                _linkGweiPerObservation, _linkGweiPerTransmission);
            }
            /**
             * @notice sets billing parameters
             * @param _maximumGasPrice highest gas price for which transmitter will be compensated
             * @param _reasonableGasPrice transmitter will receive reward for gas prices under this value
             * @param _microLinkPerEth reimbursement per ETH of gas cost, in 1e-6LINK units
             * @param _linkGweiPerObservation reward to oracle for contributing an observation to a successfully transmitted report, in 1e-9LINK units
             * @param _linkGweiPerTransmission reward to transmitter of a successful report, in 1e-9LINK units
             * @dev access control provided by billingAccessController
             */
            function setBilling(
              uint32 _maximumGasPrice,
              uint32 _reasonableGasPrice,
              uint32 _microLinkPerEth,
              uint32 _linkGweiPerObservation,
              uint32 _linkGweiPerTransmission
            )
              external
            {
              AccessControllerInterface access = s_billingAccessController;
              require(msg.sender == owner || access.hasAccess(msg.sender, msg.data),
                "Only owner&billingAdmin can call");
              payOracles();
              setBillingInternal(_maximumGasPrice, _reasonableGasPrice, _microLinkPerEth,
                _linkGweiPerObservation, _linkGweiPerTransmission);
            }
            /**
             * @notice gets billing parameters
             * @param maximumGasPrice highest gas price for which transmitter will be compensated
             * @param reasonableGasPrice transmitter will receive reward for gas prices under this value
             * @param microLinkPerEth reimbursement per ETH of gas cost, in 1e-6LINK units
             * @param linkGweiPerObservation reward to oracle for contributing an observation to a successfully transmitted report, in 1e-9LINK units
             * @param linkGweiPerTransmission reward to transmitter of a successful report, in 1e-9LINK units
             */
            function getBilling()
              external
              view
              returns (
                uint32 maximumGasPrice,
                uint32 reasonableGasPrice,
                uint32 microLinkPerEth,
                uint32 linkGweiPerObservation,
                uint32 linkGweiPerTransmission
              )
            {
              Billing memory billing = s_billing;
              return (
                billing.maximumGasPrice,
                billing.reasonableGasPrice,
                billing.microLinkPerEth,
                billing.linkGweiPerObservation,
                billing.linkGweiPerTransmission
              );
            }
            /**
             * @notice emitted when a new access-control contract is set
             * @param old the address prior to the current setting
             * @param current the address of the new access-control contract
             */
            event BillingAccessControllerSet(AccessControllerInterface old, AccessControllerInterface current);
            function setBillingAccessControllerInternal(AccessControllerInterface _billingAccessController)
              internal
            {
              AccessControllerInterface oldController = s_billingAccessController;
              if (_billingAccessController != oldController) {
                s_billingAccessController = _billingAccessController;
                emit BillingAccessControllerSet(
                  oldController,
                  _billingAccessController
                );
              }
            }
            /**
             * @notice sets billingAccessController
             * @param _billingAccessController new billingAccessController contract address
             * @dev only owner can call this
             */
            function setBillingAccessController(AccessControllerInterface _billingAccessController)
              external
              onlyOwner
            {
              setBillingAccessControllerInternal(_billingAccessController);
            }
            /**
             * @notice gets billingAccessController
             * @return address of billingAccessController contract
             */
            function billingAccessController()
              external
              view
              returns (AccessControllerInterface)
            {
              return s_billingAccessController;
            }
            /**
             * @notice withdraws an oracle's payment from the contract
             * @param _transmitter the transmitter address of the oracle
             * @dev must be called by oracle's payee address
             */
            function withdrawPayment(address _transmitter)
              external
            {
              require(msg.sender == s_payees[_transmitter], "Only payee can withdraw");
              payOracle(_transmitter);
            }
            /**
             * @notice query an oracle's payment amount
             * @param _transmitter the transmitter address of the oracle
             */
            function owedPayment(address _transmitter)
              public
              view
              returns (uint256)
            {
              Oracle memory oracle = s_oracles[_transmitter];
              if (oracle.role == Role.Unset) { return 0; }
              Billing memory billing = s_billing;
              uint256 linkWeiAmount =
                uint256(s_oracleObservationsCounts[oracle.index] - 1) *
                uint256(billing.linkGweiPerObservation) *
                (1 gwei);
              linkWeiAmount += s_gasReimbursementsLinkWei[oracle.index] - 1;
              return linkWeiAmount;
            }
            /**
             * @notice emitted when an oracle has been paid LINK
             * @param transmitter address from which the oracle sends reports to the transmit method
             * @param payee address to which the payment is sent
             * @param amount amount of LINK sent
             * @param linkToken address of the LINK token contract
             */
            event OraclePaid(
              address indexed transmitter,
              address indexed payee,
              uint256 amount,
              LinkTokenInterface indexed linkToken
            );
            // payOracle pays out _transmitter's balance to the corresponding payee, and zeros it out
            function payOracle(address _transmitter)
              internal
            {
              Oracle memory oracle = s_oracles[_transmitter];
              uint256 linkWeiAmount = owedPayment(_transmitter);
              if (linkWeiAmount > 0) {
                address payee = s_payees[_transmitter];
                // Poses no re-entrancy issues, because LINK.transfer does not yield
                // control flow.
                require(s_linkToken.transfer(payee, linkWeiAmount), "insufficient funds");
                s_oracleObservationsCounts[oracle.index] = 1; // "zero" the counts. see var's docstring
                s_gasReimbursementsLinkWei[oracle.index] = 1; // "zero" the counts. see var's docstring
                emit OraclePaid(_transmitter, payee, linkWeiAmount, s_linkToken);
              }
            }
            // payOracles pays out all transmitters, and zeros out their balances.
            //
            // It's much more gas-efficient to do this as a single operation, to avoid
            // hitting storage too much.
            function payOracles()
              internal
            {
              Billing memory billing = s_billing;
              LinkTokenInterface linkToken = s_linkToken;
              uint16[maxNumOracles] memory observationsCounts = s_oracleObservationsCounts;
              uint256[maxNumOracles] memory gasReimbursementsLinkWei =
                s_gasReimbursementsLinkWei;
              address[] memory transmitters = s_transmitters;
              for (uint transmitteridx = 0; transmitteridx < transmitters.length; transmitteridx++) {
                uint256 reimbursementAmountLinkWei = gasReimbursementsLinkWei[transmitteridx] - 1;
                uint256 obsCount = observationsCounts[transmitteridx] - 1;
                uint256 linkWeiAmount =
                  obsCount * uint256(billing.linkGweiPerObservation) * (1 gwei) + reimbursementAmountLinkWei;
                if (linkWeiAmount > 0) {
                    address payee = s_payees[transmitters[transmitteridx]];
                    // Poses no re-entrancy issues, because LINK.transfer does not yield
                    // control flow.
                    require(linkToken.transfer(payee, linkWeiAmount), "insufficient funds");
                    observationsCounts[transmitteridx] = 1;       // "zero" the counts.
                    gasReimbursementsLinkWei[transmitteridx] = 1; // "zero" the counts.
                    emit OraclePaid(transmitters[transmitteridx], payee, linkWeiAmount, linkToken);
                  }
              }
              // "Zero" the accounting storage variables
              s_oracleObservationsCounts = observationsCounts;
              s_gasReimbursementsLinkWei = gasReimbursementsLinkWei;
            }
            function oracleRewards(
              bytes memory observers,
              uint16[maxNumOracles] memory observations
            )
              internal
              pure
              returns (uint16[maxNumOracles] memory)
            {
              // reward each observer-participant with the observer reward
              for (uint obsIdx = 0; obsIdx < observers.length; obsIdx++) {
                uint8 observer = uint8(observers[obsIdx]);
                observations[observer] = saturatingAddUint16(observations[observer], 1);
              }
              return observations;
            }
            // This value needs to change if maxNumOracles is increased, or the accounting
            // calculations at the bottom of reimburseAndRewardOracles change.
            //
            // To recalculate it, run the profiler as described in
            // ../../profile/README.md, and add up the gas-usage values reported for the
            // lines in reimburseAndRewardOracles following the "gasLeft = gasleft()"
            // line. E.g., you will see output like this:
            //
            //      7        uint256 gasLeft = gasleft();
            //     29        uint256 gasCostEthWei = transmitterGasCostEthWei(
            //      9          uint256(initialGas),
            //      3          gasPrice,
            //      3          callDataGasCost,
            //      3          gasLeft
            //      .
            //      .
            //      .
            //     59        uint256 gasCostLinkWei = (gasCostEthWei * billing.microLinkPerEth)/ 1e6;
            //      .
            //      .
            //      .
            //   5047        s_gasReimbursementsLinkWei[txOracle.index] =
            //    856          s_gasReimbursementsLinkWei[txOracle.index] + gasCostLinkWei +
            //     26          uint256(billing.linkGweiPerTransmission) * (1 gwei);
            //
            // If those were the only lines to be accounted for, you would add up
            // 29+9+3+3+3+59+5047+856+26=6035.
            uint256 internal constant accountingGasCost = 6035;
            // Uncomment the following declaration to compute the remaining gas cost after
            // above gasleft(). (This must exist in a base class to OffchainAggregator, so
            // it can't go in TestOffchainAggregator.)
            //
            // uint256 public gasUsedInAccounting;
            // Gas price at which the transmitter should be reimbursed, in ETH-gwei/gas
            function impliedGasPrice(
              uint256 txGasPrice,         // ETH-gwei/gas units
              uint256 reasonableGasPrice, // ETH-gwei/gas units
              uint256 maximumGasPrice     // ETH-gwei/gas units
            )
              internal
              pure
              returns (uint256)
            {
              // Reward the transmitter for choosing an efficient gas price: if they manage
              // to come in lower than considered reasonable, give them half the savings.
              //
              // The following calculations are all in units of gwei/gas, i.e. 1e-9ETH/gas
              uint256 gasPrice = txGasPrice;
              if (txGasPrice < reasonableGasPrice) {
                // Give transmitter half the savings for coming in under the reasonable gas price
                gasPrice += (reasonableGasPrice - txGasPrice) / 2;
              }
              // Don't reimburse a gas price higher than maximumGasPrice
              return min(gasPrice, maximumGasPrice);
            }
            // gas reimbursement due the transmitter, in ETH-wei
            //
            // If this function is changed, accountingGasCost needs to change, too. See
            // its docstring
            function transmitterGasCostEthWei(
              uint256 initialGas,
              uint256 gasPrice, // ETH-gwei/gas units
              uint256 callDataCost, // gas units
              uint256 gasLeft
            )
              internal
              pure
              returns (uint128 gasCostEthWei)
            {
              require(initialGas >= gasLeft, "gasLeft cannot exceed initialGas");
              uint256 gasUsed = // gas units
                initialGas - gasLeft + // observed gas usage
                callDataCost + accountingGasCost; // estimated gas usage
              // gasUsed is in gas units, gasPrice is in ETH-gwei/gas units; convert to ETH-wei
              uint256 fullGasCostEthWei = gasUsed * gasPrice * (1 gwei);
              assert(fullGasCostEthWei < maxUint128); // the entire ETH supply fits in a uint128...
              return uint128(fullGasCostEthWei);
            }
            /**
             * @notice withdraw any available funds left in the contract, up to _amount, after accounting for the funds due to participants in past reports
             * @param _recipient address to send funds to
             * @param _amount maximum amount to withdraw, denominated in LINK-wei.
             * @dev access control provided by billingAccessController
             */
            function withdrawFunds(address _recipient, uint256 _amount)
              external
            {
              require(msg.sender == owner || s_billingAccessController.hasAccess(msg.sender, msg.data),
                "Only owner&billingAdmin can call");
              uint256 linkDue = totalLINKDue();
              uint256 linkBalance = s_linkToken.balanceOf(address(this));
              require(linkBalance >= linkDue, "insufficient balance");
              require(s_linkToken.transfer(_recipient, min(linkBalance - linkDue, _amount)), "insufficient funds");
            }
            // Total LINK due to participants in past reports.
            function totalLINKDue()
              internal
              view
              returns (uint256 linkDue)
            {
              // Argument for overflow safety: We do all computations in
              // uint256s. The inputs to linkDue are:
              // - the <= 31 observation rewards each of which has less than
              //   64 bits (32 bits for billing.linkGweiPerObservation, 32 bits
              //   for wei/gwei conversion). Hence 69 bits are sufficient for this part.
              // - the <= 31 gas reimbursements, each of which consists of at most 166
              //   bits (see s_gasReimbursementsLinkWei docstring). Hence 171 bits are
              //   sufficient for this part
              // In total, 172 bits are enough.
              uint16[maxNumOracles] memory observationCounts = s_oracleObservationsCounts;
              for (uint i = 0; i < maxNumOracles; i++) {
                linkDue += observationCounts[i] - 1; // Stored value is one greater than actual value
              }
              Billing memory billing = s_billing;
              // Convert linkGweiPerObservation to uint256, or this overflows!
              linkDue *= uint256(billing.linkGweiPerObservation) * (1 gwei);
              address[] memory transmitters = s_transmitters;
              uint256[maxNumOracles] memory gasReimbursementsLinkWei =
                s_gasReimbursementsLinkWei;
              for (uint i = 0; i < transmitters.length; i++) {
                linkDue += uint256(gasReimbursementsLinkWei[i]-1); // Stored value is one greater than actual value
              }
            }
            /**
             * @notice allows oracles to check that sufficient LINK balance is available
             * @return availableBalance LINK available on this contract, after accounting for outstanding obligations. can become negative
             */
            function linkAvailableForPayment()
              external
              view
              returns (int256 availableBalance)
            {
              // there are at most one billion LINK, so this cast is safe
              int256 balance = int256(s_linkToken.balanceOf(address(this)));
              // according to the argument in the definition of totalLINKDue,
              // totalLINKDue is never greater than 2**172, so this cast is safe
              int256 due = int256(totalLINKDue());
              // safe from overflow according to above sizes
              return int256(balance) - int256(due);
            }
            /**
             * @notice number of observations oracle is due to be reimbursed for
             * @param _signerOrTransmitter address used by oracle for signing or transmitting reports
             */
            function oracleObservationCount(address _signerOrTransmitter)
              external
              view
              returns (uint16)
            {
              Oracle memory oracle = s_oracles[_signerOrTransmitter];
              if (oracle.role == Role.Unset) { return 0; }
              return s_oracleObservationsCounts[oracle.index] - 1;
            }
            function reimburseAndRewardOracles(
              uint32 initialGas,
              bytes memory observers
            )
              internal
            {
              Oracle memory txOracle = s_oracles[msg.sender];
              Billing memory billing = s_billing;
              // Reward oracles for providing observations. Oracles are not rewarded
              // for providing signatures, because signing is essentially free.
              s_oracleObservationsCounts =
                oracleRewards(observers, s_oracleObservationsCounts);
              // Reimburse transmitter of the report for gas usage
              require(txOracle.role == Role.Transmitter,
                "sent by undesignated transmitter"
              );
              uint256 gasPrice = impliedGasPrice(
                tx.gasprice / (1 gwei), // convert to ETH-gwei units
                billing.reasonableGasPrice,
                billing.maximumGasPrice
              );
              // The following is only an upper bound, as it ignores the cheaper cost for
              // 0 bytes. Safe from overflow, because calldata just isn't that long.
              uint256 callDataGasCost = 16 * msg.data.length;
              // If any changes are made to subsequent calculations, accountingGasCost
              // needs to change, too.
              uint256 gasLeft = gasleft();
              uint256 gasCostEthWei = transmitterGasCostEthWei(
                uint256(initialGas),
                gasPrice,
                callDataGasCost,
                gasLeft
              );
              // microLinkPerEth is 1e-6LINK/ETH units, gasCostEthWei is 1e-18ETH units
              // (ETH-wei), product is 1e-24LINK-wei units, dividing by 1e6 gives
              // 1e-18LINK units, i.e. LINK-wei units
              // Safe from over/underflow, since all components are non-negative,
              // gasCostEthWei will always fit into uint128 and microLinkPerEth is a
              // uint32 (128+32 < 256!).
              uint256 gasCostLinkWei = (gasCostEthWei * billing.microLinkPerEth)/ 1e6;
              // Safe from overflow, because gasCostLinkWei < 2**160 and
              // billing.linkGweiPerTransmission * (1 gwei) < 2**64 and we increment
              // s_gasReimbursementsLinkWei[txOracle.index] at most 2**40 times.
              s_gasReimbursementsLinkWei[txOracle.index] =
                s_gasReimbursementsLinkWei[txOracle.index] + gasCostLinkWei +
                uint256(billing.linkGweiPerTransmission) * (1 gwei); // convert from linkGwei to linkWei
              // Uncomment next line to compute the remaining gas cost after above gasleft().
              // See OffchainAggregatorBilling.accountingGasCost docstring for more information.
              //
              // gasUsedInAccounting = gasLeft - gasleft();
            }
            /*
             * Payee management
             */
            /**
             * @notice emitted when a transfer of an oracle's payee address has been initiated
             * @param transmitter address from which the oracle sends reports to the transmit method
             * @param current the payeee address for the oracle, prior to this setting
             * @param proposed the proposed new payee address for the oracle
             */
            event PayeeshipTransferRequested(
              address indexed transmitter,
              address indexed current,
              address indexed proposed
            );
            /**
             * @notice emitted when a transfer of an oracle's payee address has been completed
             * @param transmitter address from which the oracle sends reports to the transmit method
             * @param current the payeee address for the oracle, prior to this setting
             */
            event PayeeshipTransferred(
              address indexed transmitter,
              address indexed previous,
              address indexed current
            );
            /**
             * @notice sets the payees for transmitting addresses
             * @param _transmitters addresses oracles use to transmit the reports
             * @param _payees addresses of payees corresponding to list of transmitters
             * @dev must be called by owner
             * @dev cannot be used to change payee addresses, only to initially populate them
             */
            function setPayees(
              address[] calldata _transmitters,
              address[] calldata _payees
            )
              external
              onlyOwner()
            {
              require(_transmitters.length == _payees.length, "transmitters.size != payees.size");
              for (uint i = 0; i < _transmitters.length; i++) {
                address transmitter = _transmitters[i];
                address payee = _payees[i];
                address currentPayee = s_payees[transmitter];
                bool zeroedOut = currentPayee == address(0);
                require(zeroedOut || currentPayee == payee, "payee already set");
                s_payees[transmitter] = payee;
                if (currentPayee != payee) {
                  emit PayeeshipTransferred(transmitter, currentPayee, payee);
                }
              }
            }
            /**
             * @notice first step of payeeship transfer (safe transfer pattern)
             * @param _transmitter transmitter address of oracle whose payee is changing
             * @param _proposed new payee address
             * @dev can only be called by payee address
             */
            function transferPayeeship(
              address _transmitter,
              address _proposed
            )
              external
            {
                require(msg.sender == s_payees[_transmitter], "only current payee can update");
                require(msg.sender != _proposed, "cannot transfer to self");
                address previousProposed = s_proposedPayees[_transmitter];
                s_proposedPayees[_transmitter] = _proposed;
                if (previousProposed != _proposed) {
                  emit PayeeshipTransferRequested(_transmitter, msg.sender, _proposed);
                }
            }
            /**
             * @notice second step of payeeship transfer (safe transfer pattern)
             * @param _transmitter transmitter address of oracle whose payee is changing
             * @dev can only be called by proposed new payee address
             */
            function acceptPayeeship(
              address _transmitter
            )
              external
            {
              require(msg.sender == s_proposedPayees[_transmitter], "only proposed payees can accept");
              address currentPayee = s_payees[_transmitter];
              s_payees[_transmitter] = msg.sender;
              s_proposedPayees[_transmitter] = address(0);
              emit PayeeshipTransferred(_transmitter, currentPayee, msg.sender);
            }
            /*
             * Helper functions
             */
            function saturatingAddUint16(uint16 _x, uint16 _y)
              internal
              pure
              returns (uint16)
            {
              return uint16(min(uint256(_x)+uint256(_y), maxUint16));
            }
            function min(uint256 a, uint256 b)
              internal
              pure
              returns (uint256)
            {
              if (a < b) { return a; }
              return b;
            }
          }
          // SPDX-License-Identifier: MIT
          pragma solidity 0.7.6;
          /**
           * @title The Owned contract
           * @notice A contract with helpers for basic contract ownership.
           */
          contract Owned {
            address payable public owner;
            address private pendingOwner;
            event OwnershipTransferRequested(
              address indexed from,
              address indexed to
            );
            event OwnershipTransferred(
              address indexed from,
              address indexed to
            );
            constructor() {
              owner = msg.sender;
            }
            /**
             * @dev Allows an owner to begin transferring ownership to a new address,
             * pending.
             */
            function transferOwnership(address _to)
              external
              onlyOwner()
            {
              pendingOwner = _to;
              emit OwnershipTransferRequested(owner, _to);
            }
            /**
             * @dev Allows an ownership transfer to be completed by the recipient.
             */
            function acceptOwnership()
              external
            {
              require(msg.sender == pendingOwner, "Must be proposed owner");
              address oldOwner = owner;
              owner = msg.sender;
              pendingOwner = address(0);
              emit OwnershipTransferred(oldOwner, msg.sender);
            }
            /**
             * @dev Reverts if called by anyone other than the contract owner.
             */
            modifier onlyOwner() {
              require(msg.sender == owner, "Only callable by owner");
              _;
            }
          }
          // SPDX-License-Identifier: MIT
          pragma solidity 0.7.6;
          import "./SimpleWriteAccessController.sol";
          /**
           * @title SimpleReadAccessController
           * @notice Gives access to:
           * - any externally owned account (note that offchain actors can always read
           * any contract storage regardless of onchain access control measures, so this
           * does not weaken the access control while improving usability)
           * - accounts explicitly added to an access list
           * @dev SimpleReadAccessController is not suitable for access controlling writes
           * since it grants any externally owned account access! See
           * SimpleWriteAccessController for that.
           */
          contract SimpleReadAccessController is SimpleWriteAccessController {
            /**
             * @notice Returns the access of an address
             * @param _user The address to query
             */
            function hasAccess(
              address _user,
              bytes memory _calldata
            )
              public
              view
              virtual
              override
              returns (bool)
            {
              return super.hasAccess(_user, _calldata) || _user == tx.origin;
            }
          }
          // SPDX-License-Identifier: MIT
          pragma solidity 0.7.6;
          import "./Owned.sol";
          import "./AccessControllerInterface.sol";
          /**
           * @title SimpleWriteAccessController
           * @notice Gives access to accounts explicitly added to an access list by the
           * controller's owner.
           * @dev does not make any special permissions for externally, see
           * SimpleReadAccessController for that.
           */
          contract SimpleWriteAccessController is AccessControllerInterface, Owned {
            bool public checkEnabled;
            mapping(address => bool) internal accessList;
            event AddedAccess(address user);
            event RemovedAccess(address user);
            event CheckAccessEnabled();
            event CheckAccessDisabled();
            constructor()
            {
              checkEnabled = true;
            }
            /**
             * @notice Returns the access of an address
             * @param _user The address to query
             */
            function hasAccess(
              address _user,
              bytes memory
            )
              public
              view
              virtual
              override
              returns (bool)
            {
              return accessList[_user] || !checkEnabled;
            }
            /**
             * @notice Adds an address to the access list
             * @param _user The address to add
             */
            function addAccess(address _user) external onlyOwner() {
              addAccessInternal(_user);
            }
            function addAccessInternal(address _user) internal {
              if (!accessList[_user]) {
                accessList[_user] = true;
                emit AddedAccess(_user);
              }
            }
            /**
             * @notice Removes an address from the access list
             * @param _user The address to remove
             */
            function removeAccess(address _user)
              external
              onlyOwner()
            {
              if (accessList[_user]) {
                accessList[_user] = false;
                emit RemovedAccess(_user);
              }
            }
            /**
             * @notice makes the access check enforced
             */
            function enableAccessCheck()
              external
              onlyOwner()
            {
              if (!checkEnabled) {
                checkEnabled = true;
                emit CheckAccessEnabled();
              }
            }
            /**
             * @notice makes the access check unenforced
             */
            function disableAccessCheck()
              external
              onlyOwner()
            {
              if (checkEnabled) {
                checkEnabled = false;
                emit CheckAccessDisabled();
              }
            }
            /**
             * @dev reverts if the caller does not have access
             */
            modifier checkAccess() {
              require(hasAccess(msg.sender, msg.data), "No access");
              _;
            }
          }
          // SPDX-License-Identifier: MIT
          pragma solidity ^0.7.0;
          abstract contract TypeAndVersionInterface{
            function typeAndVersion()
              external
              pure
              virtual
              returns (string memory);
          }

          File 5 of 7: WETH9
          // Copyright (C) 2015, 2016, 2017 Dapphub
          
          // This program is free software: you can redistribute it and/or modify
          // it under the terms of the GNU General Public License as published by
          // the Free Software Foundation, either version 3 of the License, or
          // (at your option) any later version.
          
          // This program is distributed in the hope that it will be useful,
          // but WITHOUT ANY WARRANTY; without even the implied warranty of
          // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
          // GNU General Public License for more details.
          
          // You should have received a copy of the GNU General Public License
          // along with this program.  If not, see <http://www.gnu.org/licenses/>.
          
          pragma solidity ^0.4.18;
          
          contract WETH9 {
              string public name     = "Wrapped Ether";
              string public symbol   = "WETH";
              uint8  public decimals = 18;
          
              event  Approval(address indexed src, address indexed guy, uint wad);
              event  Transfer(address indexed src, address indexed dst, uint wad);
              event  Deposit(address indexed dst, uint wad);
              event  Withdrawal(address indexed src, uint wad);
          
              mapping (address => uint)                       public  balanceOf;
              mapping (address => mapping (address => uint))  public  allowance;
          
              function() public payable {
                  deposit();
              }
              function deposit() public payable {
                  balanceOf[msg.sender] += msg.value;
                  Deposit(msg.sender, msg.value);
              }
              function withdraw(uint wad) public {
                  require(balanceOf[msg.sender] >= wad);
                  balanceOf[msg.sender] -= wad;
                  msg.sender.transfer(wad);
                  Withdrawal(msg.sender, wad);
              }
          
              function totalSupply() public view returns (uint) {
                  return this.balance;
              }
          
              function approve(address guy, uint wad) public returns (bool) {
                  allowance[msg.sender][guy] = wad;
                  Approval(msg.sender, guy, wad);
                  return true;
              }
          
              function transfer(address dst, uint wad) public returns (bool) {
                  return transferFrom(msg.sender, dst, wad);
              }
          
              function transferFrom(address src, address dst, uint wad)
                  public
                  returns (bool)
              {
                  require(balanceOf[src] >= wad);
          
                  if (src != msg.sender && allowance[src][msg.sender] != uint(-1)) {
                      require(allowance[src][msg.sender] >= wad);
                      allowance[src][msg.sender] -= wad;
                  }
          
                  balanceOf[src] -= wad;
                  balanceOf[dst] += wad;
          
                  Transfer(src, dst, wad);
          
                  return true;
              }
          }
          
          
          /*
                              GNU GENERAL PUBLIC LICENSE
                                 Version 3, 29 June 2007
          
           Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
           Everyone is permitted to copy and distribute verbatim copies
           of this license document, but changing it is not allowed.
          
                                      Preamble
          
            The GNU General Public License is a free, copyleft license for
          software and other kinds of works.
          
            The licenses for most software and other practical works are designed
          to take away your freedom to share and change the works.  By contrast,
          the GNU General Public License is intended to guarantee your freedom to
          share and change all versions of a program--to make sure it remains free
          software for all its users.  We, the Free Software Foundation, use the
          GNU General Public License for most of our software; it applies also to
          any other work released this way by its authors.  You can apply it to
          your programs, too.
          
            When we speak of free software, we are referring to freedom, not
          price.  Our General Public Licenses are designed to make sure that you
          have the freedom to distribute copies of free software (and charge for
          them if you wish), that you receive source code or can get it if you
          want it, that you can change the software or use pieces of it in new
          free programs, and that you know you can do these things.
          
            To protect your rights, we need to prevent others from denying you
          these rights or asking you to surrender the rights.  Therefore, you have
          certain responsibilities if you distribute copies of the software, or if
          you modify it: responsibilities to respect the freedom of others.
          
            For example, if you distribute copies of such a program, whether
          gratis or for a fee, you must pass on to the recipients the same
          freedoms that you received.  You must make sure that they, too, receive
          or can get the source code.  And you must show them these terms so they
          know their rights.
          
            Developers that use the GNU GPL protect your rights with two steps:
          (1) assert copyright on the software, and (2) offer you this License
          giving you legal permission to copy, distribute and/or modify it.
          
            For the developers' and authors' protection, the GPL clearly explains
          that there is no warranty for this free software.  For both users' and
          authors' sake, the GPL requires that modified versions be marked as
          changed, so that their problems will not be attributed erroneously to
          authors of previous versions.
          
            Some devices are designed to deny users access to install or run
          modified versions of the software inside them, although the manufacturer
          can do so.  This is fundamentally incompatible with the aim of
          protecting users' freedom to change the software.  The systematic
          pattern of such abuse occurs in the area of products for individuals to
          use, which is precisely where it is most unacceptable.  Therefore, we
          have designed this version of the GPL to prohibit the practice for those
          products.  If such problems arise substantially in other domains, we
          stand ready to extend this provision to those domains in future versions
          of the GPL, as needed to protect the freedom of users.
          
            Finally, every program is threatened constantly by software patents.
          States should not allow patents to restrict development and use of
          software on general-purpose computers, but in those that do, we wish to
          avoid the special danger that patents applied to a free program could
          make it effectively proprietary.  To prevent this, the GPL assures that
          patents cannot be used to render the program non-free.
          
            The precise terms and conditions for copying, distribution and
          modification follow.
          
                                 TERMS AND CONDITIONS
          
            0. Definitions.
          
            "This License" refers to version 3 of the GNU General Public License.
          
            "Copyright" also means copyright-like laws that apply to other kinds of
          works, such as semiconductor masks.
          
            "The Program" refers to any copyrightable work licensed under this
          License.  Each licensee is addressed as "you".  "Licensees" and
          "recipients" may be individuals or organizations.
          
            To "modify" a work means to copy from or adapt all or part of the work
          in a fashion requiring copyright permission, other than the making of an
          exact copy.  The resulting work is called a "modified version" of the
          earlier work or a work "based on" the earlier work.
          
            A "covered work" means either the unmodified Program or a work based
          on the Program.
          
            To "propagate" a work means to do anything with it that, without
          permission, would make you directly or secondarily liable for
          infringement under applicable copyright law, except executing it on a
          computer or modifying a private copy.  Propagation includes copying,
          distribution (with or without modification), making available to the
          public, and in some countries other activities as well.
          
            To "convey" a work means any kind of propagation that enables other
          parties to make or receive copies.  Mere interaction with a user through
          a computer network, with no transfer of a copy, is not conveying.
          
            An interactive user interface displays "Appropriate Legal Notices"
          to the extent that it includes a convenient and prominently visible
          feature that (1) displays an appropriate copyright notice, and (2)
          tells the user that there is no warranty for the work (except to the
          extent that warranties are provided), that licensees may convey the
          work under this License, and how to view a copy of this License.  If
          the interface presents a list of user commands or options, such as a
          menu, a prominent item in the list meets this criterion.
          
            1. Source Code.
          
            The "source code" for a work means the preferred form of the work
          for making modifications to it.  "Object code" means any non-source
          form of a work.
          
            A "Standard Interface" means an interface that either is an official
          standard defined by a recognized standards body, or, in the case of
          interfaces specified for a particular programming language, one that
          is widely used among developers working in that language.
          
            The "System Libraries" of an executable work include anything, other
          than the work as a whole, that (a) is included in the normal form of
          packaging a Major Component, but which is not part of that Major
          Component, and (b) serves only to enable use of the work with that
          Major Component, or to implement a Standard Interface for which an
          implementation is available to the public in source code form.  A
          "Major Component", in this context, means a major essential component
          (kernel, window system, and so on) of the specific operating system
          (if any) on which the executable work runs, or a compiler used to
          produce the work, or an object code interpreter used to run it.
          
            The "Corresponding Source" for a work in object code form means all
          the source code needed to generate, install, and (for an executable
          work) run the object code and to modify the work, including scripts to
          control those activities.  However, it does not include the work's
          System Libraries, or general-purpose tools or generally available free
          programs which are used unmodified in performing those activities but
          which are not part of the work.  For example, Corresponding Source
          includes interface definition files associated with source files for
          the work, and the source code for shared libraries and dynamically
          linked subprograms that the work is specifically designed to require,
          such as by intimate data communication or control flow between those
          subprograms and other parts of the work.
          
            The Corresponding Source need not include anything that users
          can regenerate automatically from other parts of the Corresponding
          Source.
          
            The Corresponding Source for a work in source code form is that
          same work.
          
            2. Basic Permissions.
          
            All rights granted under this License are granted for the term of
          copyright on the Program, and are irrevocable provided the stated
          conditions are met.  This License explicitly affirms your unlimited
          permission to run the unmodified Program.  The output from running a
          covered work is covered by this License only if the output, given its
          content, constitutes a covered work.  This License acknowledges your
          rights of fair use or other equivalent, as provided by copyright law.
          
            You may make, run and propagate covered works that you do not
          convey, without conditions so long as your license otherwise remains
          in force.  You may convey covered works to others for the sole purpose
          of having them make modifications exclusively for you, or provide you
          with facilities for running those works, provided that you comply with
          the terms of this License in conveying all material for which you do
          not control copyright.  Those thus making or running the covered works
          for you must do so exclusively on your behalf, under your direction
          and control, on terms that prohibit them from making any copies of
          your copyrighted material outside their relationship with you.
          
            Conveying under any other circumstances is permitted solely under
          the conditions stated below.  Sublicensing is not allowed; section 10
          makes it unnecessary.
          
            3. Protecting Users' Legal Rights From Anti-Circumvention Law.
          
            No covered work shall be deemed part of an effective technological
          measure under any applicable law fulfilling obligations under article
          11 of the WIPO copyright treaty adopted on 20 December 1996, or
          similar laws prohibiting or restricting circumvention of such
          measures.
          
            When you convey a covered work, you waive any legal power to forbid
          circumvention of technological measures to the extent such circumvention
          is effected by exercising rights under this License with respect to
          the covered work, and you disclaim any intention to limit operation or
          modification of the work as a means of enforcing, against the work's
          users, your or third parties' legal rights to forbid circumvention of
          technological measures.
          
            4. Conveying Verbatim Copies.
          
            You may convey verbatim copies of the Program's source code as you
          receive it, in any medium, provided that you conspicuously and
          appropriately publish on each copy an appropriate copyright notice;
          keep intact all notices stating that this License and any
          non-permissive terms added in accord with section 7 apply to the code;
          keep intact all notices of the absence of any warranty; and give all
          recipients a copy of this License along with the Program.
          
            You may charge any price or no price for each copy that you convey,
          and you may offer support or warranty protection for a fee.
          
            5. Conveying Modified Source Versions.
          
            You may convey a work based on the Program, or the modifications to
          produce it from the Program, in the form of source code under the
          terms of section 4, provided that you also meet all of these conditions:
          
              a) The work must carry prominent notices stating that you modified
              it, and giving a relevant date.
          
              b) The work must carry prominent notices stating that it is
              released under this License and any conditions added under section
              7.  This requirement modifies the requirement in section 4 to
              "keep intact all notices".
          
              c) You must license the entire work, as a whole, under this
              License to anyone who comes into possession of a copy.  This
              License will therefore apply, along with any applicable section 7
              additional terms, to the whole of the work, and all its parts,
              regardless of how they are packaged.  This License gives no
              permission to license the work in any other way, but it does not
              invalidate such permission if you have separately received it.
          
              d) If the work has interactive user interfaces, each must display
              Appropriate Legal Notices; however, if the Program has interactive
              interfaces that do not display Appropriate Legal Notices, your
              work need not make them do so.
          
            A compilation of a covered work with other separate and independent
          works, which are not by their nature extensions of the covered work,
          and which are not combined with it such as to form a larger program,
          in or on a volume of a storage or distribution medium, is called an
          "aggregate" if the compilation and its resulting copyright are not
          used to limit the access or legal rights of the compilation's users
          beyond what the individual works permit.  Inclusion of a covered work
          in an aggregate does not cause this License to apply to the other
          parts of the aggregate.
          
            6. Conveying Non-Source Forms.
          
            You may convey a covered work in object code form under the terms
          of sections 4 and 5, provided that you also convey the
          machine-readable Corresponding Source under the terms of this License,
          in one of these ways:
          
              a) Convey the object code in, or embodied in, a physical product
              (including a physical distribution medium), accompanied by the
              Corresponding Source fixed on a durable physical medium
              customarily used for software interchange.
          
              b) Convey the object code in, or embodied in, a physical product
              (including a physical distribution medium), accompanied by a
              written offer, valid for at least three years and valid for as
              long as you offer spare parts or customer support for that product
              model, to give anyone who possesses the object code either (1) a
              copy of the Corresponding Source for all the software in the
              product that is covered by this License, on a durable physical
              medium customarily used for software interchange, for a price no
              more than your reasonable cost of physically performing this
              conveying of source, or (2) access to copy the
              Corresponding Source from a network server at no charge.
          
              c) Convey individual copies of the object code with a copy of the
              written offer to provide the Corresponding Source.  This
              alternative is allowed only occasionally and noncommercially, and
              only if you received the object code with such an offer, in accord
              with subsection 6b.
          
              d) Convey the object code by offering access from a designated
              place (gratis or for a charge), and offer equivalent access to the
              Corresponding Source in the same way through the same place at no
              further charge.  You need not require recipients to copy the
              Corresponding Source along with the object code.  If the place to
              copy the object code is a network server, the Corresponding Source
              may be on a different server (operated by you or a third party)
              that supports equivalent copying facilities, provided you maintain
              clear directions next to the object code saying where to find the
              Corresponding Source.  Regardless of what server hosts the
              Corresponding Source, you remain obligated to ensure that it is
              available for as long as needed to satisfy these requirements.
          
              e) Convey the object code using peer-to-peer transmission, provided
              you inform other peers where the object code and Corresponding
              Source of the work are being offered to the general public at no
              charge under subsection 6d.
          
            A separable portion of the object code, whose source code is excluded
          from the Corresponding Source as a System Library, need not be
          included in conveying the object code work.
          
            A "User Product" is either (1) a "consumer product", which means any
          tangible personal property which is normally used for personal, family,
          or household purposes, or (2) anything designed or sold for incorporation
          into a dwelling.  In determining whether a product is a consumer product,
          doubtful cases shall be resolved in favor of coverage.  For a particular
          product received by a particular user, "normally used" refers to a
          typical or common use of that class of product, regardless of the status
          of the particular user or of the way in which the particular user
          actually uses, or expects or is expected to use, the product.  A product
          is a consumer product regardless of whether the product has substantial
          commercial, industrial or non-consumer uses, unless such uses represent
          the only significant mode of use of the product.
          
            "Installation Information" for a User Product means any methods,
          procedures, authorization keys, or other information required to install
          and execute modified versions of a covered work in that User Product from
          a modified version of its Corresponding Source.  The information must
          suffice to ensure that the continued functioning of the modified object
          code is in no case prevented or interfered with solely because
          modification has been made.
          
            If you convey an object code work under this section in, or with, or
          specifically for use in, a User Product, and the conveying occurs as
          part of a transaction in which the right of possession and use of the
          User Product is transferred to the recipient in perpetuity or for a
          fixed term (regardless of how the transaction is characterized), the
          Corresponding Source conveyed under this section must be accompanied
          by the Installation Information.  But this requirement does not apply
          if neither you nor any third party retains the ability to install
          modified object code on the User Product (for example, the work has
          been installed in ROM).
          
            The requirement to provide Installation Information does not include a
          requirement to continue to provide support service, warranty, or updates
          for a work that has been modified or installed by the recipient, or for
          the User Product in which it has been modified or installed.  Access to a
          network may be denied when the modification itself materially and
          adversely affects the operation of the network or violates the rules and
          protocols for communication across the network.
          
            Corresponding Source conveyed, and Installation Information provided,
          in accord with this section must be in a format that is publicly
          documented (and with an implementation available to the public in
          source code form), and must require no special password or key for
          unpacking, reading or copying.
          
            7. Additional Terms.
          
            "Additional permissions" are terms that supplement the terms of this
          License by making exceptions from one or more of its conditions.
          Additional permissions that are applicable to the entire Program shall
          be treated as though they were included in this License, to the extent
          that they are valid under applicable law.  If additional permissions
          apply only to part of the Program, that part may be used separately
          under those permissions, but the entire Program remains governed by
          this License without regard to the additional permissions.
          
            When you convey a copy of a covered work, you may at your option
          remove any additional permissions from that copy, or from any part of
          it.  (Additional permissions may be written to require their own
          removal in certain cases when you modify the work.)  You may place
          additional permissions on material, added by you to a covered work,
          for which you have or can give appropriate copyright permission.
          
            Notwithstanding any other provision of this License, for material you
          add to a covered work, you may (if authorized by the copyright holders of
          that material) supplement the terms of this License with terms:
          
              a) Disclaiming warranty or limiting liability differently from the
              terms of sections 15 and 16 of this License; or
          
              b) Requiring preservation of specified reasonable legal notices or
              author attributions in that material or in the Appropriate Legal
              Notices displayed by works containing it; or
          
              c) Prohibiting misrepresentation of the origin of that material, or
              requiring that modified versions of such material be marked in
              reasonable ways as different from the original version; or
          
              d) Limiting the use for publicity purposes of names of licensors or
              authors of the material; or
          
              e) Declining to grant rights under trademark law for use of some
              trade names, trademarks, or service marks; or
          
              f) Requiring indemnification of licensors and authors of that
              material by anyone who conveys the material (or modified versions of
              it) with contractual assumptions of liability to the recipient, for
              any liability that these contractual assumptions directly impose on
              those licensors and authors.
          
            All other non-permissive additional terms are considered "further
          restrictions" within the meaning of section 10.  If the Program as you
          received it, or any part of it, contains a notice stating that it is
          governed by this License along with a term that is a further
          restriction, you may remove that term.  If a license document contains
          a further restriction but permits relicensing or conveying under this
          License, you may add to a covered work material governed by the terms
          of that license document, provided that the further restriction does
          not survive such relicensing or conveying.
          
            If you add terms to a covered work in accord with this section, you
          must place, in the relevant source files, a statement of the
          additional terms that apply to those files, or a notice indicating
          where to find the applicable terms.
          
            Additional terms, permissive or non-permissive, may be stated in the
          form of a separately written license, or stated as exceptions;
          the above requirements apply either way.
          
            8. Termination.
          
            You may not propagate or modify a covered work except as expressly
          provided under this License.  Any attempt otherwise to propagate or
          modify it is void, and will automatically terminate your rights under
          this License (including any patent licenses granted under the third
          paragraph of section 11).
          
            However, if you cease all violation of this License, then your
          license from a particular copyright holder is reinstated (a)
          provisionally, unless and until the copyright holder explicitly and
          finally terminates your license, and (b) permanently, if the copyright
          holder fails to notify you of the violation by some reasonable means
          prior to 60 days after the cessation.
          
            Moreover, your license from a particular copyright holder is
          reinstated permanently if the copyright holder notifies you of the
          violation by some reasonable means, this is the first time you have
          received notice of violation of this License (for any work) from that
          copyright holder, and you cure the violation prior to 30 days after
          your receipt of the notice.
          
            Termination of your rights under this section does not terminate the
          licenses of parties who have received copies or rights from you under
          this License.  If your rights have been terminated and not permanently
          reinstated, you do not qualify to receive new licenses for the same
          material under section 10.
          
            9. Acceptance Not Required for Having Copies.
          
            You are not required to accept this License in order to receive or
          run a copy of the Program.  Ancillary propagation of a covered work
          occurring solely as a consequence of using peer-to-peer transmission
          to receive a copy likewise does not require acceptance.  However,
          nothing other than this License grants you permission to propagate or
          modify any covered work.  These actions infringe copyright if you do
          not accept this License.  Therefore, by modifying or propagating a
          covered work, you indicate your acceptance of this License to do so.
          
            10. Automatic Licensing of Downstream Recipients.
          
            Each time you convey a covered work, the recipient automatically
          receives a license from the original licensors, to run, modify and
          propagate that work, subject to this License.  You are not responsible
          for enforcing compliance by third parties with this License.
          
            An "entity transaction" is a transaction transferring control of an
          organization, or substantially all assets of one, or subdividing an
          organization, or merging organizations.  If propagation of a covered
          work results from an entity transaction, each party to that
          transaction who receives a copy of the work also receives whatever
          licenses to the work the party's predecessor in interest had or could
          give under the previous paragraph, plus a right to possession of the
          Corresponding Source of the work from the predecessor in interest, if
          the predecessor has it or can get it with reasonable efforts.
          
            You may not impose any further restrictions on the exercise of the
          rights granted or affirmed under this License.  For example, you may
          not impose a license fee, royalty, or other charge for exercise of
          rights granted under this License, and you may not initiate litigation
          (including a cross-claim or counterclaim in a lawsuit) alleging that
          any patent claim is infringed by making, using, selling, offering for
          sale, or importing the Program or any portion of it.
          
            11. Patents.
          
            A "contributor" is a copyright holder who authorizes use under this
          License of the Program or a work on which the Program is based.  The
          work thus licensed is called the contributor's "contributor version".
          
            A contributor's "essential patent claims" are all patent claims
          owned or controlled by the contributor, whether already acquired or
          hereafter acquired, that would be infringed by some manner, permitted
          by this License, of making, using, or selling its contributor version,
          but do not include claims that would be infringed only as a
          consequence of further modification of the contributor version.  For
          purposes of this definition, "control" includes the right to grant
          patent sublicenses in a manner consistent with the requirements of
          this License.
          
            Each contributor grants you a non-exclusive, worldwide, royalty-free
          patent license under the contributor's essential patent claims, to
          make, use, sell, offer for sale, import and otherwise run, modify and
          propagate the contents of its contributor version.
          
            In the following three paragraphs, a "patent license" is any express
          agreement or commitment, however denominated, not to enforce a patent
          (such as an express permission to practice a patent or covenant not to
          sue for patent infringement).  To "grant" such a patent license to a
          party means to make such an agreement or commitment not to enforce a
          patent against the party.
          
            If you convey a covered work, knowingly relying on a patent license,
          and the Corresponding Source of the work is not available for anyone
          to copy, free of charge and under the terms of this License, through a
          publicly available network server or other readily accessible means,
          then you must either (1) cause the Corresponding Source to be so
          available, or (2) arrange to deprive yourself of the benefit of the
          patent license for this particular work, or (3) arrange, in a manner
          consistent with the requirements of this License, to extend the patent
          license to downstream recipients.  "Knowingly relying" means you have
          actual knowledge that, but for the patent license, your conveying the
          covered work in a country, or your recipient's use of the covered work
          in a country, would infringe one or more identifiable patents in that
          country that you have reason to believe are valid.
          
            If, pursuant to or in connection with a single transaction or
          arrangement, you convey, or propagate by procuring conveyance of, a
          covered work, and grant a patent license to some of the parties
          receiving the covered work authorizing them to use, propagate, modify
          or convey a specific copy of the covered work, then the patent license
          you grant is automatically extended to all recipients of the covered
          work and works based on it.
          
            A patent license is "discriminatory" if it does not include within
          the scope of its coverage, prohibits the exercise of, or is
          conditioned on the non-exercise of one or more of the rights that are
          specifically granted under this License.  You may not convey a covered
          work if you are a party to an arrangement with a third party that is
          in the business of distributing software, under which you make payment
          to the third party based on the extent of your activity of conveying
          the work, and under which the third party grants, to any of the
          parties who would receive the covered work from you, a discriminatory
          patent license (a) in connection with copies of the covered work
          conveyed by you (or copies made from those copies), or (b) primarily
          for and in connection with specific products or compilations that
          contain the covered work, unless you entered into that arrangement,
          or that patent license was granted, prior to 28 March 2007.
          
            Nothing in this License shall be construed as excluding or limiting
          any implied license or other defenses to infringement that may
          otherwise be available to you under applicable patent law.
          
            12. No Surrender of Others' Freedom.
          
            If conditions are imposed on you (whether by court order, agreement or
          otherwise) that contradict the conditions of this License, they do not
          excuse you from the conditions of this License.  If you cannot convey a
          covered work so as to satisfy simultaneously your obligations under this
          License and any other pertinent obligations, then as a consequence you may
          not convey it at all.  For example, if you agree to terms that obligate you
          to collect a royalty for further conveying from those to whom you convey
          the Program, the only way you could satisfy both those terms and this
          License would be to refrain entirely from conveying the Program.
          
            13. Use with the GNU Affero General Public License.
          
            Notwithstanding any other provision of this License, you have
          permission to link or combine any covered work with a work licensed
          under version 3 of the GNU Affero General Public License into a single
          combined work, and to convey the resulting work.  The terms of this
          License will continue to apply to the part which is the covered work,
          but the special requirements of the GNU Affero General Public License,
          section 13, concerning interaction through a network will apply to the
          combination as such.
          
            14. Revised Versions of this License.
          
            The Free Software Foundation may publish revised and/or new versions of
          the GNU General Public License from time to time.  Such new versions will
          be similar in spirit to the present version, but may differ in detail to
          address new problems or concerns.
          
            Each version is given a distinguishing version number.  If the
          Program specifies that a certain numbered version of the GNU General
          Public License "or any later version" applies to it, you have the
          option of following the terms and conditions either of that numbered
          version or of any later version published by the Free Software
          Foundation.  If the Program does not specify a version number of the
          GNU General Public License, you may choose any version ever published
          by the Free Software Foundation.
          
            If the Program specifies that a proxy can decide which future
          versions of the GNU General Public License can be used, that proxy's
          public statement of acceptance of a version permanently authorizes you
          to choose that version for the Program.
          
            Later license versions may give you additional or different
          permissions.  However, no additional obligations are imposed on any
          author or copyright holder as a result of your choosing to follow a
          later version.
          
            15. Disclaimer of Warranty.
          
            THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
          APPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
          HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
          OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
          THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
          PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
          IS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
          ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
          
            16. Limitation of Liability.
          
            IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
          WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
          THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
          GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
          USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
          DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
          PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
          EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
          SUCH DAMAGES.
          
            17. Interpretation of Sections 15 and 16.
          
            If the disclaimer of warranty and limitation of liability provided
          above cannot be given local legal effect according to their terms,
          reviewing courts shall apply local law that most closely approximates
          an absolute waiver of all civil liability in connection with the
          Program, unless a warranty or assumption of liability accompanies a
          copy of the Program in return for a fee.
          
                               END OF TERMS AND CONDITIONS
          
                      How to Apply These Terms to Your New Programs
          
            If you develop a new program, and you want it to be of the greatest
          possible use to the public, the best way to achieve this is to make it
          free software which everyone can redistribute and change under these terms.
          
            To do so, attach the following notices to the program.  It is safest
          to attach them to the start of each source file to most effectively
          state the exclusion of warranty; and each file should have at least
          the "copyright" line and a pointer to where the full notice is found.
          
              <one line to give the program's name and a brief idea of what it does.>
              Copyright (C) <year>  <name of author>
          
              This program is free software: you can redistribute it and/or modify
              it under the terms of the GNU General Public License as published by
              the Free Software Foundation, either version 3 of the License, or
              (at your option) any later version.
          
              This program is distributed in the hope that it will be useful,
              but WITHOUT ANY WARRANTY; without even the implied warranty of
              MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
              GNU General Public License for more details.
          
              You should have received a copy of the GNU General Public License
              along with this program.  If not, see <http://www.gnu.org/licenses/>.
          
          Also add information on how to contact you by electronic and paper mail.
          
            If the program does terminal interaction, make it output a short
          notice like this when it starts in an interactive mode:
          
              <program>  Copyright (C) <year>  <name of author>
              This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
              This is free software, and you are welcome to redistribute it
              under certain conditions; type `show c' for details.
          
          The hypothetical commands `show w' and `show c' should show the appropriate
          parts of the General Public License.  Of course, your program's commands
          might be different; for a GUI interface, you would use an "about box".
          
            You should also get your employer (if you work as a programmer) or school,
          if any, to sign a "copyright disclaimer" for the program, if necessary.
          For more information on this, and how to apply and follow the GNU GPL, see
          <http://www.gnu.org/licenses/>.
          
            The GNU General Public License does not permit incorporating your program
          into proprietary programs.  If your program is a subroutine library, you
          may consider it more useful to permit linking proprietary applications with
          the library.  If this is what you want to do, use the GNU Lesser General
          Public License instead of this License.  But first, please read
          <http://www.gnu.org/philosophy/why-not-lgpl.html>.
          
          */

          File 6 of 7: Ethervista
          // SPDX-License-Identifier: MIT
          pragma solidity ^0.8.0;
          
          interface IEtherVistaFactory {
              event PairCreated(address indexed token0, address indexed token1, address pair, uint);
          
              function feeTo() external view returns (address);
              function feeToSetter() external view returns (address);
              function routerSetter() external view returns (address);
              function router() external view returns (address);
          
              function getPair(address tokenA, address tokenB) external view returns (address pair);
              function allPairs(uint) external view returns (address pair);
              function allPairsLength() external view returns (uint);
          
              function createPair(address tokenA, address tokenB) external returns (address pair);
          
              function setFeeTo(address) external;
              function setFeeToSetter(address) external;
              function setRouterSetter(address) external;
              function setRouter(address) external;
          }
          
          interface IERC20Errors {
          
              error ERC20InsufficientBalance(address sender, uint256 balance, uint256 needed);
          
              error ERC20InvalidSender(address sender);
          
              error ERC20InvalidReceiver(address receiver);
          
              error ERC20InsufficientAllowance(address spender, uint256 allowance, uint256 needed);
          
              error ERC20InvalidApprover(address approver);
          
              error ERC20InvalidSpender(address spender);
          }
          
          abstract contract Context {
              function _msgSender() internal view virtual returns (address) {
                  return msg.sender;
              }
          
              function _msgData() internal view virtual returns (bytes calldata) {
                  return msg.data;
              }
          
              function _contextSuffixLength() internal view virtual returns (uint256) {
                  return 0;
              }
          }
          
          interface IERC20 {
          
              event Transfer(address indexed from, address indexed to, uint256 value);
          
              event Approval(address indexed owner, address indexed spender, uint256 value);
          
              function totalSupply() external view returns (uint256);
          
              function balanceOf(address account) external view returns (uint256);
          
              function transfer(address to, uint256 value) external returns (bool);
          
              function allowance(address owner, address spender) external view returns (uint256);
          
              function approve(address spender, uint256 value) external returns (bool);
          
              function transferFrom(address from, address to, uint256 value) external returns (bool);
          }
          
          interface IERC20Metadata is IERC20 {
            
              function name() external view returns (string memory);
          
              function symbol() external view returns (string memory);
          
              function decimals() external view returns (uint8);
          }
          
          abstract contract ERC20 is Context, IERC20, IERC20Metadata, IERC20Errors {
              mapping(address account => uint256) private _balances;
          
              mapping(address account => mapping(address spender => uint256)) private _allowances;
          
              uint256 private _totalSupply;
          
              string private _name;
              string private _symbol;
              address factory;
          
              constructor(string memory name_, string memory symbol_, address _factory) {
                  _name = name_;
                  _symbol = symbol_;
                  factory = _factory;
              }
          
              function name() public view virtual returns (string memory) {
                  return _name;
              }
          
              function symbol() public view virtual returns (string memory) {
                  return _symbol;
              }
          
              function decimals() public view virtual returns (uint8) {
                  return 18;
              }
          
              function totalSupply() public view virtual returns (uint256) {
                  return _totalSupply;
              }
          
              function balanceOf(address account) public view virtual returns (uint256) {
                  return _balances[account];
              }
          
              function transfer(address to, uint256 value) public virtual returns (bool) {
                  address owner = _msgSender();
                  _transfer(owner, to, value);
                  return true;
              }
          
              function allowance(address owner, address spender) public view virtual returns (uint256) {
                  return _allowances[owner][spender];
              }
          
              function approve(address spender, uint256 value) public virtual returns (bool) {
                  require(spender == IEtherVistaFactory(factory).router(), 'EtherVista: FORBIDDEN');
                  address owner = _msgSender();
                  _approve(owner, spender, value);
                  return true;
              }
          
              function transferFrom(address from, address to, uint256 value) public virtual returns (bool) {
                  address spender = _msgSender();
                  _spendAllowance(from, spender, value);
                  _transfer(from, to, value);
                  return true;
              }
          
              function _transfer(address from, address to, uint256 value) internal {
                  if (from == address(0)) {
                      revert ERC20InvalidSender(address(0));
                  }
                  if (to == address(0)) {
                      revert ERC20InvalidReceiver(address(0));
                  }
                  _update(from, to, value);
              }
          
              function _update(address from, address to, uint256 value) internal virtual {
                  if (from == address(0)) {
                      _totalSupply += value;
                  } else {
                      uint256 fromBalance = _balances[from];
                      if (fromBalance < value) {
                          revert ERC20InsufficientBalance(from, fromBalance, value);
                      }
                      unchecked {
                          _balances[from] = fromBalance - value;
                      }
                  }
          
                  if (to == address(0)) {
                      unchecked {
                          _totalSupply -= value;
                      }
                  } else {
                      unchecked {
                          _balances[to] += value;
                      }
                  }
          
                  emit Transfer(from, to, value);
              }
          
              function _mint(address account, uint256 value) internal {
                  if (account == address(0)) {
                      revert ERC20InvalidReceiver(address(0));
                  }
                  _update(address(0), account, value);
              }
          
              function _approve(address owner, address spender, uint256 value) internal {
                  _approve(owner, spender, value, true);
              }
          
              function _approve(address owner, address spender, uint256 value, bool emitEvent) internal virtual {
                  if (owner == address(0)) {
                      revert ERC20InvalidApprover(address(0));
                  }
                  if (spender == address(0)) {
                      revert ERC20InvalidSpender(address(0));
                  }
                  _allowances[owner][spender] = value;
                  if (emitEvent) {
                      emit Approval(owner, spender, value);
                  }
              }
          
              function _spendAllowance(address owner, address spender, uint256 value) internal virtual {
                  uint256 currentAllowance = allowance(owner, spender);
                  if (currentAllowance != type(uint256).max) {
                      if (currentAllowance < value) {
                          revert ERC20InsufficientAllowance(spender, currentAllowance, value);
                      }
                      unchecked {
                          _approve(owner, spender, currentAllowance - value, false);
                      }
                  }
              }
          }
          
          
          contract Ethervista is ERC20 {
              constructor(address factory) ERC20("Ethervista", "VISTA", factory) {
                  _mint(msg.sender, 1000000 * 10 ** 18);
              }
          }

          File 7 of 7: EtherVistaFactory
          pragma solidity =0.5.16;
          import './EtherVistaPair.sol';
          contract EtherVistaFactory is IEtherVistaFactory {
              address public feeTo;
              address public feeToSetter;
              address public routerSetter; 
              address public router; 
              mapping(address => mapping(address => address)) public getPair;
              address[] public allPairs;
              event PairCreated(address indexed token0, address indexed token1, address pair, uint);
              bytes32 public constant INIT_CODE_HASH = keccak256(abi.encodePacked(type(EtherVistaPair).creationCode));
              constructor() public {
                  feeToSetter = 0x0000000000000000000000000000000000000000;
                  routerSetter = msg.sender;
              }
              function allPairsLength() external view returns (uint) {
                  return allPairs.length;
              }
              function setRouter(address _router) external {
                  require(msg.sender == routerSetter, 'EtherVista: FORBIDDEN');
                  router = _router;
              }
              //Can be set to the zero-address if there is no intent to upgrade Router versions
              function setRouterSetter(address setter) external {
                  require(msg.sender == routerSetter, 'EtherVista: FORBIDDEN');        
                  routerSetter = setter;
              }
              
              function createPair(address tokenA, address tokenB) external returns (address pair) {
                  require(tokenA != tokenB, 'EtherVista: IDENTICAL_ADDRESSES');
                  (address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
                  require(token0 != address(0), 'EtherVista: ZERO_ADDRESS');
                  require(getPair[token0][token1] == address(0), 'EtherVista: PAIR_EXISTS'); // single check is sufficient
                  bytes memory bytecode = type(EtherVistaPair).creationCode;
                  bytes32 salt = keccak256(abi.encodePacked(token0, token1)); 
                  assembly {
                      pair := create2(0, add(bytecode, 32), mload(bytecode), salt)
                  }
                  IEtherVistaPair(pair).initialize(token0, token1);
                  getPair[token0][token1] = pair;
                  getPair[token1][token0] = pair; // populate mapping in the reverse direction
                  allPairs.push(pair);
                  emit PairCreated(token0, token1, pair, allPairs.length);
              }
              function setFeeTo(address _feeTo) external {
                  require(msg.sender == feeToSetter, 'EtherVista: FORBIDDEN');
                  feeTo = _feeTo;
              }
              function setFeeToSetter(address _feeToSetter) external {
                  require(msg.sender == feeToSetter, 'EtherVista: FORBIDDEN');
                  feeToSetter = _feeToSetter;
              }
          }
          pragma solidity =0.5.16;
          interface IEtherVistaPair {
              event Approval(address indexed owner, address indexed spender, uint value);
              event Transfer(address indexed from, address indexed to, uint value);
              
              function setMetadata(string calldata website, string calldata image, string calldata description, string calldata chat, string calldata social) external;
              function fetchMetadata() external view returns(string memory, string memory, string memory, string memory, string memory);
              function name() external pure returns (string memory);
              function symbol() external pure returns (string memory);
              function decimals() external pure returns (uint8);
              function totalSupply() external view returns (uint);
              function balanceOf(address owner) external view returns (uint);
              function allowance(address owner, address spender) external view returns (uint);
              function updateProvider(address user) external;
              function euler(uint) external view returns (uint256);
              function viewShare() external view returns (uint256 share);
              function claimShare() external;
              function poolBalance() external view returns (uint);
              function totalCollected() external view returns (uint);
              
              function updateProtocol(address) external;
              function setProtocol() external;
              function protocol() external view returns (address);
              function payableProtocol() external view returns (address payable origin);
              function creator() external view returns (address);
              function renounce() external;
              function setFees() external;
              function updateFees(uint8, uint8, uint8, uint8) external;
              function buyLpFee() external view returns (uint8);
              function sellLpFee() external view returns (uint8);
              function buyProtocolFee() external view returns (uint8);
              function sellProtocolFee() external view returns (uint8);
              function buyTotalFee() external view returns (uint8);
              function sellTotalFee() external view returns (uint8);
              function approve(address spender, uint value) external returns (bool);
              function transfer(address to, uint value) external returns (bool);
              function transferFrom(address from, address to, uint value) external returns (bool);
              function DOMAIN_SEPARATOR() external view returns (bytes32);
              function PERMIT_TYPEHASH() external pure returns (bytes32);
              function nonces(address owner) external view returns (uint);
              function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
              event Mint(address indexed sender, uint amount0, uint amount1);
              event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
              event Swap(
                  address indexed sender,
                  uint amount0In,
                  uint amount1In,
                  uint amount0Out,
                  uint amount1Out,
                  address indexed to
              );
              event Sync(uint112 reserve0, uint112 reserve1);
              function MINIMUM_LIQUIDITY() external pure returns (uint);
              function factory() external view returns (address);
              function token0() external view returns (address);
              function token1() external view returns (address);
              function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
              function price0CumulativeLast() external view returns (uint);
              function price1CumulativeLast() external view returns (uint);
              function kLast() external view returns (uint);
              function first_mint(address to, uint8 buyLp, uint8 sellLp, uint8 buyProtocol, uint8 sellProtocol, address protocolAddress) external returns (uint liquidity);   
              function mint(address to) external returns (uint liquidity);
              function burn(address to) external returns (uint amount0, uint amount1);
              function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
              function skim(address to) external;
              function sync() external;
              function initialize(address _token0, address _token1) external;
          }
          interface IEtherVistaERC20 {
              event Approval(address indexed owner, address indexed spender, uint value);
              event Transfer(address indexed from, address indexed to, uint value);
              function name() external pure returns (string memory);
              function symbol() external pure returns (string memory);
              function decimals() external pure returns (uint8);
              function totalSupply() external view returns (uint);
              function balanceOf(address owner) external view returns (uint);
              function allowance(address owner, address spender) external view returns (uint);
              function approve(address spender, uint value) external returns (bool);
              function transfer(address to, uint value) external returns (bool);
              function transferFrom(address from, address to, uint value) external returns (bool);
              function DOMAIN_SEPARATOR() external view returns (bytes32);
              function PERMIT_TYPEHASH() external pure returns (bytes32);
              function nonces(address owner) external view returns (uint);
              function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
          }
          interface IERC20 {
              event Approval(address indexed owner, address indexed spender, uint value);
              event Transfer(address indexed from, address indexed to, uint value);
              function name() external view returns (string memory);
              function symbol() external view returns (string memory);
              function decimals() external view returns (uint8);
              function totalSupply() external view returns (uint);
              function balanceOf(address owner) external view returns (uint);
              function allowance(address owner, address spender) external view returns (uint);
              function approve(address spender, uint value) external returns (bool);
              function transfer(address to, uint value) external returns (bool);
              function transferFrom(address from, address to, uint value) external returns (bool);
          }
          interface IEtherVistaFactory {
              event PairCreated(address indexed token0, address indexed token1, address pair, uint);
              function feeTo() external view returns (address);
              function feeToSetter() external view returns (address);
              function routerSetter() external view returns (address);
              function router() external view returns (address);
              function getPair(address tokenA, address tokenB) external view returns (address pair);
              function allPairs(uint) external view returns (address pair);
              function allPairsLength() external view returns (uint);
              function createPair(address tokenA, address tokenB) external returns (address pair);
              function setFeeTo(address) external;
              function setFeeToSetter(address) external;
              function setRouterSetter(address) external;
              function setRouter(address) external;
          }
          interface IUniswapV2Callee {
              function uniswapV2Call(address sender, uint amount0, uint amount1, bytes calldata data) external;
          }
          library SafeMath {
              function add(uint x, uint y) internal pure returns (uint z) {
                  require((z = x + y) >= x, 'ds-math-add-overflow');
              }
              function sub(uint x, uint y) internal pure returns (uint z) {
                  require((z = x - y) <= x, 'ds-math-sub-underflow');
              }
              function mul(uint x, uint y) internal pure returns (uint z) {
                  require(y == 0 || (z = x * y) / y == x, 'ds-math-mul-overflow');
              }
          }
          library Math {
              function min(uint x, uint y) internal pure returns (uint z) {
                  z = x < y ? x : y;
              }
              // babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method)
              function sqrt(uint y) internal pure returns (uint z) {
                  if (y > 3) {
                      z = y;
                      uint x = y / 2 + 1;
                      while (x < z) {
                          z = x;
                          x = (y / x + x) / 2;
                      }
                  } else if (y != 0) {
                      z = 1;
                  }
              }
          }
          library UQ112x112 {
              uint224 constant Q112 = 2**112;
              // encode a uint112 as a UQ112x112
              function encode(uint112 y) internal pure returns (uint224 z) {
                  z = uint224(y) * Q112; // never overflows
              }
              // divide a UQ112x112 by a uint112, returning a UQ112x112
              function uqdiv(uint224 x, uint112 y) internal pure returns (uint224 z) {
                  z = x / uint224(y);
              }
          }
          contract EtherVistaERC20 is IEtherVistaERC20 {
              using SafeMath for uint;
              string public constant name = 'VISTA';
              string public constant symbol = 'VISTA-LP';
              uint8 public constant decimals = 18;
              uint public totalSupply;
              address public factory;
              mapping(address => uint) public balanceOf;
              mapping(address => mapping(address => uint)) public allowance;
              bytes32 public DOMAIN_SEPARATOR;
              // keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
              bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
              mapping(address => uint) public nonces;
              event Approval(address indexed owner, address indexed spender, uint value);
              event Transfer(address indexed from, address indexed to, uint value);
              constructor() public {
                  uint chainId;
                  assembly {
                      chainId := chainid
                  }
                  factory = msg.sender;
                  DOMAIN_SEPARATOR = keccak256(
                      abi.encode(
                          keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)'),
                          keccak256(bytes(name)),
                          keccak256(bytes('1')),
                          chainId,
                          address(this)
                      )
                  );
              }
              function _mint(address to, uint value) internal {
                  totalSupply = totalSupply.add(value);
                  balanceOf[to] = balanceOf[to].add(value);
                  emit Transfer(address(0), to, value);
              }
              function _burn(address from, uint value) internal {
                  balanceOf[from] = balanceOf[from].sub(value);
                  totalSupply = totalSupply.sub(value);
                  emit Transfer(from, address(0), value);
              }
              function _approve(address owner, address spender, uint value) private {
                  allowance[owner][spender] = value;
                  emit Approval(owner, spender, value);
              }
              function _transfer(address from, address to, uint value) private {
                  balanceOf[from] = balanceOf[from].sub(value);
                  balanceOf[to] = balanceOf[to].add(value);
                  emit Transfer(from, to, value);
              }
              function transfer(address to, uint value) external returns (bool) {
                  if (to != 0x000000000000000000000000000000000000dEaD) {
                  require(msg.sender == IEtherVistaFactory(factory).router(), 'EtherVistaPair: FORBIDDEN');
                  }
                  _transfer(msg.sender, to, value);
                  return true;
              }
              function approve(address spender, uint value) external returns (bool) {
                  require(spender == IEtherVistaFactory(factory).router(), 'EtherVistaPair: FORBIDDEN');
                  _approve(msg.sender, spender, value);
                  return true;
              }
              function transferFrom(address from, address to, uint value) external returns (bool) {
                  require(msg.sender == IEtherVistaFactory(factory).router(), 'EtherVistaPair: FORBIDDEN');
                  if (allowance[from][msg.sender] != uint(-1)) {
                      allowance[from][msg.sender] = allowance[from][msg.sender].sub(value);
                  }
                  _transfer(from, to, value);
                  return true;
              }
              function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external {
                  require(deadline >= block.timestamp, 'EtherVista: EXPIRED');
                  require(spender == IEtherVistaFactory(factory).router(), 'EtherVistaPair: FORBIDDEN');
                  bytes32 digest = keccak256(
                      abi.encodePacked(
                          '\\x19\\x01',
                          DOMAIN_SEPARATOR,
                          keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline))
                      )
                  );
                  address recoveredAddress = ecrecover(digest, v, r, s);
                  require(recoveredAddress != address(0) && recoveredAddress == owner, 'EtherVista: INVALID_SIGNATURE');
                  _approve(owner, spender, value);
              }
          }
          contract EtherVistaPair is IEtherVistaPair, EtherVistaERC20 {
              using SafeMath  for uint;
              using UQ112x112 for uint224;
              uint public constant MINIMUM_LIQUIDITY = 10**3;
              uint256 private bigNumber = 10**20; //prevents liqFee/totalSupply from rounding to 0.
              bytes4 private constant SELECTOR = bytes4(keccak256(bytes('transfer(address,uint256)')));
              address public factory;
              address public token0;
              address public token1;
              uint8 public buyLpFee;
              uint8 public sellLpFee;
              uint8 public buyProtocolFee; 
              uint8 public sellProtocolFee;
              uint8 public buyTotalFee;
              uint8 public sellTotalFee;
              uint256 public startTime_fees = 0; 
              uint8 public future_buyLpFee;
              uint8 public future_sellLpFee;
              uint8 public future_buyProtocolFee;
              uint8 public future_sellProtocolFee ;
              uint256 public totalCollected;
              uint public poolBalance;
              uint256 public startTime_protocol = 0;
              address public protocol;
              address public future_protocol;
              address public creator; 
              uint256 public creation_time; 
              string public websiteUrl = "Null";
              string public imageUrl = "Null"; //IPFS link
              string public tokenDescription = "Null";
              string public chatUrl = "Null";
              string public socialUrl = "Null";
              struct Provider {
                  uint256 lp;
                  uint256 euler0;
              }
              uint256[] public euler; 
              mapping(address => Provider) public Providers;
              uint112 private reserve0;           // uses single storage slot, accessible via getReserves
              uint112 private reserve1;           // uses single storage slot, accessible via getReserves
              uint32  private blockTimestampLast; // uses single storage slot, accessible via getReserves
              uint public price0CumulativeLast;
              uint public price1CumulativeLast;
              uint public kLast; // reserve0 * reserve1, as of immediately after the most recent liquidity event
              uint private unlocked = 1;
              modifier lock() {
                  require(unlocked == 1, 'EtherVista: LOCKED');
                  unlocked = 0;
                  _;
                  unlocked = 1;
              }
              //called everytime a swap is performed
              function() external payable {
                  require(msg.sender == IEtherVistaFactory(factory).router(), 'EtherVistaPair: FORBIDDEN');
                  poolBalance += msg.value;
                  totalCollected += msg.value;
                  updateEuler(msg.value);
              }
              //updates the euler constant - occurs everytime a swap is performed
              function updateEuler(uint256 liqFee) internal { 
                  if (euler.length == 0){
                      euler.push((liqFee*bigNumber)/totalSupply);
                  }else{
                      euler.push(euler[euler.length - 1] + (liqFee*bigNumber)/totalSupply); 
                  }
              }
              //called everytime liquidity is added/removed by the user
              function updateProvider(address user) external  { 
                  require(msg.sender == IEtherVistaFactory(factory).router(), 'EtherVistaPair: FORBIDDEN');
                  if (euler.length == 0){
                      Providers[user] = Provider(balanceOf[user], 0); 
                  }else{
                      Providers[user] = Provider(balanceOf[user], euler[euler.length - 1]);
                  }
              }
              function claimShare() public lock {
                  require(euler.length > 0, 'EtherVistaPair: Nothing to Claim');
                  uint256 share = (Providers[msg.sender].lp * (euler[euler.length - 1] - Providers[msg.sender].euler0))/bigNumber;
                  Providers[msg.sender] = Provider(balanceOf[msg.sender], euler[euler.length - 1]);
                  poolBalance -= share;
                  (bool sent,) = msg.sender.call.value(share)("");
                  require(sent, "Failed to send Ether"); 
              }
              
              function viewShare() public view returns (uint256 share) {
                  if (euler.length == 0){
                      return 0;
                  }else{
                      return Providers[msg.sender].lp * (euler[euler.length - 1] - Providers[msg.sender].euler0)/bigNumber;
                  }
              }
              function updateFees(uint8 buyLpFuture, uint8 sellLpFuture, uint8 buyProtocolFuture, uint8 sellProtocolFuture) external {
                  require(msg.sender == creator);
                  startTime_fees = block.timestamp;
                  future_buyLpFee = buyLpFuture;  
                  future_sellLpFee = sellLpFuture;  
                  future_buyProtocolFee = buyProtocolFuture;
                  future_sellProtocolFee = sellProtocolFuture;
              }
              function setFees() external {
                  require(startTime_fees != 0);
                  require(msg.sender == creator && block.timestamp - startTime_fees >= 3 days);
                  buyLpFee = future_buyLpFee;
                  sellLpFee = future_sellLpFee;
                  buyProtocolFee = future_buyProtocolFee;
                  sellProtocolFee = future_sellProtocolFee;
                  buyTotalFee =  future_buyLpFee + future_buyProtocolFee + 1;
                  sellTotalFee = future_sellLpFee + future_sellProtocolFee + 1;
              }
              function updateProtocol(address protocolFuture) external {
                  require(msg.sender == creator);
                  startTime_protocol = block.timestamp;
                  future_protocol = protocolFuture;
              }
              function setProtocol() external {
                  require(startTime_protocol != 0);
                  require(msg.sender == creator && block.timestamp - startTime_protocol >= 3 days);
                  protocol = future_protocol;
              }
              function payableProtocol() external view returns (address payable) {
                  return address(uint160(protocol));
              }
              function setMetadata(string calldata website, string calldata image, string calldata description, string calldata chat, string calldata social) external {
                  require(msg.sender == creator);
                  websiteUrl = website;
                  imageUrl = image;
                  tokenDescription = description;
                  chatUrl = chat;
                  socialUrl = social;
              }
              function fetchMetadata() public view returns(string memory, string memory, string memory, string memory, string memory) {
                  return (websiteUrl, imageUrl, tokenDescription, chatUrl, socialUrl);
              }
              function renounce() external {
                  require(msg.sender == creator);
                  creator = 0x000000000000000000000000000000000000dEaD;
              }
              function getReserves() public view returns (uint112 _reserve0, uint112 _reserve1, uint32 _blockTimestampLast) {
                  _reserve0 = reserve0;
                  _reserve1 = reserve1;
                  _blockTimestampLast = blockTimestampLast;
              }
              function _safeTransfer(address token, address to, uint value) private {
                  (bool success, bytes memory data) = token.call(abi.encodeWithSelector(SELECTOR, to, value));
                  require(success && (data.length == 0 || abi.decode(data, (bool))), 'EtherVista: TRANSFER_FAILED');
              }
              event Mint(address indexed sender, uint amount0, uint amount1);
              event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
              event Swap(
                  address indexed sender,
                  uint amount0In,
                  uint amount1In,
                  uint amount0Out,
                  uint amount1Out,
                  address indexed to
              );
              event Sync(uint112 reserve0, uint112 reserve1);
              constructor() public {
                  factory = msg.sender;
              }
              // called once by the factory at time of deployment
              function initialize(address _token0, address _token1) external {
                  require(msg.sender == factory, 'EtherVistaPair: FORBIDDEN'); // sufficient check
                  token0 = _token0;
                  token1 = _token1;
              }
              // update reserves and, on the first call per block, price accumulators
              function _update(uint balance0, uint balance1, uint112 _reserve0, uint112 _reserve1) private {
                  require(balance0 <= uint112(-1) && balance1 <= uint112(-1), 'EtherVistaPair: OVERFLOW');
                  uint32 blockTimestamp = uint32(block.timestamp % 2**32);
                  uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired
                  if (timeElapsed > 0 && _reserve0 != 0 && _reserve1 != 0) {
                      // * never overflows, and + overflow is desired
                      price0CumulativeLast += uint(UQ112x112.encode(_reserve1).uqdiv(_reserve0)) * timeElapsed;
                      price1CumulativeLast += uint(UQ112x112.encode(_reserve0).uqdiv(_reserve1)) * timeElapsed;
                  }
                  reserve0 = uint112(balance0);
                  reserve1 = uint112(balance1);
                  blockTimestampLast = blockTimestamp;
                  emit Sync(reserve0, reserve1);
              }
              // if fee is on, mint liquidity equivalent to 1/6th of the growth in sqrt(k). This will never be on.
              function _mintFee(uint112 _reserve0, uint112 _reserve1) private returns (bool feeOn) {
                  address feeTo = IEtherVistaFactory(factory).feeTo();
                  feeOn = feeTo != address(0);
                  uint _kLast = kLast; // gas savings
                  if (feeOn) {
                      if (_kLast != 0) {
                          uint rootK = Math.sqrt(uint(_reserve0).mul(_reserve1));
                          uint rootKLast = Math.sqrt(_kLast);
                          if (rootK > rootKLast) {
                              uint numerator = totalSupply.mul(rootK.sub(rootKLast));
                              uint denominator = rootK.mul(5).add(rootKLast);
                              uint liquidity = numerator / denominator;
                              if (liquidity > 0) _mint(feeTo, liquidity);
                          }
                      }
                  } else if (_kLast != 0) {
                      kLast = 0;
                  }
              }
              // this low-level function should be called from a contract which performs important safety checks
              function first_mint(address to, uint8 buyLp, uint8 sellLp, uint8 buyProtocol, uint8 sellProtocol, address protocolAddress) external lock returns (uint liquidity) {
                  require(msg.sender == IEtherVistaFactory(factory).router(), 'EtherVistaPair: FORBIDDEN');
                  (uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
                  uint balance0 = IERC20(token0).balanceOf(address(this));
                  uint balance1 = IERC20(token1).balanceOf(address(this));
                  uint amount0 = balance0.sub(_reserve0);
                  uint amount1 = balance1.sub(_reserve1);
                  bool feeOn = _mintFee(_reserve0, _reserve1);
                  uint _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee
                  require(_totalSupply == 0);
                  liquidity = Math.sqrt(amount0.mul(amount1)).sub(MINIMUM_LIQUIDITY);
                  _mint(address(0), MINIMUM_LIQUIDITY); // permanently lock the first MINIMUM_LIQUIDITY tokens
                  creator = to;
                  creation_time = block.timestamp;
                  protocol = protocolAddress;
                  buyLpFee = buyLp;
                  sellLpFee = sellLp;
                  buyProtocolFee = buyProtocol;
                  sellProtocolFee = sellProtocol;
                  buyTotalFee =  buyLp + buyProtocol + 1;
                  sellTotalFee = sellLp + sellProtocol + 1;
                  
                  require(liquidity > 0, 'EtherVistaPair: INSUFFICIENT_LIQUIDITY_MINTED');
                  _mint(to, liquidity);
                  _update(balance0, balance1, _reserve0, _reserve1);
                  if (feeOn) kLast = uint(reserve0).mul(reserve1); // reserve0 and reserve1 are up-to-date
                  emit Mint(msg.sender, amount0, amount1);
              }
              // this low-level function should be called from a contract which performs important safety checks
              function mint(address to) external lock returns (uint liquidity) {
                  require(msg.sender == IEtherVistaFactory(factory).router(), 'EtherVistaPair: FORBIDDEN');
                  (uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
                  uint balance0 = IERC20(token0).balanceOf(address(this));
                  uint balance1 = IERC20(token1).balanceOf(address(this));
                  uint amount0 = balance0.sub(_reserve0);
                  uint amount1 = balance1.sub(_reserve1);
                  bool feeOn = _mintFee(_reserve0, _reserve1);
                  uint _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee
                  if (_totalSupply == 0) {
                      revert('Use first_mint instead');
                  } else {
                      liquidity = Math.min(amount0.mul(_totalSupply) / _reserve0, amount1.mul(_totalSupply) / _reserve1);
                  }
                  require(liquidity > 0, 'EtherVistaPair: INSUFFICIENT_LIQUIDITY_MINTED');
                  _mint(to, liquidity);
                  _update(balance0, balance1, _reserve0, _reserve1);
                  if (feeOn) kLast = uint(reserve0).mul(reserve1); // reserve0 and reserve1 are up-to-date
                  emit Mint(msg.sender, amount0, amount1);
              }
              // this low-level function should be called from a contract which performs important safety checks
              function burn(address to) external lock returns (uint amount0, uint amount1) {
                  require(msg.sender == IEtherVistaFactory(factory).router(), 'EtherVistaPair: FORBIDDEN');   
                  require(block.timestamp - creation_time >= 5 days, 'EtherVistaPair: FORBIDDEN RUGPULL');
                  (uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
                  address _token0 = token0;                                // gas savings
                  address _token1 = token1;                                // gas savings
                  uint balance0 = IERC20(_token0).balanceOf(address(this));
                  uint balance1 = IERC20(_token1).balanceOf(address(this));
                  uint liquidity = balanceOf[address(this)];
                  bool feeOn = _mintFee(_reserve0, _reserve1);
                  uint _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee
                  amount0 = liquidity.mul(balance0) / _totalSupply; // using balances ensures pro-rata distribution
                  amount1 = liquidity.mul(balance1) / _totalSupply; // using balances ensures pro-rata distribution
                  require(amount0 > 0 && amount1 > 0, 'EtherVistaPair: INSUFFICIENT_LIQUIDITY_BURNED');
                  _burn(address(this), liquidity);
                  _safeTransfer(_token0, to, amount0);
                  _safeTransfer(_token1, to, amount1);
                  balance0 = IERC20(_token0).balanceOf(address(this));
                  balance1 = IERC20(_token1).balanceOf(address(this));
                  _update(balance0, balance1, _reserve0, _reserve1);
                  if (feeOn) kLast = uint(reserve0).mul(reserve1); // reserve0 and reserve1 are up-to-date
                  emit Burn(msg.sender, amount0, amount1, to);
              }
              // this low-level function should be called from a contract which performs important safety checks
              function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external lock {
                  require(msg.sender == IEtherVistaFactory(factory).router(), 'EtherVistaPair: FORBIDDEN');
                  require(amount0Out > 0 || amount1Out > 0, 'EtherVistaPair: INSUFFICIENT_OUTPUT_AMOUNT');
                  (uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
                  require(amount0Out < _reserve0 && amount1Out < _reserve1, 'EtherVista: INSUFFICIENT_LIQUIDITY');
                  uint balance0;
                  uint balance1;
                  { // scope for _token{0,1}, avoids stack too deep errors
                  address _token0 = token0;
                  address _token1 = token1;
                  require(to != _token0 && to != _token1, 'EtherVistaPair: INVALID_TO');
                  if (amount0Out > 0) _safeTransfer(_token0, to, amount0Out); // optimistically transfer tokens
                  if (amount1Out > 0) _safeTransfer(_token1, to, amount1Out); // optimistically transfer tokens
                  if (data.length > 0) IUniswapV2Callee(to).uniswapV2Call(msg.sender, amount0Out, amount1Out, data);
                  balance0 = IERC20(_token0).balanceOf(address(this));
                  balance1 = IERC20(_token1).balanceOf(address(this));
                  }
                  uint amount0In = balance0 > _reserve0 - amount0Out ? balance0 - (_reserve0 - amount0Out) : 0;
                  uint amount1In = balance1 > _reserve1 - amount1Out ? balance1 - (_reserve1 - amount1Out) : 0;
                  require(amount0In > 0 || amount1In > 0, 'EtherVista: INSUFFICIENT_INPUT_AMOUNT');
                  { 
                  require(balance0 * balance1 >= reserve0 * reserve1, "K");
                  }
                  _update(balance0, balance1, _reserve0, _reserve1);
                  emit Swap(msg.sender, amount0In, amount1In, amount0Out, amount1Out, to);
              }
              // force balances to match reserves
              function skim(address to) external lock {
                  address _token0 = token0; // gas savings
                  address _token1 = token1; // gas savings
                  _safeTransfer(_token0, to, IERC20(_token0).balanceOf(address(this)).sub(reserve0));
                  _safeTransfer(_token1, to, IERC20(_token1).balanceOf(address(this)).sub(reserve1));
              }
              // force reserves to match balances
              function sync() external lock {
                  _update(IERC20(token0).balanceOf(address(this)), IERC20(token1).balanceOf(address(this)), reserve0, reserve1);
              }
          }