import { PublicKey, Transaction, TransactionMessage, VersionedTransaction } from '@solana/web3.js';
import BN from 'bn.js';
import keccak256 from 'keccak256';
import secp256k1 from 'secp256k1';

var AUDIO_DECMIALS = 18;
var WAUDIO_DECMIALS = 8;
var CURRENT_USER_EXISTS_LOCAL_STORAGE_KEY = '@audius/libs:found-user';
var AuthHeaders;
(function (AuthHeaders) {
  AuthHeaders["MESSAGE"] = "Encoded-Data-Message";
  AuthHeaders["SIGNATURE"] = "Encoded-Data-Signature";
})(AuthHeaders || (AuthHeaders = {}));

var getTrackListens = function getTrackListens() {
  var timeFrame = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
  var idsArray = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
  var startTime = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
  var endTime = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null;
  var limit = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : null;
  var offset = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : null;
  var queryUrl = 'tracks/listens/';
  if (timeFrame != null) {
    switch (timeFrame) {
      case 'day':
      case 'week':
      case 'month':
      case 'year':
      case 'millennium':
        break;
      default:
        throw new Error('Invalid timeFrame value provided');
    }
    queryUrl += timeFrame;
  }
  var queryParams = {};
  if (idsArray !== null) {
    queryParams.id = idsArray;
  }
  if (limit !== null) {
    queryParams.limit = limit;
  }
  if (offset !== null) {
    queryParams.offset = offset;
  }
  if (startTime != null) {
    queryParams.start = startTime;
  }
  if (endTime != null) {
    queryParams.end = endTime;
  }
  var req = {
    url: queryUrl,
    method: 'get',
    params: queryParams
  };
  return req;
};

var requests$1 = /*#__PURE__*/Object.freeze({
    __proto__: null,
    getTrackListens: getTrackListens
});

function _iterableToArrayLimit(r, l) {
  var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"];
  if (null != t) {
    var e,
      n,
      i,
      u,
      a = [],
      f = !0,
      o = !1;
    try {
      if (i = (t = t.call(r)).next, 0 === l) {
        if (Object(t) !== t) return;
        f = !1;
      } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0);
    } catch (r) {
      o = !0, n = r;
    } finally {
      try {
        if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return;
      } finally {
        if (o) throw n;
      }
    }
    return a;
  }
}
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 _objectSpread2(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) {
      _defineProperty(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;
}
function _regeneratorRuntime() {
  _regeneratorRuntime = function () {
    return e;
  };
  var t,
    e = {},
    r = Object.prototype,
    n = r.hasOwnProperty,
    o = Object.defineProperty || function (t, e, r) {
      t[e] = r.value;
    },
    i = "function" == typeof Symbol ? Symbol : {},
    a = i.iterator || "@@iterator",
    c = i.asyncIterator || "@@asyncIterator",
    u = i.toStringTag || "@@toStringTag";
  function define(t, e, r) {
    return Object.defineProperty(t, e, {
      value: r,
      enumerable: !0,
      configurable: !0,
      writable: !0
    }), t[e];
  }
  try {
    define({}, "");
  } catch (t) {
    define = function (t, e, r) {
      return t[e] = r;
    };
  }
  function wrap(t, e, r, n) {
    var i = e && e.prototype instanceof Generator ? e : Generator,
      a = Object.create(i.prototype),
      c = new Context(n || []);
    return o(a, "_invoke", {
      value: makeInvokeMethod(t, r, c)
    }), a;
  }
  function tryCatch(t, e, r) {
    try {
      return {
        type: "normal",
        arg: t.call(e, r)
      };
    } catch (t) {
      return {
        type: "throw",
        arg: t
      };
    }
  }
  e.wrap = wrap;
  var h = "suspendedStart",
    l = "suspendedYield",
    f = "executing",
    s = "completed",
    y = {};
  function Generator() {}
  function GeneratorFunction() {}
  function GeneratorFunctionPrototype() {}
  var p = {};
  define(p, a, function () {
    return this;
  });
  var d = Object.getPrototypeOf,
    v = d && d(d(values([])));
  v && v !== r && n.call(v, a) && (p = v);
  var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p);
  function defineIteratorMethods(t) {
    ["next", "throw", "return"].forEach(function (e) {
      define(t, e, function (t) {
        return this._invoke(e, t);
      });
    });
  }
  function AsyncIterator(t, e) {
    function invoke(r, o, i, a) {
      var c = tryCatch(t[r], t, o);
      if ("throw" !== c.type) {
        var u = c.arg,
          h = u.value;
        return h && "object" == typeof h && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) {
          invoke("next", t, i, a);
        }, function (t) {
          invoke("throw", t, i, a);
        }) : e.resolve(h).then(function (t) {
          u.value = t, i(u);
        }, function (t) {
          return invoke("throw", t, i, a);
        });
      }
      a(c.arg);
    }
    var r;
    o(this, "_invoke", {
      value: function (t, n) {
        function callInvokeWithMethodAndArg() {
          return new e(function (e, r) {
            invoke(t, n, e, r);
          });
        }
        return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg();
      }
    });
  }
  function makeInvokeMethod(e, r, n) {
    var o = h;
    return function (i, a) {
      if (o === f) throw new Error("Generator is already running");
      if (o === s) {
        if ("throw" === i) throw a;
        return {
          value: t,
          done: !0
        };
      }
      for (n.method = i, n.arg = a;;) {
        var c = n.delegate;
        if (c) {
          var u = maybeInvokeDelegate(c, n);
          if (u) {
            if (u === y) continue;
            return u;
          }
        }
        if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) {
          if (o === h) throw o = s, n.arg;
          n.dispatchException(n.arg);
        } else "return" === n.method && n.abrupt("return", n.arg);
        o = f;
        var p = tryCatch(e, r, n);
        if ("normal" === p.type) {
          if (o = n.done ? s : l, p.arg === y) continue;
          return {
            value: p.arg,
            done: n.done
          };
        }
        "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg);
      }
    };
  }
  function maybeInvokeDelegate(e, r) {
    var n = r.method,
      o = e.iterator[n];
    if (o === t) return r.delegate = null, "throw" === n && e.iterator.return && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y;
    var i = tryCatch(o, e.iterator, r.arg);
    if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y;
    var a = i.arg;
    return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y);
  }
  function pushTryEntry(t) {
    var e = {
      tryLoc: t[0]
    };
    1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e);
  }
  function resetTryEntry(t) {
    var e = t.completion || {};
    e.type = "normal", delete e.arg, t.completion = e;
  }
  function Context(t) {
    this.tryEntries = [{
      tryLoc: "root"
    }], t.forEach(pushTryEntry, this), this.reset(!0);
  }
  function values(e) {
    if (e || "" === e) {
      var r = e[a];
      if (r) return r.call(e);
      if ("function" == typeof e.next) return e;
      if (!isNaN(e.length)) {
        var o = -1,
          i = function next() {
            for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next;
            return next.value = t, next.done = !0, next;
          };
        return i.next = i;
      }
    }
    throw new TypeError(typeof e + " is not iterable");
  }
  return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", {
    value: GeneratorFunctionPrototype,
    configurable: !0
  }), o(GeneratorFunctionPrototype, "constructor", {
    value: GeneratorFunction,
    configurable: !0
  }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) {
    var e = "function" == typeof t && t.constructor;
    return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name));
  }, e.mark = function (t) {
    return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t;
  }, e.awrap = function (t) {
    return {
      __await: t
    };
  }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () {
    return this;
  }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) {
    void 0 === i && (i = Promise);
    var a = new AsyncIterator(wrap(t, r, n, o), i);
    return e.isGeneratorFunction(r) ? a : a.next().then(function (t) {
      return t.done ? t.value : a.next();
    });
  }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () {
    return this;
  }), define(g, "toString", function () {
    return "[object Generator]";
  }), e.keys = function (t) {
    var e = Object(t),
      r = [];
    for (var n in e) r.push(n);
    return r.reverse(), function next() {
      for (; r.length;) {
        var t = r.pop();
        if (t in e) return next.value = t, next.done = !1, next;
      }
      return next.done = !0, next;
    };
  }, e.values = values, Context.prototype = {
    constructor: Context,
    reset: function (e) {
      if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t);
    },
    stop: function () {
      this.done = !0;
      var t = this.tryEntries[0].completion;
      if ("throw" === t.type) throw t.arg;
      return this.rval;
    },
    dispatchException: function (e) {
      if (this.done) throw e;
      var r = this;
      function handle(n, o) {
        return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o;
      }
      for (var o = this.tryEntries.length - 1; o >= 0; --o) {
        var i = this.tryEntries[o],
          a = i.completion;
        if ("root" === i.tryLoc) return handle("end");
        if (i.tryLoc <= this.prev) {
          var c = n.call(i, "catchLoc"),
            u = n.call(i, "finallyLoc");
          if (c && u) {
            if (this.prev < i.catchLoc) return handle(i.catchLoc, !0);
            if (this.prev < i.finallyLoc) return handle(i.finallyLoc);
          } else if (c) {
            if (this.prev < i.catchLoc) return handle(i.catchLoc, !0);
          } else {
            if (!u) throw new Error("try statement without catch or finally");
            if (this.prev < i.finallyLoc) return handle(i.finallyLoc);
          }
        }
      }
    },
    abrupt: function (t, e) {
      for (var r = this.tryEntries.length - 1; r >= 0; --r) {
        var o = this.tryEntries[r];
        if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) {
          var i = o;
          break;
        }
      }
      i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null);
      var a = i ? i.completion : {};
      return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a);
    },
    complete: function (t, e) {
      if ("throw" === t.type) throw t.arg;
      return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y;
    },
    finish: function (t) {
      for (var e = this.tryEntries.length - 1; e >= 0; --e) {
        var r = this.tryEntries[e];
        if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y;
      }
    },
    catch: function (t) {
      for (var e = this.tryEntries.length - 1; e >= 0; --e) {
        var r = this.tryEntries[e];
        if (r.tryLoc === t) {
          var n = r.completion;
          if ("throw" === n.type) {
            var o = n.arg;
            resetTryEntry(r);
          }
          return o;
        }
      }
      throw new Error("illegal catch attempt");
    },
    delegateYield: function (e, r, n) {
      return this.delegate = {
        iterator: values(e),
        resultName: r,
        nextLoc: n
      }, "next" === this.method && (this.arg = t), y;
    }
  }, e;
}
function _typeof(o) {
  "@babel/helpers - typeof";

  return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) {
    return typeof o;
  } : function (o) {
    return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o;
  }, _typeof(o);
}
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
  try {
    var info = gen[key](arg);
    var value = info.value;
  } catch (error) {
    reject(error);
    return;
  }
  if (info.done) {
    resolve(value);
  } else {
    Promise.resolve(value).then(_next, _throw);
  }
}
function _asyncToGenerator(fn) {
  return function () {
    var self = this,
      args = arguments;
    return new Promise(function (resolve, reject) {
      var gen = fn.apply(self, args);
      function _next(value) {
        asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
      }
      function _throw(err) {
        asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
      }
      _next(undefined);
    });
  };
}
function _classCallCheck(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}
function _defineProperties(target, props) {
  for (var i = 0; i < props.length; i++) {
    var descriptor = props[i];
    descriptor.enumerable = descriptor.enumerable || false;
    descriptor.configurable = true;
    if ("value" in descriptor) descriptor.writable = true;
    Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor);
  }
}
function _createClass(Constructor, protoProps, staticProps) {
  if (protoProps) _defineProperties(Constructor.prototype, protoProps);
  if (staticProps) _defineProperties(Constructor, staticProps);
  Object.defineProperty(Constructor, "prototype", {
    writable: false
  });
  return Constructor;
}
function _defineProperty(obj, key, value) {
  key = _toPropertyKey(key);
  if (key in obj) {
    Object.defineProperty(obj, key, {
      value: value,
      enumerable: true,
      configurable: true,
      writable: true
    });
  } else {
    obj[key] = value;
  }
  return obj;
}
function _slicedToArray(arr, i) {
  return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest();
}
function _toConsumableArray(arr) {
  return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread();
}
function _arrayWithoutHoles(arr) {
  if (Array.isArray(arr)) return _arrayLikeToArray(arr);
}
function _arrayWithHoles(arr) {
  if (Array.isArray(arr)) return arr;
}
function _iterableToArray(iter) {
  if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
}
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;
}
function _nonIterableSpread() {
  throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _nonIterableRest() {
  throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
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 () {};
      return {
        s: F,
        n: function () {
          if (i >= o.length) return {
            done: true
          };
          return {
            done: false,
            value: o[i++]
          };
        },
        e: function (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 () {
      it = it.call(o);
    },
    n: function () {
      var step = it.next();
      normalCompletion = step.done;
      return step;
    },
    e: function (e) {
      didErr = true;
      err = e;
    },
    f: function () {
      try {
        if (!normalCompletion && it.return != null) it.return();
      } finally {
        if (didErr) throw err;
      }
    }
  };
}
function _toPrimitive(input, hint) {
  if (typeof input !== "object" || input === null) return input;
  var prim = input[Symbol.toPrimitive];
  if (prim !== undefined) {
    var res = prim.call(input, hint || "default");
    if (typeof res !== "object") return res;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return (hint === "string" ? String : Number)(input);
}
function _toPropertyKey(arg) {
  var key = _toPrimitive(arg, "string");
  return typeof key === "symbol" ? key : String(key);
}

/* eslint-disable @typescript-eslint/restrict-plus-operands */
var getUsers = function getUsers() {
  var limit = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 100;
  var offset = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
  var idsArray = arguments.length > 2 ? arguments[2] : undefined;
  var walletAddress = arguments.length > 3 ? arguments[3] : undefined;
  var handle = arguments.length > 4 ? arguments[4] : undefined;
  var minBlockNumber = arguments.length > 5 ? arguments[5] : undefined;
  var includeIncomplete = arguments.length > 6 ? arguments[6] : undefined;
  var queryParams = {
    limit: limit,
    offset: offset
  };
  if (handle) {
    queryParams.handle = handle;
  }
  if (walletAddress) {
    queryParams.wallet = walletAddress;
  }
  if (minBlockNumber) {
    queryParams.min_block_number = minBlockNumber;
  }
  if (idsArray != null) {
    if (!Array.isArray(idsArray)) {
      throw new Error('Expected integer array of user ids');
    }
    queryParams.id = idsArray;
  }
  if (includeIncomplete != null) {
    queryParams.include_incomplete = includeIncomplete;
  }
  var req = {
    endpoint: 'users',
    queryParams: queryParams
  };
  return req;
};
var getTracks = function getTracks() {
  var limit = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 100;
  var offset = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
  var idsArray = arguments.length > 2 ? arguments[2] : undefined;
  var targetUserId = arguments.length > 3 ? arguments[3] : undefined;
  var sort = arguments.length > 4 ? arguments[4] : undefined;
  var minBlockNumber = arguments.length > 5 ? arguments[5] : undefined;
  var filterDeleted = arguments.length > 6 ? arguments[6] : undefined;
  var withUsers = arguments.length > 7 && arguments[7] !== undefined ? arguments[7] : false;
  var queryParams = {
    limit: limit,
    offset: offset
  };
  if (idsArray) {
    if (!Array.isArray(idsArray)) {
      throw new Error('Expected array of track ids');
    }
    queryParams.id = idsArray;
  }
  if (minBlockNumber) {
    queryParams.min_block_number = minBlockNumber;
  }
  if (targetUserId) {
    queryParams.user_id = targetUserId;
  }
  if (sort) {
    queryParams.sort = sort;
  }
  if (typeof filterDeleted === 'boolean') {
    queryParams.filter_deleted = filterDeleted;
  }
  if (withUsers) {
    queryParams.with_users = true;
  }
  var req = {
    endpoint: 'tracks',
    queryParams: queryParams
  };
  return req;
};
var getTracksByHandleAndSlug = function getTracksByHandleAndSlug(handle, slug) {
  return {
    endpoint: 'v1/tracks',
    method: 'get',
    queryParams: {
      handle: handle,
      slug: slug
    }
  };
};
var getTracksIncludingUnlisted = function getTracksIncludingUnlisted(identifiers) {
  var withUsers = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
  var queryParams = {};
  if (withUsers) {
    queryParams.with_users = true;
  }
  var req = {
    endpoint: 'tracks_including_unlisted',
    method: 'post',
    data: {
      tracks: identifiers
    },
    queryParams: queryParams
  };
  return req;
};
var getRandomTracks = function getRandomTracks(genre, limit, exclusionList, time) {
  var req = {
    endpoint: 'tracks/random',
    queryParams: {
      genre: genre,
      limit: limit,
      exclusionList: exclusionList,
      time: time
    }
  };
  return req;
};
var getStemsForTrack = function getStemsForTrack(trackId) {
  var req = {
    endpoint: "stems/".concat(trackId),
    queryParams: {
      with_users: true
    }
  };
  return req;
};
var getRemixesOfTrack = function getRemixesOfTrack(trackId) {
  var limit = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
  var offset = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
  var req = {
    endpoint: "remixes/".concat(trackId, "/children"),
    queryParams: {
      with_users: true,
      limit: limit,
      offset: offset
    }
  };
  return req;
};
var getRemixTrackParents = function getRemixTrackParents(trackId) {
  var limit = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
  var offset = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
  var req = {
    endpoint: "remixes/".concat(trackId, "/parents"),
    queryParams: {
      with_users: true,
      limit: limit,
      offset: offset
    }
  };
  return req;
};
var getTrendingTracks = function getTrendingTracks() {
  var genre = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
  var timeFrame = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
  var idsArray = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
  var limit = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null;
  var offset = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : null;
  var withUsers = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : false;
  var endpoint = '/trending/';
  if (timeFrame != null) {
    switch (timeFrame) {
      case 'day':
      case 'week':
      case 'month':
      case 'year':
        break;
      default:
        throw new Error('Invalid timeFrame value provided');
    }
    endpoint += "".concat(endpoint).concat(timeFrame);
  }
  var req = {
    endpoint: endpoint,
    method: 'get',
    queryParams: _objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2({}, idsArray !== null ? {
      id: idsArray
    } : {}), limit !== null ? {
      limit: limit
    } : {}), offset !== null ? {
      offset: offset
    } : {}), genre !== null ? {
      genre: genre
    } : {}), withUsers ? {
      with_users: withUsers
    } : {})
  };
  return req;
};
var getPlaylists = function getPlaylists() {
  var limit = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 100;
  var offset = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
  var idsArray = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
  var targetUserId = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null;
  var withUsers = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : false;
  if (idsArray != null) {
    if (!Array.isArray(idsArray)) {
      throw new Error('Expected integer array of user ids');
    }
  }
  return {
    endpoint: 'playlists',
    queryParams: _objectSpread2(_objectSpread2(_objectSpread2({
      limit: limit,
      offset: offset
    }, idsArray != null ? {
      playlist_id: idsArray
    } : {}), targetUserId ? {
      user_id: targetUserId
    } : {}), withUsers ? {
      with_users: true
    } : {})
  };
};
var getFullPlaylist = function getFullPlaylist(encodedPlaylistId, encodedUserId) {
  return {
    endpoint: 'v1/full/playlists',
    urlParams: '/' + encodedPlaylistId,
    queryParams: {
      user_id: encodedUserId
    }
  };
};
var getSocialFeed = function getSocialFeed(filter) {
  var limit = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 100;
  var offset = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0;
  var withUsers = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false;
  var tracksOnly = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : false;
  return {
    endpoint: 'feed',
    queryParams: {
      filter: filter,
      limit: limit,
      offset: offset,
      with_users: withUsers,
      tracks_only: tracksOnly
    }
  };
};
var getUserRepostFeed = function getUserRepostFeed(userId) {
  var limit = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 100;
  var offset = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0;
  var withUsers = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false;
  return {
    endpoint: 'feed',
    urlParams: '/reposts/' + userId,
    queryParams: {
      limit: limit,
      offset: offset,
      with_users: withUsers
    }
  };
};
var getFollowIntersectionUsers = function getFollowIntersectionUsers() {
  var limit = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 100;
  var offset = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
  var followeeUserId = arguments.length > 2 ? arguments[2] : undefined;
  var followerUserId = arguments.length > 3 ? arguments[3] : undefined;
  return {
    endpoint: 'users',
    urlParams: '/intersection/follow/' + followeeUserId + '/' + followerUserId,
    queryParams: {
      limit: limit,
      offset: offset
    }
  };
};
var getTrackRepostIntersectionUsers = function getTrackRepostIntersectionUsers() {
  var limit = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 100;
  var offset = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
  var repostTrackId = arguments.length > 2 ? arguments[2] : undefined;
  var followerUserId = arguments.length > 3 ? arguments[3] : undefined;
  return {
    endpoint: 'users',
    urlParams: '/intersection/repost/track/' + repostTrackId + '/' + followerUserId,
    queryParams: {
      limit: limit,
      offset: offset
    }
  };
};
var getPlaylistRepostIntersectionUsers = function getPlaylistRepostIntersectionUsers() {
  var limit = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 100;
  var offset = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
  var repostPlaylistId = arguments.length > 2 ? arguments[2] : undefined;
  var followerUserId = arguments.length > 3 ? arguments[3] : undefined;
  return {
    endpoint: 'users',
    urlParams: '/intersection/repost/playlist/' + repostPlaylistId + '/' + followerUserId,
    queryParams: {
      limit: limit,
      offset: offset
    }
  };
};
var getFollowersForUser = function getFollowersForUser() {
  var limit = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 100;
  var offset = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
  var followeeUserId = arguments.length > 2 ? arguments[2] : undefined;
  return {
    endpoint: 'users',
    urlParams: '/followers/' + followeeUserId,
    queryParams: {
      limit: limit,
      offset: offset
    }
  };
};
var getFolloweesForUser = function getFolloweesForUser() {
  var limit = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 100;
  var offset = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
  var followerUserId = arguments.length > 2 ? arguments[2] : undefined;
  return {
    endpoint: 'users',
    urlParams: '/followees/' + followerUserId,
    queryParams: {
      limit: limit,
      offset: offset
    }
  };
};
var getRepostersForTrack = function getRepostersForTrack() {
  var limit = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 100;
  var offset = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
  var repostTrackId = arguments.length > 2 ? arguments[2] : undefined;
  return {
    endpoint: 'users',
    urlParams: '/reposts/track/' + repostTrackId,
    queryParams: {
      limit: limit,
      offset: offset
    }
  };
};
var getRepostersForPlaylist = function getRepostersForPlaylist() {
  var limit = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 100;
  var offset = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
  var repostPlaylistId = arguments.length > 2 ? arguments[2] : undefined;
  return {
    endpoint: 'users',
    urlParams: '/reposts/playlist/' + repostPlaylistId,
    queryParams: {
      limit: limit,
      offset: offset
    }
  };
};
var getSaversForTrack = function getSaversForTrack() {
  var limit = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 100;
  var offset = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
  var saveTrackId = arguments.length > 2 ? arguments[2] : undefined;
  return {
    endpoint: 'users',
    urlParams: '/saves/track/' + saveTrackId,
    queryParams: {
      limit: limit,
      offset: offset
    }
  };
};
var getSaversForPlaylist = function getSaversForPlaylist() {
  var limit = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 100;
  var offset = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
  var savePlaylistId = arguments.length > 2 ? arguments[2] : undefined;
  return {
    endpoint: 'users',
    urlParams: '/saves/playlist/' + savePlaylistId,
    queryParams: {
      limit: limit,
      offset: offset
    }
  };
};
var searchFull = function searchFull(text, kind) {
  var limit = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 100;
  var offset = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0;
  return {
    endpoint: 'search/full',
    queryParams: {
      query: text,
      kind: kind,
      limit: limit,
      offset: offset
    }
  };
};
var searchAutocomplete = function searchAutocomplete(text) {
  var limit = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 100;
  var offset = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0;
  return {
    endpoint: 'search/autocomplete',
    queryParams: {
      query: text,
      limit: limit,
      offset: offset
    }
  };
};
var searchTags = function searchTags(text) {
  var userTagCount = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 2;
  var kind = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'all';
  var limit = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 100;
  var offset = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 0;
  return {
    endpoint: 'search/tags',
    queryParams: {
      query: text,
      user_tag_count: userTagCount,
      kind: kind,
      limit: limit,
      offset: offset
    }
  };
};
var getSavedPlaylists = function getSavedPlaylists() {
  var limit = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 100;
  var offset = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
  var withUsers = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
  return {
    endpoint: 'saves/playlists',
    queryParams: {
      limit: limit,
      offset: offset,
      with_users: withUsers
    }
  };
};
var getSavedAlbums = function getSavedAlbums() {
  var limit = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 100;
  var offset = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
  var withUsers = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
  return {
    endpoint: 'saves/albums',
    queryParams: {
      limit: limit,
      offset: offset,
      with_users: withUsers
    }
  };
};
var getSavedTracks = function getSavedTracks() {
  var limit = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 100;
  var offset = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
  var withUsers = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
  return {
    endpoint: 'saves/tracks',
    queryParams: {
      limit: limit,
      offset: offset,
      with_users: withUsers
    }
  };
};
/**
 * Return user collections (saved & uploaded) along w/ users for those collections
 */
var getUserAccount = function getUserAccount(wallet) {
  if (wallet === undefined) {
    throw new Error('Expected wallet to get user account');
  }
  return {
    endpoint: 'users/account',
    queryParams: {
      wallet: wallet
    }
  };
};
/**
 * @deprecated Migrate to using getTopFullPlaylists
 */
var getTopPlaylists = function getTopPlaylists(type, limit, mood, filter) {
  var withUsers = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : false;
  return {
    endpoint: "/top/".concat(type),
    queryParams: {
      limit: limit,
      mood: mood,
      filter: filter,
      with_users: withUsers
    }
  };
};
var getTopFullPlaylists = function getTopFullPlaylists(_ref) {
  var type = _ref.type,
    limit = _ref.limit,
    mood = _ref.mood,
    filter = _ref.filter,
    encodedUserId = _ref.encodedUserId,
    _ref$withUsers = _ref.withUsers,
    withUsers = _ref$withUsers === void 0 ? false : _ref$withUsers;
  return {
    endpoint: "/v1/full/playlists/top",
    queryParams: {
      type: type,
      limit: limit,
      mood: mood,
      filter: filter,
      with_users: withUsers,
      user_id: encodedUserId
    }
  };
};
/**
 * @deprecated Migrate to using getBestNewReleases
 */
var getTopFolloweeWindowed = function getTopFolloweeWindowed(type, window, limit) {
  var withUsers = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false;
  return {
    endpoint: "/top_followee_windowed/".concat(type, "/").concat(window),
    queryParams: {
      limit: limit,
      with_users: withUsers
    }
  };
};
var getBestNewReleases = function getBestNewReleases(window, limit, encodedUserId) {
  var withUsers = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false;
  return {
    endpoint: "/v1/full/tracks/best_new_releases",
    queryParams: {
      window: window,
      limit: limit,
      user_id: encodedUserId,
      with_users: withUsers
    }
  };
};
var getMostLovedTracks = function getMostLovedTracks(encodedUserId, limit) {
  var withUsers = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
  return {
    endpoint: "/v1/full/tracks/most_loved",
    queryParams: {
      limit: limit,
      user_id: encodedUserId,
      with_users: withUsers
    }
  };
};
var getFeelingLuckyTracks = function getFeelingLuckyTracks(encodedUserId, limit) {
  var withUsers = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
  return {
    endpoint: "/v1/full/tracks/feeling_lucky",
    queryParams: {
      limit: limit,
      user_id: encodedUserId,
      with_users: withUsers
    }
  };
};
var getTopFolloweeSaves = function getTopFolloweeSaves(type, limit) {
  var withUsers = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
  return {
    endpoint: "/top_followee_saves/".concat(type),
    queryParams: {
      limit: limit,
      with_users: withUsers
    }
  };
};
var getLatest = function getLatest(type) {
  var limit = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1;
  var offset = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0;
  return {
    endpoint: "/latest/".concat(type),
    queryParams: {
      limit: limit,
      offset: offset
    }
  };
};
var getTopCreatorsByGenres = function getTopCreatorsByGenres(genres) {
  var limit = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 30;
  var offset = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0;
  var withUsers = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false;
  return {
    endpoint: 'users/genre/top',
    queryParams: {
      genre: genres,
      limit: limit,
      offset: offset,
      with_users: withUsers
    }
  };
};
var getURSMContentNodes = function getURSMContentNodes(ownerWallet) {
  return {
    endpoint: 'ursm_content_nodes',
    queryParams: {
      owner_wallet: ownerWallet
    }
  };
};
var getNotifications = function getNotifications(minBlockNumber, trackIds, timeout) {
  return {
    endpoint: 'notifications',
    queryParams: {
      min_block_number: minBlockNumber,
      track_id: trackIds
    },
    timeout: timeout
  };
};
var getUserNotifications = function getUserNotifications(_ref2) {
  var encodedUserId = _ref2.encodedUserId,
    timestamp = _ref2.timestamp,
    groupId = _ref2.groupId,
    limit = _ref2.limit,
    validTypes = _ref2.validTypes;
  return {
    endpoint: "v1/full/notifications/".concat(encodedUserId),
    queryParams: {
      timestamp: timestamp,
      group_id: groupId,
      limit: limit,
      valid_types: validTypes
    }
  };
};
var getUserSubscribers = function getUserSubscribers(encodedUserId, timeout) {
  return {
    endpoint: "v1/full/users/".concat(encodedUserId, "/subscribers"),
    method: 'get',
    timeout: timeout
  };
};
var bulkGetUserSubscribers = function bulkGetUserSubscribers(encodedUserIds, timeout) {
  return {
    endpoint: 'v1/full/users/subscribers',
    method: 'post',
    headers: {
      'Content-Type': 'application/json'
    },
    data: {
      ids: encodedUserIds
    },
    timeout: timeout
  };
};
var getCIDData = function getCIDData(cid) {
  var responseType = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'json';
  var timeout = arguments.length > 2 ? arguments[2] : undefined;
  return {
    endpoint: "v1/full/cid_data/".concat(cid),
    method: 'get',
    responseType: responseType,
    timeout: timeout
  };
};
var getSolanaNotifications = function getSolanaNotifications(minSlotNumber, timeout) {
  return {
    endpoint: 'solana_notifications',
    queryParams: {
      min_slot_number: minSlotNumber
    },
    timeout: timeout
  };
};
var getTrackListenMilestones = function getTrackListenMilestones(timeout) {
  return {
    endpoint: 'track_listen_milestones',
    timeout: timeout
  };
};
var getChallengeAttestation = function getChallengeAttestation(challengeId, encodedUserId, specifier, oracleAddress) {
  return {
    endpoint: "/v1/challenges/".concat(challengeId, "/attest"),
    queryParams: {
      user_id: encodedUserId,
      specifier: specifier,
      oracle: oracleAddress
    }
  };
};
var getCreateSenderAttestation = function getCreateSenderAttestation(senderEthAddress) {
  return {
    endpoint: '/v1/challenges/attest_sender',
    queryParams: {
      sender_eth_address: senderEthAddress
    }
  };
};
var getUndisbursedChallenges = function getUndisbursedChallenges(limit, offset, completedBlockNumber, encodedUserId) {
  return {
    endpoint: '/v1/challenges/undisbursed',
    queryParams: {
      limit: limit,
      offset: offset,
      completed_blocknumber: completedBlockNumber,
      user_id: encodedUserId
    }
  };
};
var verifyToken = function verifyToken(token) {
  return {
    endpoint: '/v1/users/verify_token',
    queryParams: {
      token: token
    }
  };
};
var getUserReplicaSet = function getUserReplicaSet(encodedUserId) {
  return {
    endpoint: "/v1/full/users/".concat(encodedUserId, "/replica_set"),
    timeout: 5000
  };
};
var getUnclaimedId = function getUnclaimedId(type) {
  return {
    endpoint: "/v1/".concat(type, "/unclaimed_id"),
    timeout: 5000,
    queryParams: {
      noCache: Math.floor(Math.random() * 1000).toString()
    }
  };
};
var getUserListenCountsMonthly = function getUserListenCountsMonthly(encodedUserId, startTime, endTime) {
  return {
    endpoint: "/v1/users/".concat(encodedUserId, "/listen_counts_monthly"),
    timeout: 10000,
    queryParams: {
      start_time: startTime,
      end_time: endTime
    }
  };
};

var requests = /*#__PURE__*/Object.freeze({
    __proto__: null,
    getUsers: getUsers,
    getTracks: getTracks,
    getTracksByHandleAndSlug: getTracksByHandleAndSlug,
    getTracksIncludingUnlisted: getTracksIncludingUnlisted,
    getRandomTracks: getRandomTracks,
    getStemsForTrack: getStemsForTrack,
    getRemixesOfTrack: getRemixesOfTrack,
    getRemixTrackParents: getRemixTrackParents,
    getTrendingTracks: getTrendingTracks,
    getPlaylists: getPlaylists,
    getFullPlaylist: getFullPlaylist,
    getSocialFeed: getSocialFeed,
    getUserRepostFeed: getUserRepostFeed,
    getFollowIntersectionUsers: getFollowIntersectionUsers,
    getTrackRepostIntersectionUsers: getTrackRepostIntersectionUsers,
    getPlaylistRepostIntersectionUsers: getPlaylistRepostIntersectionUsers,
    getFollowersForUser: getFollowersForUser,
    getFolloweesForUser: getFolloweesForUser,
    getRepostersForTrack: getRepostersForTrack,
    getRepostersForPlaylist: getRepostersForPlaylist,
    getSaversForTrack: getSaversForTrack,
    getSaversForPlaylist: getSaversForPlaylist,
    searchFull: searchFull,
    searchAutocomplete: searchAutocomplete,
    searchTags: searchTags,
    getSavedPlaylists: getSavedPlaylists,
    getSavedAlbums: getSavedAlbums,
    getSavedTracks: getSavedTracks,
    getUserAccount: getUserAccount,
    getTopPlaylists: getTopPlaylists,
    getTopFullPlaylists: getTopFullPlaylists,
    getTopFolloweeWindowed: getTopFolloweeWindowed,
    getBestNewReleases: getBestNewReleases,
    getMostLovedTracks: getMostLovedTracks,
    getFeelingLuckyTracks: getFeelingLuckyTracks,
    getTopFolloweeSaves: getTopFolloweeSaves,
    getLatest: getLatest,
    getTopCreatorsByGenres: getTopCreatorsByGenres,
    getURSMContentNodes: getURSMContentNodes,
    getNotifications: getNotifications,
    getUserNotifications: getUserNotifications,
    getUserSubscribers: getUserSubscribers,
    bulkGetUserSubscribers: bulkGetUserSubscribers,
    getCIDData: getCIDData,
    getSolanaNotifications: getSolanaNotifications,
    getTrackListenMilestones: getTrackListenMilestones,
    getChallengeAttestation: getChallengeAttestation,
    getCreateSenderAttestation: getCreateSenderAttestation,
    getUndisbursedChallenges: getUndisbursedChallenges,
    verifyToken: verifyToken,
    getUserReplicaSet: getUserReplicaSet,
    getUnclaimedId: getUnclaimedId,
    getUserListenCountsMonthly: getUserListenCountsMonthly
});

/**
 * Converts a BN to a Uint8Array of length 8, in little endian notation.
 * Useful for when Rust wants a u64 (8 * 8) represented as a byte array.
 * Ex: https://github.com/AudiusProject/audius-protocol/blob/main/solana-programs/reward-manager/program/src/processor.rs#L389
 */
var padBNToUint8Array = function padBNToUint8Array(bn) {
  return bn.toArray('le', 8);
};

var SolanaUtils = /*#__PURE__*/function () {
  function SolanaUtils() {
    _classCallCheck(this, SolanaUtils);
  }
  _createClass(SolanaUtils, null, [{
    key: "signBytes",
    value:
    /**
     * Signs arbitrary bytes
     */
    function signBytes(bytes, ethPrivateKey) {
      var msgHash = keccak256(bytes);
      var ethPrivateKeyArr = Buffer.from(ethPrivateKey, 'hex');
      var signatureObj = secp256k1.ecdsaSign(Uint8Array.from(msgHash), ethPrivateKeyArr);
      var signature = Buffer.from(signatureObj.signature);
      return {
        signature: signature,
        recoveryId: signatureObj.recid
      };
    }
    /**
     * Puts an instruction in a serializable form that our relay can understand.
     * Note we are faking the return type for callers to work with it easier
     */
  }, {
    key: "prepareInstructionForRelay",
    value: function prepareInstructionForRelay(instruction) {
      return {
        programId: instruction.programId.toString(),
        data: instruction.data,
        keys: instruction.keys.map(function (_ref) {
          var isSigner = _ref.isSigner,
            pubkey = _ref.pubkey,
            isWritable = _ref.isWritable;
          return {
            pubkey: pubkey.toString(),
            isSigner: isSigner,
            isWritable: isWritable
          };
        })
      };
    }
    /**
     * Constructs a transfer ID
     */
  }, {
    key: "constructTransferId",
    value: function constructTransferId(challengeId, specifier) {
      return "".concat(challengeId, ":").concat(specifier);
    }
    /**
     * Constructs an attestation from inputs.
     */
  }, {
    key: "constructAttestation",
    value: function constructAttestation(recipientEthAddress, tokenAmount, transferId, oracleAddress) {
      var encoder = new TextEncoder();
      var userBytes = SolanaUtils.ethAddressToArray(recipientEthAddress);
      var transferIdBytes = encoder.encode(transferId);
      var amountBytes = padBNToUint8Array(tokenAmount);
      var items = oracleAddress ? [userBytes, amountBytes, transferIdBytes, SolanaUtils.ethAddressToArray(oracleAddress)] : [userBytes, amountBytes, transferIdBytes];
      var sep = encoder.encode('_');
      var res = items.slice(1).reduce(function (prev, cur) {
        return Uint8Array.of.apply(Uint8Array, _toConsumableArray(prev).concat(_toConsumableArray(sep), _toConsumableArray(cur)));
      }, Uint8Array.from(items[0]));
      return res;
    }
    /**
     * Converts "UI" wAudio (i.e. 5) into properly denominated BN representation - (i.e. 5 * 10 ^ 8)
     */
  }, {
    key: "uiAudioToBNWaudio",
    value: function uiAudioToBNWaudio(amount) {
      return new BN(amount * Math.pow(10, WAUDIO_DECMIALS));
    }
    /**
     * Derives a program address from a program ID and pubkey as seed.
     * Optionally takes in seeds.
     * Returns the new pubkey and bump seeds.
     */
  }, {
    key: "findProgramAddressFromPubkey",
    value: function () {
      var _findProgramAddressFromPubkey = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(programId, pubkey, seed) {
        var seedsArr;
        return _regeneratorRuntime().wrap(function _callee$(_context) {
          while (1) switch (_context.prev = _context.next) {
            case 0:
              seedsArr = [pubkey.toBytes().slice(0, 32)];
              if (seed) {
                seedsArr.push(seed);
              }
              _context.next = 4;
              return PublicKey.findProgramAddress(seedsArr, programId);
            case 4:
              return _context.abrupt("return", _context.sent);
            case 5:
            case "end":
              return _context.stop();
          }
        }, _callee);
      }));
      function findProgramAddressFromPubkey(_x, _x2, _x3) {
        return _findProgramAddressFromPubkey.apply(this, arguments);
      }
      return findProgramAddressFromPubkey;
    }()
    /**
     * Finds a program address, using both seeds, pubkey, and the derived authority.
     * Return [authority, derivedAddress, and bumpSeeds]
     *
     */
  }, {
    key: "findProgramAddressWithAuthority",
    value: function () {
      var _findProgramAddressWithAuthority = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(programId, address, seed) {
        var _yield$SolanaUtils$fi, _yield$SolanaUtils$fi2, authority, _yield$SolanaUtils$fi3, _yield$SolanaUtils$fi4, derivedAddress, bumpSeed;
        return _regeneratorRuntime().wrap(function _callee2$(_context2) {
          while (1) switch (_context2.prev = _context2.next) {
            case 0:
              _context2.next = 2;
              return SolanaUtils.findProgramAddressFromPubkey(programId, address);
            case 2:
              _yield$SolanaUtils$fi = _context2.sent;
              _yield$SolanaUtils$fi2 = _slicedToArray(_yield$SolanaUtils$fi, 1);
              authority = _yield$SolanaUtils$fi2[0];
              _context2.next = 7;
              return SolanaUtils.findProgramAddressFromPubkey(programId, authority, seed);
            case 7:
              _yield$SolanaUtils$fi3 = _context2.sent;
              _yield$SolanaUtils$fi4 = _slicedToArray(_yield$SolanaUtils$fi3, 2);
              derivedAddress = _yield$SolanaUtils$fi4[0];
              bumpSeed = _yield$SolanaUtils$fi4[1];
              return _context2.abrupt("return", [authority, derivedAddress, bumpSeed]);
            case 12:
            case "end":
              return _context2.stop();
          }
        }, _callee2);
      }));
      function findProgramAddressWithAuthority(_x4, _x5, _x6) {
        return _findProgramAddressWithAuthority.apply(this, arguments);
      }
      return findProgramAddressWithAuthority;
    }()
    /**
     * Converts an eth address hex represenatation to an array of Uint8s in big endian notation
     * @param ethAddress
     */
  }, {
    key: "ethAddressToArray",
    value: function ethAddressToArray(ethAddress) {
      var strippedEthAddress = ethAddress.replace('0x', '');
      // Need to pad the array to length 20 - otherwise, hex eth keys starting with '0' would
      // result in truncated arrays, while eth spec is always 20 bytes
      return Uint8Array.of.apply(Uint8Array, _toConsumableArray(new BN(strippedEthAddress, 'hex').toArray('be', 20)));
    }
    // Safely create pubkey from nullable val
  }, {
    key: "newPublicKeyNullable",
    value: function newPublicKeyNullable(val) {
      return val ? new PublicKey(val) : null;
    }
  }]);
  return SolanaUtils;
}();

/**
 * Handles sending Solana transactions, either directly via `sendAndConfirmTransaction`,
 * or via IdentityService's relay.
 */
var TransactionHandler = /*#__PURE__*/function () {
  /**
   * Creates an instance of TransactionHandler.
   */
  function TransactionHandler(_ref) {
    var connection = _ref.connection,
      useRelay = _ref.useRelay,
      _ref$identityService = _ref.identityService,
      identityService = _ref$identityService === void 0 ? null : _ref$identityService,
      _ref$feePayerKeypairs = _ref.feePayerKeypairs,
      feePayerKeypairs = _ref$feePayerKeypairs === void 0 ? null : _ref$feePayerKeypairs,
      _ref$skipPreflight = _ref.skipPreflight,
      skipPreflight = _ref$skipPreflight === void 0 ? true : _ref$skipPreflight,
      _ref$retryTimeoutMs = _ref.retryTimeoutMs,
      retryTimeoutMs = _ref$retryTimeoutMs === void 0 ? 60000 : _ref$retryTimeoutMs,
      _ref$pollingFrequency = _ref.pollingFrequencyMs,
      pollingFrequencyMs = _ref$pollingFrequency === void 0 ? 300 : _ref$pollingFrequency,
      _ref$sendingFrequency = _ref.sendingFrequencyMs,
      sendingFrequencyMs = _ref$sendingFrequency === void 0 ? 300 : _ref$sendingFrequency;
    _classCallCheck(this, TransactionHandler);
    _defineProperty(this, "connection", void 0);
    _defineProperty(this, "useRelay", void 0);
    _defineProperty(this, "identityService", void 0);
    _defineProperty(this, "feePayerKeypairs", void 0);
    _defineProperty(this, "skipPreflight", void 0);
    _defineProperty(this, "retryTimeoutMs", void 0);
    _defineProperty(this, "pollingFrequencyMs", void 0);
    _defineProperty(this, "sendingFrequencyMs", void 0);
    this.connection = connection;
    this.useRelay = useRelay;
    this.identityService = identityService;
    this.feePayerKeypairs = feePayerKeypairs;
    this.skipPreflight = skipPreflight;
    this.retryTimeoutMs = retryTimeoutMs;
    this.pollingFrequencyMs = pollingFrequencyMs;
    this.sendingFrequencyMs = sendingFrequencyMs;
  }
  /**
   * Primary method to send a Solana transaction.
   */
  _createClass(TransactionHandler, [{
    key: "handleTransaction",
    value: function () {
      var _handleTransaction = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(_ref2) {
        var instructions, _ref2$errorMapping, errorMapping, _ref2$recentBlockhash, recentBlockhash, _ref2$logger, logger, _ref2$skipPreflight, skipPreflight, _ref2$feePayerOverrid, feePayerOverride, _ref2$sendBlockhash, sendBlockhash, _ref2$signatures, signatures, _ref2$lookupTableAddr, lookupTableAddresses, _ref2$retry, retry, result;
        return _regeneratorRuntime().wrap(function _callee$(_context) {
          while (1) switch (_context.prev = _context.next) {
            case 0:
              instructions = _ref2.instructions, _ref2$errorMapping = _ref2.errorMapping, errorMapping = _ref2$errorMapping === void 0 ? null : _ref2$errorMapping, _ref2$recentBlockhash = _ref2.recentBlockhash, recentBlockhash = _ref2$recentBlockhash === void 0 ? null : _ref2$recentBlockhash, _ref2$logger = _ref2.logger, logger = _ref2$logger === void 0 ? console : _ref2$logger, _ref2$skipPreflight = _ref2.skipPreflight, skipPreflight = _ref2$skipPreflight === void 0 ? false : _ref2$skipPreflight, _ref2$feePayerOverrid = _ref2.feePayerOverride, feePayerOverride = _ref2$feePayerOverrid === void 0 ? null : _ref2$feePayerOverrid, _ref2$sendBlockhash = _ref2.sendBlockhash, sendBlockhash = _ref2$sendBlockhash === void 0 ? false : _ref2$sendBlockhash, _ref2$signatures = _ref2.signatures, signatures = _ref2$signatures === void 0 ? null : _ref2$signatures, _ref2$lookupTableAddr = _ref2.lookupTableAddresses, lookupTableAddresses = _ref2$lookupTableAddr === void 0 ? [] : _ref2$lookupTableAddr, _ref2$retry = _ref2.retry, retry = _ref2$retry === void 0 ? true : _ref2$retry;
              result = null;
              if (!this.useRelay) {
                _context.next = 8;
                break;
              }
              _context.next = 5;
              return this._relayTransaction(instructions, recentBlockhash, skipPreflight, feePayerOverride, sendBlockhash, signatures, retry);
            case 5:
              result = _context.sent;
              _context.next = 11;
              break;
            case 8:
              _context.next = 10;
              return this._locallyConfirmTransaction(instructions, recentBlockhash, logger, skipPreflight, feePayerOverride, signatures, lookupTableAddresses, retry);
            case 10:
              result = _context.sent;
            case 11:
              if (result.error && result.errorCode !== null && errorMapping) {
                result.errorCode = errorMapping.fromErrorCode(result.errorCode);
              }
              return _context.abrupt("return", result);
            case 13:
            case "end":
              return _context.stop();
          }
        }, _callee, this);
      }));
      function handleTransaction(_x) {
        return _handleTransaction.apply(this, arguments);
      }
      return handleTransaction;
    }()
  }, {
    key: "_relayTransaction",
    value: function () {
      var _relayTransaction2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(instructions, recentBlockhash, skipPreflight) {
        var feePayerOverride,
          sendBlockhash,
          signatures,
          retry,
          relayable,
          transactionData,
          _this$identityService,
          _response$transaction,
          response,
          error,
          _e$response,
          _e$response$data,
          errorCode,
          _args2 = arguments;
        return _regeneratorRuntime().wrap(function _callee2$(_context2) {
          while (1) switch (_context2.prev = _context2.next) {
            case 0:
              feePayerOverride = _args2.length > 3 && _args2[3] !== undefined ? _args2[3] : null;
              sendBlockhash = _args2.length > 4 ? _args2[4] : undefined;
              signatures = _args2.length > 5 ? _args2[5] : undefined;
              retry = _args2.length > 6 ? _args2[6] : undefined;
              relayable = instructions.map(SolanaUtils.prepareInstructionForRelay);
              transactionData = {
                signatures: signatures,
                instructions: relayable,
                skipPreflight: skipPreflight === null ? this.skipPreflight : skipPreflight,
                feePayerOverride: feePayerOverride ? feePayerOverride.toString() : null,
                retry: retry
              };
              if (!(sendBlockhash || Array.isArray(signatures))) {
                _context2.next = 15;
                break;
              }
              if (!(recentBlockhash !== null && recentBlockhash !== void 0)) {
                _context2.next = 11;
                break;
              }
              _context2.t0 = recentBlockhash;
              _context2.next = 14;
              break;
            case 11:
              _context2.next = 13;
              return this.connection.getLatestBlockhash('confirmed');
            case 13:
              _context2.t0 = _context2.sent.blockhash;
            case 14:
              transactionData.recentBlockhash = _context2.t0;
            case 15:
              _context2.prev = 15;
              _context2.next = 18;
              return (_this$identityService = this.identityService) === null || _this$identityService === void 0 ? void 0 : _this$identityService.solanaRelay(transactionData);
            case 18:
              response = _context2.sent;
              return _context2.abrupt("return", {
                res: (_response$transaction = response === null || response === void 0 ? void 0 : response.transactionSignature) !== null && _response$transaction !== void 0 ? _response$transaction : null,
                error: null,
                errorCode: null
              });
            case 22:
              _context2.prev = 22;
              _context2.t1 = _context2["catch"](15);
              error = null;
              if (_typeof(_context2.t1) === 'object' && _context2.t1 !== null) {
                error = ((_e$response = _context2.t1.response) === null || _e$response === void 0 ? void 0 : (_e$response$data = _e$response.data) === null || _e$response$data === void 0 ? void 0 : _e$response$data.error) || _context2.t1.message;
              }
              errorCode = error ? this._parseSolanaErrorCode(error) : null;
              return _context2.abrupt("return", {
                res: null,
                error: error,
                errorCode: errorCode
              });
            case 28:
            case "end":
              return _context2.stop();
          }
        }, _callee2, this, [[15, 22]]);
      }));
      function _relayTransaction(_x2, _x3, _x4) {
        return _relayTransaction2.apply(this, arguments);
      }
      return _relayTransaction;
    }()
  }, {
    key: "_locallyConfirmTransaction",
    value: function () {
      var _locallyConfirmTransaction2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee5(instructions, recentBlockhash, logger, skipPreflight) {
        var _this = this,
          _this$feePayerKeypair,
          _recentBlockhash;
        var feePayerOverride,
          signatures,
          lookupTableAddresses,
          retry,
          feePayerKeypairOverride,
          feePayerAccount,
          rawTransaction,
          lookupTableAccounts,
          _iterator,
          _step,
          address,
          lookupTableAccount,
          message,
          tx,
          _tx,
          sendRawTransaction,
          txid,
          errorCode,
          error,
          done,
          sendCount,
          startTime,
          _errorCode,
          _error,
          _args5 = arguments;
        return _regeneratorRuntime().wrap(function _callee5$(_context5) {
          while (1) switch (_context5.prev = _context5.next) {
            case 0:
              feePayerOverride = _args5.length > 4 && _args5[4] !== undefined ? _args5[4] : null;
              signatures = _args5.length > 5 && _args5[5] !== undefined ? _args5[5] : null;
              lookupTableAddresses = _args5.length > 6 ? _args5[6] : undefined;
              retry = _args5.length > 7 && _args5[7] !== undefined ? _args5[7] : true;
              feePayerKeypairOverride = function () {
                if (feePayerOverride && _this.feePayerKeypairs) {
                  var stringFeePayer = feePayerOverride.toString();
                  return _this.feePayerKeypairs.find(function (keypair) {
                    return keypair.publicKey.toString() === stringFeePayer;
                  });
                }
                return null;
              }();
              feePayerAccount = feePayerKeypairOverride !== null && feePayerKeypairOverride !== void 0 ? feePayerKeypairOverride : (_this$feePayerKeypair = this.feePayerKeypairs) === null || _this$feePayerKeypair === void 0 ? void 0 : _this$feePayerKeypair[0];
              if (feePayerAccount) {
                _context5.next = 9;
                break;
              }
              logger.error('transactionHandler: Local feepayer keys missing for direct confirmation!');
              return _context5.abrupt("return", {
                res: null,
                error: 'Missing keys',
                errorCode: null
              });
            case 9:
              if (!((_recentBlockhash = recentBlockhash) !== null && _recentBlockhash !== void 0)) {
                _context5.next = 13;
                break;
              }
              _context5.t0 = _recentBlockhash;
              _context5.next = 16;
              break;
            case 13:
              _context5.next = 15;
              return this.connection.getLatestBlockhash('confirmed');
            case 15:
              _context5.t0 = _context5.sent.blockhash;
            case 16:
              recentBlockhash = _context5.t0;
              if (!(lookupTableAddresses.length > 0)) {
                _context5.next = 51;
                break;
              }
              // Use v0 transaction if lookup table addresses were supplied
              lookupTableAccounts = []; // Need to use for loop instead of forEach to properly await async calls
              _iterator = _createForOfIteratorHelper(lookupTableAddresses);
              _context5.prev = 20;
              _iterator.s();
            case 22:
              if ((_step = _iterator.n()).done) {
                _context5.next = 36;
                break;
              }
              address = _step.value;
              if (!(address === undefined)) {
                _context5.next = 26;
                break;
              }
              return _context5.abrupt("continue", 34);
            case 26:
              _context5.next = 28;
              return this.connection.getAddressLookupTable(new PublicKey(address));
            case 28:
              lookupTableAccount = _context5.sent;
              if (!(lookupTableAccount.value !== null)) {
                _context5.next = 33;
                break;
              }
              lookupTableAccounts.push(lookupTableAccount.value);
              _context5.next = 34;
              break;
            case 33:
              return _context5.abrupt("return", {
                res: null,
                error: "Missing lookup table account for address ".concat(address),
                errorCode: null
              });
            case 34:
              _context5.next = 22;
              break;
            case 36:
              _context5.next = 41;
              break;
            case 38:
              _context5.prev = 38;
              _context5.t1 = _context5["catch"](20);
              _iterator.e(_context5.t1);
            case 41:
              _context5.prev = 41;
              _iterator.f();
              return _context5.finish(41);
            case 44:
              message = new TransactionMessage({
                payerKey: feePayerAccount.publicKey,
                recentBlockhash: recentBlockhash,
                instructions: instructions
              }).compileToV0Message(lookupTableAccounts);
              tx = new VersionedTransaction(message);
              tx.sign([feePayerAccount]);
              if (Array.isArray(signatures)) {
                signatures.forEach(function (_ref3) {
                  var publicKey = _ref3.publicKey,
                    signature = _ref3.signature;
                  tx.addSignature(new PublicKey(publicKey), signature);
                });
              }
              rawTransaction = tx.serialize();
              _context5.next = 58;
              break;
            case 51:
              // Otherwise send a legacy transaction
              _tx = new Transaction();
              _tx.recentBlockhash = recentBlockhash;
              instructions.forEach(function (i) {
                return _tx.add(i);
              });
              _tx.feePayer = feePayerAccount.publicKey;
              _tx.sign(feePayerAccount);
              if (Array.isArray(signatures)) {
                signatures.forEach(function (_ref4) {
                  var publicKey = _ref4.publicKey,
                    signature = _ref4.signature;
                  _tx.addSignature(new PublicKey(publicKey), signature);
                });
              }
              rawTransaction = _tx.serialize();
            case 58:
              // Send the txn
              sendRawTransaction = /*#__PURE__*/function () {
                var _ref5 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3() {
                  return _regeneratorRuntime().wrap(function _callee3$(_context3) {
                    while (1) switch (_context3.prev = _context3.next) {
                      case 0:
                        _context3.next = 2;
                        return _this.connection.sendRawTransaction(rawTransaction, {
                          skipPreflight: skipPreflight === null ? _this.skipPreflight : skipPreflight,
                          preflightCommitment: 'processed',
                          maxRetries: retry ? 0 : undefined
                        });
                      case 2:
                        return _context3.abrupt("return", _context3.sent);
                      case 3:
                      case "end":
                        return _context3.stop();
                    }
                  }, _callee3);
                }));
                return function sendRawTransaction() {
                  return _ref5.apply(this, arguments);
                };
              }();
              _context5.prev = 59;
              _context5.next = 62;
              return sendRawTransaction();
            case 62:
              txid = _context5.sent;
              _context5.next = 72;
              break;
            case 65:
              _context5.prev = 65;
              _context5.t2 = _context5["catch"](59);
              // Rarely, this intiial send will fail
              logger.warn("transactionHandler: Initial send failed: ".concat(_context5.t2));
              errorCode = null;
              error = null;
              if (_context5.t2 instanceof Error) {
                error = _context5.t2.message;
                errorCode = this._parseSolanaErrorCode(error);
              }
              return _context5.abrupt("return", {
                res: null,
                error: error,
                errorCode: errorCode
              });
            case 72:
              done = false; // Start up resubmission loop
              sendCount = 0;
              startTime = Date.now();
              if (retry) {
                _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee4() {
                  var elapsed;
                  return _regeneratorRuntime().wrap(function _callee4$(_context4) {
                    while (1) switch (_context4.prev = _context4.next) {
                      case 0:
                        elapsed = Date.now() - startTime; // eslint-disable-next-line no-unmodified-loop-condition
                      case 1:
                        if (!(!done && elapsed < _this.retryTimeoutMs)) {
                          _context4.next = 9;
                          break;
                        }
                        try {
                          sendRawTransaction();
                        } catch (e) {
                          logger.warn("transactionHandler: error in send loop: ".concat(e, " for txId ").concat(txid));
                        }
                        sendCount++;
                        _context4.next = 6;
                        return delay(_this.sendingFrequencyMs);
                      case 6:
                        elapsed = Date.now() - startTime;
                        _context4.next = 1;
                        break;
                      case 9:
                      case "end":
                        return _context4.stop();
                    }
                  }, _callee4);
                }))();
              }
              // Await for tx confirmation
              _context5.prev = 76;
              _context5.next = 79;
              return this._awaitTransactionSignatureConfirmation(txid, logger);
            case 79:
              done = true;
              logger.info("transactionHandler: finished for txid ".concat(txid, " with ").concat(sendCount, " retries"));
              return _context5.abrupt("return", {
                res: txid,
                error: null,
                errorCode: null
              });
            case 84:
              _context5.prev = 84;
              _context5.t3 = _context5["catch"](76);
              logger.warn("transactionHandler: error in awaitTransactionSignature: ".concat(JSON.stringify(_context5.t3), ", ").concat(txid));
              done = true;
              _errorCode = null;
              _error = null;
              if (_context5.t3 instanceof Error) {
                _error = _context5.t3.message;
                _errorCode = this._parseSolanaErrorCode(_error);
              }
              return _context5.abrupt("return", {
                res: null,
                error: _error,
                errorCode: _errorCode
              });
            case 92:
            case "end":
              return _context5.stop();
          }
        }, _callee5, this, [[20, 38, 41, 44], [59, 65], [76, 84]]);
      }));
      function _locallyConfirmTransaction(_x5, _x6, _x7, _x8) {
        return _locallyConfirmTransaction2.apply(this, arguments);
      }
      return _locallyConfirmTransaction;
    }()
  }, {
    key: "_awaitTransactionSignatureConfirmation",
    value: function () {
      var _awaitTransactionSignatureConfirmation2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee8(txid, logger) {
        var _this2 = this;
        var done, result;
        return _regeneratorRuntime().wrap(function _callee8$(_context8) {
          while (1) switch (_context8.prev = _context8.next) {
            case 0:
              done = false;
              _context8.next = 3;
              return new Promise(function (resolve, reject) {
                _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee7() {
                  return _regeneratorRuntime().wrap(function _callee7$(_context7) {
                    while (1) switch (_context7.prev = _context7.next) {
                      case 0:
                        // Setup timeout if nothing else finishes
                        setTimeout(function () {
                          if (done) {
                            return;
                          }
                          done = true;
                          var message = "transactionHandler: Timed out in await, ".concat(txid);
                          logger.warn(message);
                          reject(new Error(message));
                        }, _this2.retryTimeoutMs);
                        // Setup WS listener
                        try {
                          _this2.connection.onSignature(txid, function (result) {
                            if (done) return;
                            done = true;
                            if (result.err) {
                              var err = JSON.stringify(result.err);
                              logger.warn("transactionHandler: Error in onSignature ".concat(txid, ", ").concat(err));
                              reject(new Error(err));
                            } else {
                              resolve(txid);
                            }
                          }, 'processed');
                        } catch (e) {
                          done = true;
                          logger.error("transactionHandler: WS error in setup ".concat(txid, ", ").concat(e));
                        }
                        // Setup polling
                      case 2:
                        if (done) {
                          _context7.next = 9;
                          break;
                        }
                        _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee6() {
                          var signatureStatuses, _result, err;
                          return _regeneratorRuntime().wrap(function _callee6$(_context6) {
                            while (1) switch (_context6.prev = _context6.next) {
                              case 0:
                                _context6.prev = 0;
                                _context6.next = 3;
                                return _this2.connection.getSignatureStatuses([txid]);
                              case 3:
                                signatureStatuses = _context6.sent;
                                _result = signatureStatuses === null || signatureStatuses === void 0 ? void 0 : signatureStatuses.value[0]; // Early return this iteration if already done, or no result
                                if (!(done || !_result)) {
                                  _context6.next = 7;
                                  break;
                                }
                                return _context6.abrupt("return");
                              case 7:
                                if (!_result.err) {
                                  _context6.next = 13;
                                  break;
                                }
                                err = JSON.stringify(_result.err);
                                logger.error("transactionHandler: polling saw result error: ".concat(err, ", tx: ").concat(txid));
                                done = true;
                                reject(new Error(err));
                                return _context6.abrupt("return");
                              case 13:
                                if (_result.confirmations !== null && _result.confirmations !== 0 || _result.confirmationStatus === 'confirmed' || _result.confirmationStatus === 'finalized') {
                                  _context6.next = 15;
                                  break;
                                }
                                return _context6.abrupt("return");
                              case 15:
                                // Otherwise, we made it
                                done = true;
                                resolve(txid);
                                _context6.next = 22;
                                break;
                              case 19:
                                _context6.prev = 19;
                                _context6.t0 = _context6["catch"](0);
                                if (!done) {
                                  logger.error("transactionHandler: REST polling connection error: ".concat(_context6.t0, ", tx: ").concat(txid));
                                }
                              case 22:
                              case "end":
                                return _context6.stop();
                            }
                          }, _callee6, null, [[0, 19]]);
                        }))();
                        _context7.next = 7;
                        return delay(_this2.pollingFrequencyMs);
                      case 7:
                        _context7.next = 2;
                        break;
                      case 9:
                      case "end":
                        return _context7.stop();
                    }
                  }, _callee7);
                }))();
              });
            case 3:
              result = _context8.sent;
              done = true;
              return _context8.abrupt("return", result);
            case 6:
            case "end":
              return _context8.stop();
          }
        }, _callee8);
      }));
      function _awaitTransactionSignatureConfirmation(_x9, _x10) {
        return _awaitTransactionSignatureConfirmation2.apply(this, arguments);
      }
      return _awaitTransactionSignatureConfirmation;
    }()
    /**
     * Attempts to parse an error code out of a message of the form:
     * "... custom program error: 0x1", where the return in this case would be the number 1.
     * Returns null for unparsable strings.
     */
  }, {
    key: "_parseSolanaErrorCode",
    value: function _parseSolanaErrorCode(errorMessage) {
      if (!errorMessage) return null;
      // Match on custom solana program errors
      var matcher = /(?:custom program error: 0x)(.*)$/;
      var res = errorMessage.match(matcher);
      if (res && res.length === 2) return res[1] ? parseInt(res[1], 16) || null : null;
      // Match on custom anchor errors
      var matcher2 = /(?:"Custom":)(\d+)/;
      var res2 = errorMessage.match(matcher2);
      if (res2 && res2.length === 2) return res2[1] ? parseInt(res2[1], 10) || null : null;
      return null;
    }
  }]);
  return TransactionHandler;
}();
function delay(_x11) {
  return _delay.apply(this, arguments);
}
function _delay() {
  _delay = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee9(ms) {
    return _regeneratorRuntime().wrap(function _callee9$(_context9) {
      while (1) switch (_context9.prev = _context9.next) {
        case 0:
          _context9.next = 2;
          return new Promise(function (resolve) {
            return setTimeout(resolve, ms);
          });
        case 2:
          return _context9.abrupt("return", _context9.sent);
        case 3:
        case "end":
          return _context9.stop();
      }
    }, _callee9);
  }));
  return _delay.apply(this, arguments);
}

export { AUDIO_DECMIALS, AuthHeaders, CURRENT_USER_EXISTS_LOCAL_STORAGE_KEY, requests as DiscoveryAPI, requests$1 as IdentityAPI, TransactionHandler, WAUDIO_DECMIALS };
//# sourceMappingURL=core.js.map
