"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.findTokensInfoFromDenoms = exports.findTokensHistoryFromDenoms = exports.findTokenInfoFromDenom = exports.findTokenHistoryFromDenom = exports.findTokenFromDenom = exports.findIbcTokensFromHashes = exports.findIbcTokenFromHash = void 0;
var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator"));
var _currency = require("./currency.constants");
var _currency2 = require("./currency.utils");
function _regenerator() { /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/babel/babel/blob/main/packages/babel-helpers/LICENSE */ var e, t, r = "function" == typeof Symbol ? Symbol : {}, n = r.iterator || "@@iterator", o = r.toStringTag || "@@toStringTag"; function i(r, n, o, i) { var c = n && n.prototype instanceof Generator ? n : Generator, u = Object.create(c.prototype); return _regeneratorDefine2(u, "_invoke", function (r, n, o) { var i, c, u, f = 0, p = o || [], y = !1, G = { p: 0, n: 0, v: e, a: d, f: d.bind(e, 4), d: function d(t, r) { return i = t, c = 0, u = e, G.n = r, a; } }; function d(r, n) { for (c = r, u = n, t = 0; !y && f && !o && t < p.length; t++) { var o, i = p[t], d = G.p, l = i[2]; r > 3 ? (o = l === n) && (u = i[(c = i[4]) ? 5 : (c = 3, 3)], i[4] = i[5] = e) : i[0] <= d && ((o = r < 2 && d < i[1]) ? (c = 0, G.v = n, G.n = i[1]) : d < l && (o = r < 3 || i[0] > n || n > l) && (i[4] = r, i[5] = n, G.n = l, c = 0)); } if (o || r > 1) return a; throw y = !0, n; } return function (o, p, l) { if (f > 1) throw TypeError("Generator is already running"); for (y && 1 === p && d(p, l), c = p, u = l; (t = c < 2 ? e : u) || !y;) { i || (c ? c < 3 ? (c > 1 && (G.n = -1), d(c, u)) : G.n = u : G.v = u); try { if (f = 2, i) { if (c || (o = "next"), t = i[o]) { if (!(t = t.call(i, u))) throw TypeError("iterator result is not an object"); if (!t.done) return t; u = t.value, c < 2 && (c = 0); } else 1 === c && (t = i["return"]) && t.call(i), c < 2 && (u = TypeError("The iterator does not provide a '" + o + "' method"), c = 1); i = e; } else if ((t = (y = G.n < 0) ? u : r.call(n, G)) !== a) break; } catch (t) { i = e, c = 1, u = t; } finally { f = 1; } } return { value: t, done: y }; }; }(r, o, i), !0), u; } var a = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} t = Object.getPrototypeOf; var c = [][n] ? t(t([][n]())) : (_regeneratorDefine2(t = {}, n, function () { return this; }), t), u = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(c); function f(e) { return Object.setPrototypeOf ? Object.setPrototypeOf(e, GeneratorFunctionPrototype) : (e.__proto__ = GeneratorFunctionPrototype, _regeneratorDefine2(e, o, "GeneratorFunction")), e.prototype = Object.create(u), e; } return GeneratorFunction.prototype = GeneratorFunctionPrototype, _regeneratorDefine2(u, "constructor", GeneratorFunctionPrototype), _regeneratorDefine2(GeneratorFunctionPrototype, "constructor", GeneratorFunction), GeneratorFunction.displayName = "GeneratorFunction", _regeneratorDefine2(GeneratorFunctionPrototype, o, "GeneratorFunction"), _regeneratorDefine2(u), _regeneratorDefine2(u, o, "Generator"), _regeneratorDefine2(u, n, function () { return this; }), _regeneratorDefine2(u, "toString", function () { return "[object Generator]"; }), (_regenerator = function _regenerator() { return { w: i, m: f }; })(); }
function _regeneratorDefine2(e, r, n, t) { var i = Object.defineProperty; try { i({}, "", {}); } catch (e) { i = 0; } _regeneratorDefine2 = function _regeneratorDefine(e, r, n, t) { function o(r, n) { _regeneratorDefine2(e, r, function (e) { return this._invoke(r, n, e); }); } r ? i ? i(e, r, { value: n, enumerable: !t, configurable: !t, writable: !t }) : e[r] = n : (o("next", 0), o("throw", 1), o("return", 2)); }, _regeneratorDefine2(e, r, n, t); }
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { (0, _defineProperty2["default"])(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
var findTokenFromDenom = exports.findTokenFromDenom = function findTokenFromDenom(denom) {
  if (!(denom !== null && denom !== void 0 && denom.length)) return;
  var denomLowerCased = denom === null || denom === void 0 ? void 0 : denom.toLowerCase();
  var token = _currency.keplrCurrencies[denomLowerCased];
  if (token) return token;
  var denomUpperCased = denom === null || denom === void 0 ? void 0 : denom.toUpperCase();
  var possibleToken = Object.values(_currency.keplrCurrencies).find(function (currency) {
    return currency.coinMinimalDenom === denom || currency.coinDenom === denom || currency.coinMinimalDenom === denomLowerCased || currency.coinDenom === denomLowerCased || currency.coinMinimalDenom === denomUpperCased || currency.coinDenom === denomUpperCased;
  });
  return possibleToken;
};
var findIbcTokenFromHash = exports.findIbcTokenFromHash = function () {
  var cache = {};
  return /*#__PURE__*/function () {
    var _ref = (0, _asyncToGenerator2["default"])(/*#__PURE__*/_regenerator().m(function _callee(queryClient, ibcHash) {
      var _response$denomTrace;
      var hash, response, token, result;
      return _regenerator().w(function (_context) {
        while (1) switch (_context.n) {
          case 0:
            if (queryClient) {
              _context.n = 1;
              break;
            }
            throw new Error("Invalid query client");
          case 1:
            hash = ibcHash.replace(/^ibc\//i, "");
            if (!cache[hash]) {
              _context.n = 2;
              break;
            }
            return _context.a(2, cache[hash]);
          case 2:
            _context.n = 3;
            return queryClient.ibc.applications.transfer.v1.denomTrace({
              hash: hash
            });
          case 3:
            response = _context.v;
            if ((_response$denomTrace = response.denomTrace) !== null && _response$denomTrace !== void 0 && _response$denomTrace.baseDenom) {
              _context.n = 4;
              break;
            }
            return _context.a(2);
          case 4:
            token = findTokenFromDenom(response.denomTrace.baseDenom);
            result = {
              ibc: _objectSpread(_objectSpread({}, response.denomTrace), {}, {
                hash: hash
              }),
              token: token
            };
            cache[hash] = result;
            return _context.a(2, result);
        }
      }, _callee);
    }));
    return function (_x, _x2) {
      return _ref.apply(this, arguments);
    };
  }();
}();
var findIbcTokensFromHashes = exports.findIbcTokensFromHashes = /*#__PURE__*/function () {
  var _ref2 = (0, _asyncToGenerator2["default"])(/*#__PURE__*/_regenerator().m(function _callee2(queryClient, ibcHashes) {
    var requests, responses, results;
    return _regenerator().w(function (_context2) {
      while (1) switch (_context2.n) {
        case 0:
          if (queryClient) {
            _context2.n = 1;
            break;
          }
          throw new Error("Invalid query client");
        case 1:
          requests = ibcHashes.map(function (ibcHash) {
            return findIbcTokenFromHash(queryClient, ibcHash);
          });
          _context2.n = 2;
          return Promise.allSettled(requests);
        case 2:
          responses = _context2.v;
          results = responses.map(function (response) {
            if (response.status !== "fulfilled") return;
            return response.value;
          });
          return _context2.a(2, results);
      }
    }, _callee2);
  }));
  return function findIbcTokensFromHashes(_x3, _x4) {
    return _ref2.apply(this, arguments);
  };
}();

/**
 * LOCAL USE ONLY
 * Fetch a list of currencies as defined in keplr chain registry:
 * https://github.com/chainapsis/keplr-chain-registry/tree/main/cosmos
 */
// export const fetchAllCurrenciesInKeplrChainRegistry = async () => {
//   const fetchKeplrChainInfo = async (chainName: string) => {
//     try {
//       const url = `https://raw.githubusercontent.com/chainapsis/keplr-chain-registry/main/cosmos/${chainName}.json`;
//       const response = await axios.get(url);
//       return response.data as KeplrChainInfo;
//     } catch (error) {
//       return {} as KeplrChainInfo;
//     }
//   };

//   const responses = await Promise.allSettled(
//     keplrChainNames.map((chainName) => fetchKeplrChainInfo(chainName))
//   );
//   let chainInfos = responses
//     .filter((x) => x.status === "fulfilled")
//     // @ts-ignore
//     .map((x) => x.value);
//   chainInfos = chainInfos.map(prepareKeplrChainInfoTokenAssets);
//   let currencies = chainInfos
//     .map((chainInfo: KeplrChainInfo): TokenAsset[] => chainInfo.currencies)
//     .flat();
//   return currencies.reduce((result, value) => {
//     if (!result[value.coinMinimalDenom])
//       return { ...result, [value.coinMinimalDenom]: value };
//     return {
//       ...result,
//       [value.coinMinimalDenom]: { ...result[value.coinMinimalDenom], ...value },
//     };
//   }, {});
// };

var findTokenInfoFromDenom = exports.findTokenInfoFromDenom = function () {
  var cache = {};
  return /*#__PURE__*/function () {
    var _ref3 = (0, _asyncToGenerator2["default"])(/*#__PURE__*/_regenerator().m(function _callee3(denom) {
      var _cache$denom, _token$coinCodexId;
      var cacheResult,
        baseUrl,
        token,
        coinCodexTokenInfo,
        result,
        _args3 = arguments;
      return _regenerator().w(function (_context3) {
        while (1) switch (_context3.n) {
          case 0:
            cacheResult = _args3.length > 1 && _args3[1] !== undefined ? _args3[1] : true;
            baseUrl = _args3.length > 2 && _args3[2] !== undefined ? _args3[2] : _currency.coinCodexBaseUrl;
            if (denom) {
              _context3.n = 1;
              break;
            }
            return _context3.a(2);
          case 1:
            token = findTokenFromDenom(denom);
            if (!(cacheResult && (cache[denom] || cache[token === null || token === void 0 ? void 0 : token.coinCodexId]))) {
              _context3.n = 2;
              break;
            }
            return _context3.a(2, (_cache$denom = cache[denom]) !== null && _cache$denom !== void 0 ? _cache$denom : cache[token === null || token === void 0 ? void 0 : token.coinCodexId]);
          case 2:
            _context3.n = 3;
            return (0, _currency2.fetchTokenInfo)((_token$coinCodexId = token === null || token === void 0 ? void 0 : token.coinCodexId) !== null && _token$coinCodexId !== void 0 ? _token$coinCodexId : denom, baseUrl);
          case 3:
            coinCodexTokenInfo = _context3.v;
            if (coinCodexTokenInfo) {
              _context3.n = 4;
              break;
            }
            return _context3.a(2);
          case 4:
            result = {
              symbol: coinCodexTokenInfo.symbol,
              coinName: coinCodexTokenInfo.coin_name,
              shortname: coinCodexTokenInfo.shortname,
              slug: coinCodexTokenInfo.slug,
              displaySymbol: coinCodexTokenInfo.display_symbol,
              todayOpen: coinCodexTokenInfo.today_open,
              lastPriceUsd: coinCodexTokenInfo.last_price_usd,
              priceChangePercent: {
                "1H": coinCodexTokenInfo.price_change_1H_percent,
                "1D": coinCodexTokenInfo.price_change_1D_percent,
                "7D": coinCodexTokenInfo.price_change_7D_percent,
                "30D": coinCodexTokenInfo.price_change_30D_percent,
                "90D": coinCodexTokenInfo.price_change_90D_percent
              },
              lastUpdate: coinCodexTokenInfo.last_update,
              social: coinCodexTokenInfo.social
            };
            if (cacheResult) cache[denom] = result;
            return _context3.a(2, result);
        }
      }, _callee3);
    }));
    return function (_x5) {
      return _ref3.apply(this, arguments);
    };
  }();
}();
var findTokensInfoFromDenoms = exports.findTokensInfoFromDenoms = /*#__PURE__*/function () {
  var _ref4 = (0, _asyncToGenerator2["default"])(/*#__PURE__*/_regenerator().m(function _callee4(denoms) {
    var requests, responses, results;
    return _regenerator().w(function (_context4) {
      while (1) switch (_context4.n) {
        case 0:
          requests = denoms.map(function (d) {
            return findTokenInfoFromDenom(d);
          });
          _context4.n = 1;
          return Promise.allSettled(requests);
        case 1:
          responses = _context4.v;
          results = responses.map(function (response) {
            if (response.status !== "fulfilled") return;
            return response.value;
          });
          return _context4.a(2, results);
      }
    }, _callee4);
  }));
  return function findTokensInfoFromDenoms(_x6) {
    return _ref4.apply(this, arguments);
  };
}();
var findTokenHistoryFromDenom = exports.findTokenHistoryFromDenom = function () {
  var cache = {};
  return /*#__PURE__*/function () {
    var _ref5 = (0, _asyncToGenerator2["default"])(/*#__PURE__*/_regenerator().m(function _callee5(denom, startDate, endDate) {
      var _cache$denom2, _token$coinCodexId2, _, _Object$values;
      var samples,
        cacheResult,
        baseUrl,
        token,
        coinCodexTokenHistory,
        result,
        _args5 = arguments;
      return _regenerator().w(function (_context5) {
        while (1) switch (_context5.n) {
          case 0:
            samples = _args5.length > 3 && _args5[3] !== undefined ? _args5[3] : 100;
            cacheResult = _args5.length > 4 && _args5[4] !== undefined ? _args5[4] : true;
            baseUrl = _args5.length > 5 && _args5[5] !== undefined ? _args5[5] : _currency.coinCodexBaseUrl;
            if (denom) {
              _context5.n = 1;
              break;
            }
            return _context5.a(2);
          case 1:
            token = findTokenFromDenom(denom);
            if (!(cacheResult && (cache[denom] || cache[token === null || token === void 0 ? void 0 : token.coinCodexId]))) {
              _context5.n = 2;
              break;
            }
            return _context5.a(2, (_cache$denom2 = cache[denom]) !== null && _cache$denom2 !== void 0 ? _cache$denom2 : cache[token === null || token === void 0 ? void 0 : token.coinCodexId]);
          case 2:
            _context5.n = 3;
            return (0, _currency2.fetchTokenHistory)((_token$coinCodexId2 = token === null || token === void 0 ? void 0 : token.coinCodexId) !== null && _token$coinCodexId2 !== void 0 ? _token$coinCodexId2 : denom, startDate, endDate, samples, baseUrl);
          case 3:
            coinCodexTokenHistory = _context5.v;
            if (coinCodexTokenHistory) {
              _context5.n = 4;
              break;
            }
            return _context5.a(2);
          case 4:
            result = (_ = ((_Object$values = Object.values(coinCodexTokenHistory)) !== null && _Object$values !== void 0 ? _Object$values : [[]])[0]) === null || _ === void 0 ? void 0 : _.map(function (v) {
              return {
                timestamp: v[0],
                usdPrice: v[1],
                usdVolume24H: v[2]
              };
            });
            if (cacheResult) cache[denom] = result;
            return _context5.a(2, result);
        }
      }, _callee5);
    }));
    return function (_x7, _x8, _x9) {
      return _ref5.apply(this, arguments);
    };
  }();
}();
var findTokensHistoryFromDenoms = exports.findTokensHistoryFromDenoms = /*#__PURE__*/function () {
  var _ref6 = (0, _asyncToGenerator2["default"])(/*#__PURE__*/_regenerator().m(function _callee6(denoms, startDate, endDate) {
    var samples,
      cacheResult,
      requests,
      responses,
      results,
      _args6 = arguments;
    return _regenerator().w(function (_context6) {
      while (1) switch (_context6.n) {
        case 0:
          samples = _args6.length > 3 && _args6[3] !== undefined ? _args6[3] : 100;
          cacheResult = _args6.length > 4 && _args6[4] !== undefined ? _args6[4] : true;
          requests = denoms.map(function (d) {
            return findTokenHistoryFromDenom(d, startDate, endDate, samples, cacheResult);
          });
          _context6.n = 1;
          return Promise.allSettled(requests);
        case 1:
          responses = _context6.v;
          results = responses.map(function (response) {
            if (response.status !== "fulfilled") return;
            return response.value;
          });
          return _context6.a(2, results);
      }
    }, _callee6);
  }));
  return function findTokensHistoryFromDenoms(_x0, _x1, _x10) {
    return _ref6.apply(this, arguments);
  };
}();