import _defineProperty from '@babel/runtime/helpers/defineProperty';
import _asyncToGenerator from '@babel/runtime/helpers/asyncToGenerator';
import _regeneratorRuntime from '@babel/runtime/regenerator';
import { V2PoolProvider, ChainId, UniswapMulticallProvider, V2QuoteProvider, OnChainQuoteProvider, StaticV2SubgraphProvider, AlphaRouter, routeAmountsToString } from '@brydge-network/smart-order-router';
import { Token, CurrencyAmount } from '@uniswap/sdk-core';
import { B as BASES_TO_CHECK_TRADES_AGAINST, i as isExactInput, S as SupportedChainId, N as NO_ROUTE } from './index-88c27e43.js';
import JSBI from 'jsbi';
import _slicedToArray from '@babel/runtime/helpers/slicedToArray';
import _toConsumableArray from '@babel/runtime/helpers/toConsumableArray';
import _classCallCheck from '@babel/runtime/helpers/classCallCheck';
import _createClass from '@babel/runtime/helpers/createClass';
import _inherits from '@babel/runtime/helpers/inherits';
import _possibleConstructorReturn from '@babel/runtime/helpers/possibleConstructorReturn';
import _getPrototypeOf from '@babel/runtime/helpers/getPrototypeOf';
import { getCreate2Address } from '@ethersproject/address';
import { keccak256, pack } from '@ethersproject/solidity';
import { Pair } from '@uniswap/v2-sdk';
import _assertThisInitialized from '@babel/runtime/helpers/assertThisInitialized';
import { Protocol } from '@uniswap/router-sdk';
import 'react';
import 'buffer';
import 'jotai';
import 'jotai/utils';
import 'jotai/immer';
import 'tiny-invariant';
import '@ethersproject/units';
import '@ethersproject/abi';
import '@ethersproject/providers';
import '@web3-react/core';
import '@web3-react/eip1193';
import '@web3-react/empty';
import '@web3-react/url';
import '@web3-react/types';
import '@uniswap/redux-multicall';
import '@ethersproject/constants';
import '@ethersproject/contracts';
import '@babel/runtime/helpers/typeof';
import '@reduxjs/toolkit/query/react';
import '@reduxjs/toolkit';
import 'qs';
import '@uniswap/v3-sdk';
import 'ethers';
import '@babel/runtime/helpers/get';
import '@brydge-network/token-list';
import '@ethersproject/hash';
import '@brydge-network/utils';
import 'firebase/database';
import 'firebase/app';
import 'cids';
import 'multicodec';
import 'multihashes';
import '@babel/runtime/helpers/wrapNativeSuper';
import '@babel/runtime/helpers/taggedTemplateLiteral';
import 'styled-components';
import 'react-feather';
import 'rebass';
import 'wicg-inert';
import 'react-dom';
import 'polished';
import 'wcag-contrast';
import '@babel/runtime/helpers/extends';
import '@babel/runtime/helpers/objectWithoutProperties';
import 'popper-max-size-modifier';
import 'react-popper';
import 'node-vibrant/lib/bundle.js';
import 'setimmediate';
import 'react-virtualized-auto-sizer';
import 'react-window';
import '@ethersproject/bytes';
import '@ethersproject/bignumber';
import 'axios';
import 'make-plural/plurals';
import 'react-redux';
import 'redux';

function _createSuper$3(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$3(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(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(_ref2, 2),
    token0 = _ref3[0],
    token1 = _ref3[1];
  return getCreate2Address(factoryAddress, keccak256(['bytes'], [pack(['address', 'address'], [token0.address, token1.address])]), INIT_CODE_HASH$1);
};
var QuickswapPair = /*#__PURE__*/function (_UniswapPair) {
  _inherits(QuickswapPair, _UniswapPair);
  var _super = _createSuper$3(QuickswapPair);
  function QuickswapPair() {
    _classCallCheck(this, QuickswapPair);
    return _super.apply(this, arguments);
  }
  _createClass(QuickswapPair, null, [{
    key: "getAddress",
    value: function getAddress(tokenA, tokenB) {
      return computePairAddress$1({
        factoryAddress: FACTORY_ADDRESS$1,
        tokenA: tokenA,
        tokenB: tokenB
      });
    }
  }]);
  return QuickswapPair;
}(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(this, QuickswapStaticV2SubgraphProvider);
    this.chainId = chainId;
  }
  _createClass(QuickswapStaticV2SubgraphProvider, [{
    key: "getPools",
    value: function () {
      var _getPools = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(tokenIn, tokenOut) {
        var bases, basePairs, pairs, poolAddressSet, subgraphPools;
        return _regeneratorRuntime.wrap(function _callee$(_context) {
          while (1) {
            switch (_context.prev = _context.next) {
              case 0:
                bases = 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(bases.map(function (base) {
                    return [tokenIn, base];
                  })), _toConsumableArray(bases.map(function (base) {
                    return [tokenOut, base];
                  }))));
                }
                pairs = basePairs.filter(function (tokens) {
                  return Boolean(tokens[0] && tokens[1]);
                }).filter(function (_ref) {
                  var _ref2 = _slicedToArray(_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(_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(_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(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(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(QuickswapV2PoolProvider, _UniswapV2PoolProvide);
  var _super = _createSuper$2(QuickswapV2PoolProvider);
  function QuickswapV2PoolProvider() {
    var _this;
    _classCallCheck(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(_assertThisInitialized(_this), "POOL_ADDRESS_CACHE_2", {});
    return _this;
  }
  _createClass(QuickswapV2PoolProvider, [{
    key: "getPoolAddress",
    value: function getPoolAddress(tokenA, tokenB) {
      var _ref = tokenA.sortsBefore(tokenB) ? [tokenA, tokenB] : [tokenB, tokenA],
        _ref2 = _slicedToArray(_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;
}(V2PoolProvider);

function _createSuper$1(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$1(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(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(_ref2, 2),
    token0 = _ref3[0],
    token1 = _ref3[1];
  return getCreate2Address(factoryAddress, keccak256(['bytes'], [pack(['address', 'address'], [token0.address, token1.address])]), INIT_CODE_HASH);
};
var TraderJoePair = /*#__PURE__*/function (_UniswapPair) {
  _inherits(TraderJoePair, _UniswapPair);
  var _super = _createSuper$1(TraderJoePair);
  function TraderJoePair() {
    _classCallCheck(this, TraderJoePair);
    return _super.apply(this, arguments);
  }
  _createClass(TraderJoePair, null, [{
    key: "getAddress",
    value: function getAddress(tokenA, tokenB) {
      return computePairAddress({
        factoryAddress: FACTORY_ADDRESS,
        tokenA: tokenA,
        tokenB: tokenB
      });
    }
  }]);
  return TraderJoePair;
}(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(this, TraderJoeStaticV2SubgraphProvider);
    this.chainId = chainId;
  }
  _createClass(TraderJoeStaticV2SubgraphProvider, [{
    key: "getPools",
    value: function () {
      var _getPools = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(tokenIn, tokenOut) {
        var bases, basePairs, pairs, poolAddressSet, subgraphPools;
        return _regeneratorRuntime.wrap(function _callee$(_context) {
          while (1) {
            switch (_context.prev = _context.next) {
              case 0:
                bases = 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(bases.map(function (base) {
                    return [tokenIn, base];
                  })), _toConsumableArray(bases.map(function (base) {
                    return [tokenOut, base];
                  }))));
                }
                pairs = basePairs.filter(function (tokens) {
                  return Boolean(tokens[0] && tokens[1]);
                }).filter(function (_ref) {
                  var _ref2 = _slicedToArray(_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(_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(_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(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(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(TraderJoeV2PoolProvider, _UniswapV2PoolProvide);
  var _super = _createSuper(TraderJoeV2PoolProvider);
  function TraderJoeV2PoolProvider() {
    var _this;
    _classCallCheck(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(_assertThisInitialized(_this), "POOL_ADDRESS_CACHE_2", {});
    return _this;
  }
  _createClass(TraderJoeV2PoolProvider, [{
    key: "getPoolAddress",
    value: function getPoolAddress(tokenA, tokenB) {
      var _ref = tokenA.sortsBefore(tokenB) ? [tokenA, tokenB] : [tokenB, tokenA],
        _ref2 = _slicedToArray(_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;
}(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 === 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 = isExactInput(tradeType) ? _amount.quotient.toString() : _quote.quotient.toString();
          }
          var edgeAmountOut = undefined;
          if (i === pools.length - 1) {
            edgeAmountOut = 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 === 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 = isExactInput(tradeType) ? _amount.quotient.toString() : _quote.quotient.toString();
          }
          var _edgeAmountOut = undefined;
          if (_i === _pools.length - 1) {
            _edgeAmountOut = 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 = 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(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(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 === ChainId.POLYGON) {
    multicall2Provider = new UniswapMulticallProvider(chainId, provider, 375000);
    v2PoolProvider = new QuickswapV2PoolProvider(chainId, multicall2Provider);
    v2QuoteProvider = new 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 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 === ChainId.AVALANCHE) {
    multicall2Provider = new UniswapMulticallProvider(chainId, provider, 375000);
    v2PoolProvider = new TraderJoeV2PoolProvider(chainId, multicall2Provider);
    v2QuoteProvider = new 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 !== ChainId.MAINNET) {
      v2SubgraphProvider = new StaticV2SubgraphProvider(chainId);
    }
  }
  var router = new 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( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(_ref, router, routerConfig) {
    var tradeType, tokenIn, tokenOut, amountRaw, currencyIn, currencyOut, baseCurrency, quoteCurrency, amount, route;
    return _regeneratorRuntime.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 Token(tokenIn.chainId, tokenIn.address, tokenIn.decimals, tokenIn.symbol);
            currencyOut = new Token(tokenOut.chainId, tokenOut.address, tokenOut.decimals, tokenOut.symbol);
            baseCurrency = isExactInput(tradeType) ? currencyIn : currencyOut;
            quoteCurrency = isExactInput(tradeType) ? currencyOut : currencyIn;
            amount = CurrencyAmount.fromRawAmount(baseCurrency, JSBI.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", NO_ROUTE);
          case 11:
            return _context.abrupt("return", transformSwapRouteToGetQuoteResult(_objectSpread(_objectSpread({}, route), {}, {
              routeString: 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( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2(_ref2, routerConfig) {
    var tokenInAddress, tokenInChainId, tokenInDecimals, tokenInSymbol, tokenOutAddress, tokenOutChainId, tokenOutDecimals, tokenOutSymbol, amount, tradeType, provider, router;
    return _regeneratorRuntime.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);
}

export { getClientSideQuote };
