'use strict';

var _defineProperty = require('@babel/runtime/helpers/defineProperty');
var _asyncToGenerator = require('@babel/runtime/helpers/asyncToGenerator');
var _regeneratorRuntime = require('@babel/runtime/regenerator');
var smartOrderRouter = require('@brydge-network/smart-order-router');
var sdkCore = require('@uniswap/sdk-core');
var index = require('./index-5a435af0.cjs');
var JSBI = require('jsbi');
var _slicedToArray = require('@babel/runtime/helpers/slicedToArray');
var _toConsumableArray = require('@babel/runtime/helpers/toConsumableArray');
var _classCallCheck = require('@babel/runtime/helpers/classCallCheck');
var _createClass = require('@babel/runtime/helpers/createClass');
var _inherits = require('@babel/runtime/helpers/inherits');
var _possibleConstructorReturn = require('@babel/runtime/helpers/possibleConstructorReturn');
var _getPrototypeOf = require('@babel/runtime/helpers/getPrototypeOf');
var address = require('@ethersproject/address');
var solidity = require('@ethersproject/solidity');
var v2Sdk = require('@uniswap/v2-sdk');
var _assertThisInitialized = require('@babel/runtime/helpers/assertThisInitialized');
var routerSdk = require('@uniswap/router-sdk');
require('react');
require('buffer');
require('jotai');
require('jotai/utils');
require('jotai/immer');
require('tiny-invariant');
require('@ethersproject/units');
require('@ethersproject/abi');
require('@ethersproject/providers');
require('@web3-react/core');
require('@web3-react/eip1193');
require('@web3-react/empty');
require('@web3-react/url');
require('@web3-react/types');
require('@uniswap/redux-multicall');
require('@ethersproject/constants');
require('@ethersproject/contracts');
require('@babel/runtime/helpers/typeof');
require('@reduxjs/toolkit/query/react');
require('@reduxjs/toolkit');
require('qs');
require('@uniswap/v3-sdk');
require('ethers');
require('@babel/runtime/helpers/get');
require('@brydge-network/token-list');
require('@ethersproject/hash');
require('@brydge-network/utils');
require('firebase/database');
require('firebase/app');
require('cids');
require('multicodec');
require('multihashes');
require('@babel/runtime/helpers/wrapNativeSuper');
require('@babel/runtime/helpers/taggedTemplateLiteral');
require('styled-components');
require('react-feather');
require('rebass');
require('wicg-inert');
require('react-dom');
require('polished');
require('wcag-contrast');
require('@babel/runtime/helpers/extends');
require('@babel/runtime/helpers/objectWithoutProperties');
require('popper-max-size-modifier');
require('react-popper');
require('node-vibrant/lib/bundle.js');
require('setimmediate');
require('react-virtualized-auto-sizer');
require('react-window');
require('@ethersproject/bytes');
require('@ethersproject/bignumber');
require('axios');
require('make-plural/plurals');
require('react-redux');
require('redux');

function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }

var _defineProperty__default = /*#__PURE__*/_interopDefaultLegacy(_defineProperty);
var _asyncToGenerator__default = /*#__PURE__*/_interopDefaultLegacy(_asyncToGenerator);
var _regeneratorRuntime__default = /*#__PURE__*/_interopDefaultLegacy(_regeneratorRuntime);
var JSBI__default = /*#__PURE__*/_interopDefaultLegacy(JSBI);
var _slicedToArray__default = /*#__PURE__*/_interopDefaultLegacy(_slicedToArray);
var _toConsumableArray__default = /*#__PURE__*/_interopDefaultLegacy(_toConsumableArray);
var _classCallCheck__default = /*#__PURE__*/_interopDefaultLegacy(_classCallCheck);
var _createClass__default = /*#__PURE__*/_interopDefaultLegacy(_createClass);
var _inherits__default = /*#__PURE__*/_interopDefaultLegacy(_inherits);
var _possibleConstructorReturn__default = /*#__PURE__*/_interopDefaultLegacy(_possibleConstructorReturn);
var _getPrototypeOf__default = /*#__PURE__*/_interopDefaultLegacy(_getPrototypeOf);
var _assertThisInitialized__default = /*#__PURE__*/_interopDefaultLegacy(_assertThisInitialized);

function _createSuper$3(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$3(); return function _createSuperInternal() { var Super = _getPrototypeOf__default["default"](Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf__default["default"](this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn__default["default"](this, result); }; }
function _isNativeReflectConstruct$3() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
var FACTORY_ADDRESS$1 = '0x5757371414417b8C6CAad45bAeF941aBc7d3Ab32';
var INIT_CODE_HASH$1 = '0x96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f';
var computePairAddress$1 = function computePairAddress(_ref) {
  var factoryAddress = _ref.factoryAddress,
    tokenA = _ref.tokenA,
    tokenB = _ref.tokenB;
  var _ref2 = tokenA.sortsBefore(tokenB) ? [tokenA, tokenB] : [tokenB, tokenA],
    _ref3 = _slicedToArray__default["default"](_ref2, 2),
    token0 = _ref3[0],
    token1 = _ref3[1];
  return address.getCreate2Address(factoryAddress, solidity.keccak256(['bytes'], [solidity.pack(['address', 'address'], [token0.address, token1.address])]), INIT_CODE_HASH$1);
};
var QuickswapPair = /*#__PURE__*/function (_UniswapPair) {
  _inherits__default["default"](QuickswapPair, _UniswapPair);
  var _super = _createSuper$3(QuickswapPair);
  function QuickswapPair() {
    _classCallCheck__default["default"](this, QuickswapPair);
    return _super.apply(this, arguments);
  }
  _createClass__default["default"](QuickswapPair, null, [{
    key: "getAddress",
    value: function getAddress(tokenA, tokenB) {
      return computePairAddress$1({
        factoryAddress: FACTORY_ADDRESS$1,
        tokenA: tokenA,
        tokenB: tokenB
      });
    }
  }]);
  return QuickswapPair;
}(v2Sdk.Pair);

/**
 * Provider that does not get data from an external source and instead returns
 * a hardcoded list of Subgraph pools.
 *
 * Since the pools are hardcoded, the liquidity/price values are dummies and should not
 * be depended on.
 *
 * Useful for instances where other data sources are unavailable. E.g. subgraph not available.
 *
 * @export
 * @class StaticV2SubgraphProvider
 */
var QuickswapStaticV2SubgraphProvider = /*#__PURE__*/function () {
  function QuickswapStaticV2SubgraphProvider(chainId) {
    _classCallCheck__default["default"](this, QuickswapStaticV2SubgraphProvider);
    this.chainId = chainId;
  }
  _createClass__default["default"](QuickswapStaticV2SubgraphProvider, [{
    key: "getPools",
    value: function () {
      var _getPools = _asyncToGenerator__default["default"]( /*#__PURE__*/_regeneratorRuntime__default["default"].mark(function _callee(tokenIn, tokenOut) {
        var bases, basePairs, pairs, poolAddressSet, subgraphPools;
        return _regeneratorRuntime__default["default"].wrap(function _callee$(_context) {
          while (1) {
            switch (_context.prev = _context.next) {
              case 0:
                bases = index.BASES_TO_CHECK_TRADES_AGAINST[this.chainId];
                if (bases) {
                  _context.next = 3;
                  break;
                }
                return _context.abrupt("return", []);
              case 3:
                basePairs = bases.flatMap(function (base) {
                  return bases.map(function (otherBase) {
                    return [base, otherBase];
                  });
                });
                if (tokenIn && tokenOut) {
                  basePairs.push.apply(basePairs, [[tokenIn, tokenOut]].concat(_toConsumableArray__default["default"](bases.map(function (base) {
                    return [tokenIn, base];
                  })), _toConsumableArray__default["default"](bases.map(function (base) {
                    return [tokenOut, base];
                  }))));
                }
                pairs = basePairs.filter(function (tokens) {
                  return Boolean(tokens[0] && tokens[1]);
                }).filter(function (_ref) {
                  var _ref2 = _slicedToArray__default["default"](_ref, 2),
                    tokenA = _ref2[0],
                    tokenB = _ref2[1];
                  return tokenA.address !== tokenB.address && !tokenA.equals(tokenB);
                });
                poolAddressSet = new Set();
                subgraphPools = pairs.map(function (_ref3) {
                  var _ref4 = _slicedToArray__default["default"](_ref3, 2),
                    tokenA = _ref4[0],
                    tokenB = _ref4[1];
                  var poolAddress = QuickswapPair.getAddress(tokenA, tokenB);
                  if (poolAddressSet.has(poolAddress)) {
                    return undefined;
                  }
                  poolAddressSet.add(poolAddress);
                  var _ref5 = tokenA.sortsBefore(tokenB) ? [tokenA, tokenB] : [tokenB, tokenA],
                    _ref6 = _slicedToArray__default["default"](_ref5, 2),
                    token0 = _ref6[0],
                    token1 = _ref6[1];
                  return {
                    id: poolAddress,
                    liquidity: '100',
                    token0: {
                      id: token0.address
                    },
                    token1: {
                      id: token1.address
                    },
                    supply: 100,
                    reserve: 100,
                    reserveUSD: 100
                  };
                }).filter(function (v) {
                  return !!v;
                });
                return _context.abrupt("return", subgraphPools);
              case 9:
              case "end":
                return _context.stop();
            }
          }
        }, _callee, this);
      }));
      function getPools(_x, _x2) {
        return _getPools.apply(this, arguments);
      }
      return getPools;
    }()
  }]);
  return QuickswapStaticV2SubgraphProvider;
}();

function _createSuper$2(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$2(); return function _createSuperInternal() { var Super = _getPrototypeOf__default["default"](Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf__default["default"](this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn__default["default"](this, result); }; }
function _isNativeReflectConstruct$2() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
var QuickswapV2PoolProvider = /*#__PURE__*/function (_UniswapV2PoolProvide) {
  _inherits__default["default"](QuickswapV2PoolProvider, _UniswapV2PoolProvide);
  var _super = _createSuper$2(QuickswapV2PoolProvider);
  function QuickswapV2PoolProvider() {
    var _this;
    _classCallCheck__default["default"](this, QuickswapV2PoolProvider);
    for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }
    _this = _super.call.apply(_super, [this].concat(args));
    _defineProperty__default["default"](_assertThisInitialized__default["default"](_this), "POOL_ADDRESS_CACHE_2", {});
    return _this;
  }
  _createClass__default["default"](QuickswapV2PoolProvider, [{
    key: "getPoolAddress",
    value: function getPoolAddress(tokenA, tokenB) {
      var _ref = tokenA.sortsBefore(tokenB) ? [tokenA, tokenB] : [tokenB, tokenA],
        _ref2 = _slicedToArray__default["default"](_ref, 2),
        token0 = _ref2[0],
        token1 = _ref2[1];
      var cacheKey = "".concat(this.chainId, "/").concat(token0.address, "/").concat(token1.address);
      var cachedAddress = this.POOL_ADDRESS_CACHE_2[cacheKey];
      if (cachedAddress) {
        return {
          poolAddress: cachedAddress,
          token0: token0,
          token1: token1
        };
      }
      var poolAddress = QuickswapPair.getAddress(token0, token1);
      this.POOL_ADDRESS_CACHE_2[cacheKey] = poolAddress;
      return {
        poolAddress: poolAddress,
        token0: token0,
        token1: token1
      };
    }
  }]);
  return QuickswapV2PoolProvider;
}(smartOrderRouter.V2PoolProvider);

function _createSuper$1(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$1(); return function _createSuperInternal() { var Super = _getPrototypeOf__default["default"](Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf__default["default"](this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn__default["default"](this, result); }; }
function _isNativeReflectConstruct$1() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
var FACTORY_ADDRESS = '0x9Ad6C38BE94206cA50bb0d90783181662f0Cfa10';
var INIT_CODE_HASH = '0x0bbca9af0511ad1a1da383135cf3a8d2ac620e549ef9f6ae3a4c33c2fed0af91';
var computePairAddress = function computePairAddress(_ref) {
  var factoryAddress = _ref.factoryAddress,
    tokenA = _ref.tokenA,
    tokenB = _ref.tokenB;
  var _ref2 = tokenA.sortsBefore(tokenB) ? [tokenA, tokenB] : [tokenB, tokenA],
    _ref3 = _slicedToArray__default["default"](_ref2, 2),
    token0 = _ref3[0],
    token1 = _ref3[1];
  return address.getCreate2Address(factoryAddress, solidity.keccak256(['bytes'], [solidity.pack(['address', 'address'], [token0.address, token1.address])]), INIT_CODE_HASH);
};
var TraderJoePair = /*#__PURE__*/function (_UniswapPair) {
  _inherits__default["default"](TraderJoePair, _UniswapPair);
  var _super = _createSuper$1(TraderJoePair);
  function TraderJoePair() {
    _classCallCheck__default["default"](this, TraderJoePair);
    return _super.apply(this, arguments);
  }
  _createClass__default["default"](TraderJoePair, null, [{
    key: "getAddress",
    value: function getAddress(tokenA, tokenB) {
      return computePairAddress({
        factoryAddress: FACTORY_ADDRESS,
        tokenA: tokenA,
        tokenB: tokenB
      });
    }
  }]);
  return TraderJoePair;
}(v2Sdk.Pair);

/**
 * Provider that does not get data from an external source and instead returns
 * a hardcoded list of Subgraph pools.
 *
 * Since the pools are hardcoded, the liquidity/price values are dummies and should not
 * be depended on.
 *
 * Useful for instances where other data sources are unavailable. E.g. subgraph not available.
 *
 * @export
 * @class StaticV2SubgraphProvider
 */
var TraderJoeStaticV2SubgraphProvider = /*#__PURE__*/function () {
  function TraderJoeStaticV2SubgraphProvider(chainId) {
    _classCallCheck__default["default"](this, TraderJoeStaticV2SubgraphProvider);
    this.chainId = chainId;
  }
  _createClass__default["default"](TraderJoeStaticV2SubgraphProvider, [{
    key: "getPools",
    value: function () {
      var _getPools = _asyncToGenerator__default["default"]( /*#__PURE__*/_regeneratorRuntime__default["default"].mark(function _callee(tokenIn, tokenOut) {
        var bases, basePairs, pairs, poolAddressSet, subgraphPools;
        return _regeneratorRuntime__default["default"].wrap(function _callee$(_context) {
          while (1) {
            switch (_context.prev = _context.next) {
              case 0:
                bases = index.BASES_TO_CHECK_TRADES_AGAINST[this.chainId];
                if (bases) {
                  _context.next = 3;
                  break;
                }
                return _context.abrupt("return", []);
              case 3:
                basePairs = bases.flatMap(function (base) {
                  return bases.map(function (otherBase) {
                    return [base, otherBase];
                  });
                });
                if (tokenIn && tokenOut) {
                  basePairs.push.apply(basePairs, [[tokenIn, tokenOut]].concat(_toConsumableArray__default["default"](bases.map(function (base) {
                    return [tokenIn, base];
                  })), _toConsumableArray__default["default"](bases.map(function (base) {
                    return [tokenOut, base];
                  }))));
                }
                pairs = basePairs.filter(function (tokens) {
                  return Boolean(tokens[0] && tokens[1]);
                }).filter(function (_ref) {
                  var _ref2 = _slicedToArray__default["default"](_ref, 2),
                    tokenA = _ref2[0],
                    tokenB = _ref2[1];
                  return tokenA.address !== tokenB.address && !tokenA.equals(tokenB);
                });
                poolAddressSet = new Set();
                subgraphPools = pairs.map(function (_ref3) {
                  var _ref4 = _slicedToArray__default["default"](_ref3, 2),
                    tokenA = _ref4[0],
                    tokenB = _ref4[1];
                  var poolAddress = TraderJoePair.getAddress(tokenA, tokenB);
                  if (poolAddressSet.has(poolAddress)) {
                    return undefined;
                  }
                  poolAddressSet.add(poolAddress);
                  var _ref5 = tokenA.sortsBefore(tokenB) ? [tokenA, tokenB] : [tokenB, tokenA],
                    _ref6 = _slicedToArray__default["default"](_ref5, 2),
                    token0 = _ref6[0],
                    token1 = _ref6[1];
                  return {
                    id: poolAddress,
                    liquidity: '100',
                    token0: {
                      id: token0.address
                    },
                    token1: {
                      id: token1.address
                    },
                    supply: 100,
                    reserve: 100,
                    reserveUSD: 100
                  };
                }).filter(function (v) {
                  return !!v;
                });
                return _context.abrupt("return", subgraphPools);
              case 9:
              case "end":
                return _context.stop();
            }
          }
        }, _callee, this);
      }));
      function getPools(_x, _x2) {
        return _getPools.apply(this, arguments);
      }
      return getPools;
    }()
  }]);
  return TraderJoeStaticV2SubgraphProvider;
}();

function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf__default["default"](Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf__default["default"](this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn__default["default"](this, result); }; }
function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
var TraderJoeV2PoolProvider = /*#__PURE__*/function (_UniswapV2PoolProvide) {
  _inherits__default["default"](TraderJoeV2PoolProvider, _UniswapV2PoolProvide);
  var _super = _createSuper(TraderJoeV2PoolProvider);
  function TraderJoeV2PoolProvider() {
    var _this;
    _classCallCheck__default["default"](this, TraderJoeV2PoolProvider);
    for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }
    _this = _super.call.apply(_super, [this].concat(args));
    _defineProperty__default["default"](_assertThisInitialized__default["default"](_this), "POOL_ADDRESS_CACHE_2", {});
    return _this;
  }
  _createClass__default["default"](TraderJoeV2PoolProvider, [{
    key: "getPoolAddress",
    value: function getPoolAddress(tokenA, tokenB) {
      var _ref = tokenA.sortsBefore(tokenB) ? [tokenA, tokenB] : [tokenB, tokenA],
        _ref2 = _slicedToArray__default["default"](_ref, 2),
        token0 = _ref2[0],
        token1 = _ref2[1];
      var cacheKey = "".concat(this.chainId, "/").concat(token0.address, "/").concat(token1.address);
      var cachedAddress = this.POOL_ADDRESS_CACHE_2[cacheKey];
      if (cachedAddress) {
        return {
          poolAddress: cachedAddress,
          token0: token0,
          token1: token1
        };
      }
      var poolAddress = TraderJoePair.getAddress(token0, token1);
      this.POOL_ADDRESS_CACHE_2[cacheKey] = poolAddress;
      return {
        poolAddress: poolAddress,
        token0: token0,
        token1: token1
      };
    }
  }]);
  return TraderJoeV2PoolProvider;
}(smartOrderRouter.V2PoolProvider);

function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }

// from routing-api (https://github.com/Uniswap/routing-api/blob/main/lib/handlers/quote/quote.ts#L243-L311)
function transformSwapRouteToGetQuoteResult(_ref) {
  var quote = _ref.quote,
    quoteGasAdjusted = _ref.quoteGasAdjusted,
    route = _ref.route,
    routeString = _ref.routeString,
    estimatedGasUsed = _ref.estimatedGasUsed,
    estimatedGasUsedQuoteToken = _ref.estimatedGasUsedQuoteToken,
    estimatedGasUsedUSD = _ref.estimatedGasUsedUSD,
    gasPriceWei = _ref.gasPriceWei,
    methodParameters = _ref.methodParameters,
    blockNumber = _ref.blockNumber,
    _ref$trade = _ref.trade,
    tradeType = _ref$trade.tradeType,
    inputAmount = _ref$trade.inputAmount,
    outputAmount = _ref$trade.outputAmount;
  var routeResponse = [];
  var _iterator = _createForOfIteratorHelper(route),
    _step;
  try {
    for (_iterator.s(); !(_step = _iterator.n()).done;) {
      var subRoute = _step.value;
      var _amount = subRoute.amount,
        _quote = subRoute.quote,
        tokenPath = subRoute.tokenPath;
      if (subRoute.protocol === routerSdk.Protocol.V3) {
        var pools = subRoute.route.pools;
        var curRoute = [];
        for (var i = 0; i < pools.length; i++) {
          var nextPool = pools[i];
          var tokenIn = tokenPath[i];
          var tokenOut = tokenPath[i + 1];
          var edgeAmountIn = undefined;
          if (i === 0) {
            edgeAmountIn = index.isExactInput(tradeType) ? _amount.quotient.toString() : _quote.quotient.toString();
          }
          var edgeAmountOut = undefined;
          if (i === pools.length - 1) {
            edgeAmountOut = index.isExactInput(tradeType) ? _quote.quotient.toString() : _amount.quotient.toString();
          }
          curRoute.push({
            type: 'v3-pool',
            tokenIn: {
              chainId: tokenIn.chainId,
              decimals: tokenIn.decimals,
              address: tokenIn.address,
              symbol: tokenIn.symbol
            },
            tokenOut: {
              chainId: tokenOut.chainId,
              decimals: tokenOut.decimals,
              address: tokenOut.address,
              symbol: tokenOut.symbol
            },
            fee: nextPool.fee.toString(),
            liquidity: nextPool.liquidity.toString(),
            sqrtRatioX96: nextPool.sqrtRatioX96.toString(),
            tickCurrent: nextPool.tickCurrent.toString(),
            amountIn: edgeAmountIn,
            amountOut: edgeAmountOut
          });
        }
        routeResponse.push(curRoute);
      } else if (subRoute.protocol === routerSdk.Protocol.V2) {
        var _pools = subRoute.route.pairs;
        var _curRoute = [];
        for (var _i = 0; _i < _pools.length; _i++) {
          var _nextPool = _pools[_i];
          var _tokenIn = tokenPath[_i];
          var _tokenOut = tokenPath[_i + 1];
          var _edgeAmountIn = undefined;
          if (_i === 0) {
            _edgeAmountIn = index.isExactInput(tradeType) ? _amount.quotient.toString() : _quote.quotient.toString();
          }
          var _edgeAmountOut = undefined;
          if (_i === _pools.length - 1) {
            _edgeAmountOut = index.isExactInput(tradeType) ? _quote.quotient.toString() : _amount.quotient.toString();
          }
          var reserve0 = _nextPool.reserve0;
          var reserve1 = _nextPool.reserve1;
          _curRoute.push({
            type: 'v2-pool',
            tokenIn: {
              chainId: _tokenIn.chainId,
              decimals: _tokenIn.decimals,
              address: _tokenIn.address,
              symbol: _tokenIn.symbol
            },
            tokenOut: {
              chainId: _tokenOut.chainId,
              decimals: _tokenOut.decimals,
              address: _tokenOut.address,
              symbol: _tokenOut.symbol
            },
            reserve0: {
              token: {
                chainId: reserve0.currency.wrapped.chainId,
                decimals: reserve0.currency.wrapped.decimals,
                address: reserve0.currency.wrapped.address,
                symbol: reserve0.currency.wrapped.symbol
              },
              quotient: reserve0.quotient.toString()
            },
            reserve1: {
              token: {
                chainId: reserve1.currency.wrapped.chainId,
                decimals: reserve1.currency.wrapped.decimals,
                address: reserve1.currency.wrapped.address,
                symbol: reserve1.currency.wrapped.symbol
              },
              quotient: reserve1.quotient.toString()
            },
            amountIn: _edgeAmountIn,
            amountOut: _edgeAmountOut
          });
        }
        routeResponse.push(_curRoute);
      }
    }
  } catch (err) {
    _iterator.e(err);
  } finally {
    _iterator.f();
  }
  var amount = index.isExactInput(tradeType) ? inputAmount : outputAmount;
  return {
    methodParameters: methodParameters,
    blockNumber: blockNumber.toString(),
    amount: amount.quotient.toString(),
    amountDecimals: amount.toExact(),
    quote: quote.quotient.toString(),
    quoteDecimals: quote.toExact(),
    quoteGasAdjusted: quoteGasAdjusted.quotient.toString(),
    quoteGasAdjustedDecimals: quoteGasAdjusted.toExact(),
    gasUseEstimateQuote: estimatedGasUsedQuoteToken.quotient.toString(),
    gasUseEstimateQuoteDecimals: estimatedGasUsedQuoteToken.toExact(),
    gasUseEstimate: estimatedGasUsed.toString(),
    gasUseEstimateUSD: estimatedGasUsedUSD.toExact(),
    gasPriceWei: gasPriceWei.toString(),
    route: routeResponse,
    routeString: routeString
  };
}

function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty__default["default"](target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
var AUTO_ROUTER_SUPPORTED_CHAINS = Object.values(index.SupportedChainId).filter(function (chainId) {
  return Number.isInteger(chainId);
});
function isAutoRouterSupportedChain(chainId) {
  return !!(chainId && AUTO_ROUTER_SUPPORTED_CHAINS.includes(chainId));
}
/** A cache of AlphaRouters, which must be initialized to a specific chain/provider. */
var routersCache = new WeakMap();

// used to coerce the same chain id on two different enums to be retyped to each other
function coerceChainIdTypeToOther(chain) {
  return chain;
}
function getRouter(chainId, provider) {
  var routers = routersCache.get(provider) || {};
  var cached = routers[chainId];
  if (cached) {
    return cached;
  }
  var multicall2Provider;
  var v2PoolProvider;
  var v2QuoteProvider;
  var v2SubgraphProvider;
  var onChainQuoteProvider;
  if (chainId === smartOrderRouter.ChainId.POLYGON) {
    multicall2Provider = new smartOrderRouter.UniswapMulticallProvider(chainId, provider, 375000);
    v2PoolProvider = new QuickswapV2PoolProvider(chainId, multicall2Provider);
    v2QuoteProvider = new smartOrderRouter.V2QuoteProvider();
    v2SubgraphProvider = new QuickswapStaticV2SubgraphProvider(chainId);

    // V3 computes on-chain, so the quoter must have gas limits appropriate to the provider.
    // Most defaults are fine, but polygon needs a lower gas limit.
    // TODO(zzmp): Upstream to @brydge-network/smart-order-router, possibly making this easier to modify
    // (eg allowing configuration without an instance to avoid duplicating multicall2Provider).
    onChainQuoteProvider = new smartOrderRouter.OnChainQuoteProvider(chainId, provider, multicall2Provider, {
      retries: 2,
      minTimeout: 100,
      maxTimeout: 1000
    }, {
      multicallChunk: 10,
      gasLimitPerCall: 5000000,
      quoteMinSuccessRate: 0.1
    }, {
      gasLimitOverride: 5000000,
      multicallChunk: 5
    }, {
      gasLimitOverride: 6250000,
      multicallChunk: 4
    });
  } else if (chainId === smartOrderRouter.ChainId.AVALANCHE) {
    multicall2Provider = new smartOrderRouter.UniswapMulticallProvider(chainId, provider, 375000);
    v2PoolProvider = new TraderJoeV2PoolProvider(chainId, multicall2Provider);
    v2QuoteProvider = new smartOrderRouter.V2QuoteProvider();
    v2SubgraphProvider = new TraderJoeStaticV2SubgraphProvider(chainId);
  } else {
    // V2 is unsupported for chains other than mainnet.
    // TODO(zzmp): Upstream to @brydge-network/smart-order-router, exporting an enum of supported v2 chains for clarity.
    if (chainId !== smartOrderRouter.ChainId.MAINNET) {
      v2SubgraphProvider = new smartOrderRouter.StaticV2SubgraphProvider(chainId);
    }
  }
  var router = new smartOrderRouter.AlphaRouter({
    provider: provider,
    chainId: chainId,
    v2PoolProvider: v2PoolProvider,
    v2SubgraphProvider: v2SubgraphProvider,
    v2QuoteProvider: v2QuoteProvider,
    onChainQuoteProvider: onChainQuoteProvider,
    multicall2Provider: multicall2Provider
  });
  routers[chainId] = router;
  routersCache.set(provider, routers);
  return router;
}
function getQuote(_x, _x2, _x3) {
  return _getQuote.apply(this, arguments);
}
function _getQuote() {
  _getQuote = _asyncToGenerator__default["default"]( /*#__PURE__*/_regeneratorRuntime__default["default"].mark(function _callee(_ref, router, routerConfig) {
    var tradeType, tokenIn, tokenOut, amountRaw, currencyIn, currencyOut, baseCurrency, quoteCurrency, amount, route;
    return _regeneratorRuntime__default["default"].wrap(function _callee$(_context) {
      while (1) {
        switch (_context.prev = _context.next) {
          case 0:
            tradeType = _ref.tradeType, tokenIn = _ref.tokenIn, tokenOut = _ref.tokenOut, amountRaw = _ref.amount;
            currencyIn = new sdkCore.Token(tokenIn.chainId, tokenIn.address, tokenIn.decimals, tokenIn.symbol);
            currencyOut = new sdkCore.Token(tokenOut.chainId, tokenOut.address, tokenOut.decimals, tokenOut.symbol);
            baseCurrency = index.isExactInput(tradeType) ? currencyIn : currencyOut;
            quoteCurrency = index.isExactInput(tradeType) ? currencyOut : currencyIn;
            amount = sdkCore.CurrencyAmount.fromRawAmount(baseCurrency, JSBI__default["default"].BigInt(amountRaw !== null && amountRaw !== void 0 ? amountRaw : '1')); // a null amountRaw should initialize the route
            _context.next = 8;
            return router.route(amount, quoteCurrency, tradeType, /*swapConfig=*/undefined, routerConfig);
          case 8:
            route = _context.sent;
            if (!(amountRaw === null || !route)) {
              _context.next = 11;
              break;
            }
            return _context.abrupt("return", index.NO_ROUTE);
          case 11:
            return _context.abrupt("return", transformSwapRouteToGetQuoteResult(_objectSpread(_objectSpread({}, route), {}, {
              routeString: smartOrderRouter.routeAmountsToString(route.route)
            })));
          case 12:
          case "end":
            return _context.stop();
        }
      }
    }, _callee);
  }));
  return _getQuote.apply(this, arguments);
}
function getClientSideQuote(_x4, _x5) {
  return _getClientSideQuote.apply(this, arguments);
}
function _getClientSideQuote() {
  _getClientSideQuote = _asyncToGenerator__default["default"]( /*#__PURE__*/_regeneratorRuntime__default["default"].mark(function _callee2(_ref2, routerConfig) {
    var tokenInAddress, tokenInChainId, tokenInDecimals, tokenInSymbol, tokenOutAddress, tokenOutChainId, tokenOutDecimals, tokenOutSymbol, amount, tradeType, provider, router;
    return _regeneratorRuntime__default["default"].wrap(function _callee2$(_context2) {
      while (1) {
        switch (_context2.prev = _context2.next) {
          case 0:
            tokenInAddress = _ref2.tokenInAddress, tokenInChainId = _ref2.tokenInChainId, tokenInDecimals = _ref2.tokenInDecimals, tokenInSymbol = _ref2.tokenInSymbol, tokenOutAddress = _ref2.tokenOutAddress, tokenOutChainId = _ref2.tokenOutChainId, tokenOutDecimals = _ref2.tokenOutDecimals, tokenOutSymbol = _ref2.tokenOutSymbol, amount = _ref2.amount, tradeType = _ref2.tradeType, provider = _ref2.provider;
            if (isAutoRouterSupportedChain(tokenInChainId)) {
              _context2.next = 3;
              break;
            }
            throw new Error("Router does not support this token's chain (chainId: ".concat(tokenInChainId, ")."));
          case 3:
            router = getRouter(coerceChainIdTypeToOther(tokenInChainId), provider);
            return _context2.abrupt("return", getQuote({
              tradeType: tradeType,
              tokenIn: {
                address: tokenInAddress,
                chainId: tokenInChainId,
                decimals: tokenInDecimals,
                symbol: tokenInSymbol
              },
              tokenOut: {
                address: tokenOutAddress,
                chainId: tokenOutChainId,
                decimals: tokenOutDecimals,
                symbol: tokenOutSymbol
              },
              amount: amount
            }, router, routerConfig));
          case 5:
          case "end":
            return _context2.stop();
        }
      }
    }, _callee2);
  }));
  return _getClientSideQuote.apply(this, arguments);
}

exports.getClientSideQuote = getClientSideQuote;
