"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.getSignerData = void 0;
var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator"));
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); }
// Re-export types for backwards compatibility

var SignerStoreKey = "ixo-signer-data";

/**
 * Helper function to get the signer sequence from chain, and if it is same
 * as current locally stored one, it means you you want to send another tx while there is
 * already one in progress on chain, thus increment the local sequence by 1 and use it.
 * If the time from previous check is more than 7 seconds, then we assume the remote sequence is
 * correct and use it since a tx could have failed and thus the sequence is not incremented.
 */
var getSignerData = exports.getSignerData = /*#__PURE__*/function () {
  var _ref = (0, _asyncToGenerator2["default"])(/*#__PURE__*/_regenerator().m(function _callee(signingClient, wallet, storageFunctions) {
    var chainId, accounts, address, _yield$signingClient$, accountNumber, sequence, data, now, updated, timeDiff, _t;
    return _regenerator().w(function (_context) {
      while (1) switch (_context.n) {
        case 0:
          if (storageFunctions) {
            _context.n = 1;
            break;
          }
          throw new Error("Storage functions not provided");
        case 1:
          _context.n = 2;
          return signingClient.getChainId();
        case 2:
          chainId = _context.v;
          _context.n = 3;
          return wallet.getAccounts();
        case 3:
          accounts = _context.v;
          address = accounts[0].address;
          _context.n = 4;
          return signingClient.getSequence(address);
        case 4:
          _yield$signingClient$ = _context.v;
          accountNumber = _yield$signingClient$.accountNumber;
          sequence = _yield$signingClient$.sequence;
          if (!storageFunctions.getAndIncrementSequence) {
            _context.n = 5;
            break;
          }
          return _context.a(2, storageFunctions.getAndIncrementSequence({
            chainId: chainId,
            accountNumber: accountNumber,
            chainSequence: sequence
          }));
        case 5:
          if (!(!storageFunctions.getLocalData || !storageFunctions.setLocalData)) {
            _context.n = 6;
            break;
          }
          throw new Error("Storage functions must provide either getAndIncrementSequence or both getLocalData and setLocalData");
        case 6:
          _context.n = 7;
          return storageFunctions.getLocalData(SignerStoreKey);
        case 7:
          _t = _context.v;
          if (_t) {
            _context.n = 8;
            break;
          }
          _t = {};
        case 8:
          data = _t;
          now = new Date();
          if (!data[chainId]) data[chainId] = {};
          if (!data[chainId][accountNumber]) {
            data[chainId][accountNumber] = {
              sequence: sequence,
              updated: now.toISOString()
            };
          }
          updated = new Date(data[chainId][accountNumber].updated);
          timeDiff = now.getTime() - updated.getTime();
          if (
          // last updated is more than 7 seconds ago
          timeDiff > 7000 ||
          // or no timeDiff which means it is the first time
          timeDiff === 0 ||
          // or the remote sequence is more than local one
          sequence > data[chainId][accountNumber].sequence) {
            // then update the local sequence to use remote one
            data[chainId][accountNumber].sequence = sequence;
          } else {
            // otherwise increment the local sequence by 1 as we are sending another tx while remote one is in progress
            data[chainId][accountNumber].sequence++;
          }

          // set the updated time to now
          data[chainId][accountNumber].updated = now.toISOString();

          // Await setLocalData to ensure data is persisted before returning
          // This prevents race conditions where concurrent calls read stale sequence data
          _context.n = 9;
          return storageFunctions.setLocalData(SignerStoreKey, data);
        case 9:
          return _context.a(2, {
            accountNumber: accountNumber,
            sequence: data[chainId][accountNumber].sequence,
            chainId: chainId
          });
      }
    }, _callee);
  }));
  return function getSignerData(_x, _x2, _x3) {
    return _ref.apply(this, arguments);
  };
}();