UNPKG

starknetkit

Version:

<!-- logo --> <p align="center"> <img width='300' src="https://starknetkit-website-git-blo-1541-argentlabs.vercel.app/starknetKit-logo.svg"> </p>

13,266 lines 536 kB
var Ed = Object.defineProperty;
var _d = (t, e, i) => e in t ? Ed(t, e, { enumerable: !0, configurable: !0, writable: !0, value: i }) : t[e] = i;
var W = (t, e, i) => (_d(t, typeof e != "symbol" ? e + "" : e, i), i);
import { f as ch, g as xd, c as Ui } from "./connector-4bc69b15.js";
import { d as Id, a as Sd, L as hi, M as Dd, g as Ad } from "./Modal-897c4ec2.js";
import { constants as gi, RpcProvider as uh, Account as $d } from "starknet";
import { a as Od, r as Td } from "./index-42161a8d.js";
var zo = { exports: {} }, Gi = typeof Reflect == "object" ? Reflect : null, Fa = Gi && typeof Gi.apply == "function" ? Gi.apply : function(e, i, r) {
  return Function.prototype.apply.call(e, i, r);
}, _s;
Gi && typeof Gi.ownKeys == "function" ? _s = Gi.ownKeys : Object.getOwnPropertySymbols ? _s = function(e) {
  return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e));
} : _s = function(e) {
  return Object.getOwnPropertyNames(e);
};
function Cd(t) {
  console && console.warn && console.warn(t);
}
var hh = Number.isNaN || function(e) {
  return e !== e;
};
function oe() {
  oe.init.call(this);
}
zo.exports = oe;
zo.exports.once = Ud;
oe.EventEmitter = oe;
oe.prototype._events = void 0;
oe.prototype._eventsCount = 0;
oe.prototype._maxListeners = void 0;
var Ua = 10;
function Ys(t) {
  if (typeof t != "function")
    throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof t);
}
Object.defineProperty(oe, "defaultMaxListeners", {
  enumerable: !0,
  get: function() {
    return Ua;
  },
  set: function(t) {
    if (typeof t != "number" || t < 0 || hh(t))
      throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received ' + t + ".");
    Ua = t;
  }
});
oe.init = function() {
  (this._events === void 0 || this._events === Object.getPrototypeOf(this)._events) && (this._events = /* @__PURE__ */ Object.create(null), this._eventsCount = 0), this._maxListeners = this._maxListeners || void 0;
};
oe.prototype.setMaxListeners = function(e) {
  if (typeof e != "number" || e < 0 || hh(e))
    throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received ' + e + ".");
  return this._maxListeners = e, this;
};
function lh(t) {
  return t._maxListeners === void 0 ? oe.defaultMaxListeners : t._maxListeners;
}
oe.prototype.getMaxListeners = function() {
  return lh(this);
};
oe.prototype.emit = function(e) {
  for (var i = [], r = 1; r < arguments.length; r++)
    i.push(arguments[r]);
  var s = e === "error", n = this._events;
  if (n !== void 0)
    s = s && n.error === void 0;
  else if (!s)
    return !1;
  if (s) {
    var o;
    if (i.length > 0 && (o = i[0]), o instanceof Error)
      throw o;
    var a = new Error("Unhandled error." + (o ? " (" + o.message + ")" : ""));
    throw a.context = o, a;
  }
  var c = n[e];
  if (c === void 0)
    return !1;
  if (typeof c == "function")
    Fa(c, this, i);
  else
    for (var u = c.length, h = yh(c, u), r = 0; r < u; ++r)
      Fa(h[r], this, i);
  return !0;
};
function fh(t, e, i, r) {
  var s, n, o;
  if (Ys(i), n = t._events, n === void 0 ? (n = t._events = /* @__PURE__ */ Object.create(null), t._eventsCount = 0) : (n.newListener !== void 0 && (t.emit(
    "newListener",
    e,
    i.listener ? i.listener : i
  ), n = t._events), o = n[e]), o === void 0)
    o = n[e] = i, ++t._eventsCount;
  else if (typeof o == "function" ? o = n[e] = r ? [i, o] : [o, i] : r ? o.unshift(i) : o.push(i), s = lh(t), s > 0 && o.length > s && !o.warned) {
    o.warned = !0;
    var a = new Error("Possible EventEmitter memory leak detected. " + o.length + " " + String(e) + " listeners added. Use emitter.setMaxListeners() to increase limit");
    a.name = "MaxListenersExceededWarning", a.emitter = t, a.type = e, a.count = o.length, Cd(a);
  }
  return t;
}
oe.prototype.addListener = function(e, i) {
  return fh(this, e, i, !1);
};
oe.prototype.on = oe.prototype.addListener;
oe.prototype.prependListener = function(e, i) {
  return fh(this, e, i, !0);
};
function Pd() {
  if (!this.fired)
    return this.target.removeListener(this.type, this.wrapFn), this.fired = !0, arguments.length === 0 ? this.listener.call(this.target) : this.listener.apply(this.target, arguments);
}
function dh(t, e, i) {
  var r = { fired: !1, wrapFn: void 0, target: t, type: e, listener: i }, s = Pd.bind(r);
  return s.listener = i, r.wrapFn = s, s;
}
oe.prototype.once = function(e, i) {
  return Ys(i), this.on(e, dh(this, e, i)), this;
};
oe.prototype.prependOnceListener = function(e, i) {
  return Ys(i), this.prependListener(e, dh(this, e, i)), this;
};
oe.prototype.removeListener = function(e, i) {
  var r, s, n, o, a;
  if (Ys(i), s = this._events, s === void 0)
    return this;
  if (r = s[e], r === void 0)
    return this;
  if (r === i || r.listener === i)
    --this._eventsCount === 0 ? this._events = /* @__PURE__ */ Object.create(null) : (delete s[e], s.removeListener && this.emit("removeListener", e, r.listener || i));
  else if (typeof r != "function") {
    for (n = -1, o = r.length - 1; o >= 0; o--)
      if (r[o] === i || r[o].listener === i) {
        a = r[o].listener, n = o;
        break;
      }
    if (n < 0)
      return this;
    n === 0 ? r.shift() : Rd(r, n), r.length === 1 && (s[e] = r[0]), s.removeListener !== void 0 && this.emit("removeListener", e, a || i);
  }
  return this;
};
oe.prototype.off = oe.prototype.removeListener;
oe.prototype.removeAllListeners = function(e) {
  var i, r, s;
  if (r = this._events, r === void 0)
    return this;
  if (r.removeListener === void 0)
    return arguments.length === 0 ? (this._events = /* @__PURE__ */ Object.create(null), this._eventsCount = 0) : r[e] !== void 0 && (--this._eventsCount === 0 ? this._events = /* @__PURE__ */ Object.create(null) : delete r[e]), this;
  if (arguments.length === 0) {
    var n = Object.keys(r), o;
    for (s = 0; s < n.length; ++s)
      o = n[s], o !== "removeListener" && this.removeAllListeners(o);
    return this.removeAllListeners("removeListener"), this._events = /* @__PURE__ */ Object.create(null), this._eventsCount = 0, this;
  }
  if (i = r[e], typeof i == "function")
    this.removeListener(e, i);
  else if (i !== void 0)
    for (s = i.length - 1; s >= 0; s--)
      this.removeListener(e, i[s]);
  return this;
};
function ph(t, e, i) {
  var r = t._events;
  if (r === void 0)
    return [];
  var s = r[e];
  return s === void 0 ? [] : typeof s == "function" ? i ? [s.listener || s] : [s] : i ? Fd(s) : yh(s, s.length);
}
oe.prototype.listeners = function(e) {
  return ph(this, e, !0);
};
oe.prototype.rawListeners = function(e) {
  return ph(this, e, !1);
};
oe.listenerCount = function(t, e) {
  return typeof t.listenerCount == "function" ? t.listenerCount(e) : gh.call(t, e);
};
oe.prototype.listenerCount = gh;
function gh(t) {
  var e = this._events;
  if (e !== void 0) {
    var i = e[t];
    if (typeof i == "function")
      return 1;
    if (i !== void 0)
      return i.length;
  }
  return 0;
}
oe.prototype.eventNames = function() {
  return this._eventsCount > 0 ? _s(this._events) : [];
};
function yh(t, e) {
  for (var i = new Array(e), r = 0; r < e; ++r)
    i[r] = t[r];
  return i;
}
function Rd(t, e) {
  for (; e + 1 < t.length; e++)
    t[e] = t[e + 1];
  t.pop();
}
function Fd(t) {
  for (var e = new Array(t.length), i = 0; i < e.length; ++i)
    e[i] = t[i].listener || t[i];
  return e;
}
function Ud(t, e) {
  return new Promise(function(i, r) {
    function s(o) {
      t.removeListener(e, n), r(o);
    }
    function n() {
      typeof t.removeListener == "function" && t.removeListener("error", s), i([].slice.call(arguments));
    }
    wh(t, e, n, { once: !0 }), e !== "error" && Bd(t, s, { once: !0 });
  });
}
function Bd(t, e, i) {
  typeof t.on == "function" && wh(t, "error", e, i);
}
function wh(t, e, i, r) {
  if (typeof t.on == "function")
    r.once ? t.once(e, i) : t.on(e, i);
  else if (typeof t.addEventListener == "function")
    t.addEventListener(e, function s(n) {
      r.once && t.removeEventListener(e, s), i(n);
    });
  else
    throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type ' + typeof t);
}
var rt = zo.exports;
const mh = /* @__PURE__ */ ch(rt);
var L = {};
/*! *****************************************************************************
Copyright (c) Microsoft Corporation.

Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */
var eo = function(t, e) {
  return eo = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(i, r) {
    i.__proto__ = r;
  } || function(i, r) {
    for (var s in r)
      r.hasOwnProperty(s) && (i[s] = r[s]);
  }, eo(t, e);
};
function Nd(t, e) {
  eo(t, e);
  function i() {
    this.constructor = t;
  }
  t.prototype = e === null ? Object.create(e) : (i.prototype = e.prototype, new i());
}
var to = function() {
  return to = Object.assign || function(e) {
    for (var i, r = 1, s = arguments.length; r < s; r++) {
      i = arguments[r];
      for (var n in i)
        Object.prototype.hasOwnProperty.call(i, n) && (e[n] = i[n]);
    }
    return e;
  }, to.apply(this, arguments);
};
function kd(t, e) {
  var i = {};
  for (var r in t)
    Object.prototype.hasOwnProperty.call(t, r) && e.indexOf(r) < 0 && (i[r] = t[r]);
  if (t != null && typeof Object.getOwnPropertySymbols == "function")
    for (var s = 0, r = Object.getOwnPropertySymbols(t); s < r.length; s++)
      e.indexOf(r[s]) < 0 && Object.prototype.propertyIsEnumerable.call(t, r[s]) && (i[r[s]] = t[r[s]]);
  return i;
}
function Ld(t, e, i, r) {
  var s = arguments.length, n = s < 3 ? e : r === null ? r = Object.getOwnPropertyDescriptor(e, i) : r, o;
  if (typeof Reflect == "object" && typeof Reflect.decorate == "function")
    n = Reflect.decorate(t, e, i, r);
  else
    for (var a = t.length - 1; a >= 0; a--)
      (o = t[a]) && (n = (s < 3 ? o(n) : s > 3 ? o(e, i, n) : o(e, i)) || n);
  return s > 3 && n && Object.defineProperty(e, i, n), n;
}
function Md(t, e) {
  return function(i, r) {
    e(i, r, t);
  };
}
function qd(t, e) {
  if (typeof Reflect == "object" && typeof Reflect.metadata == "function")
    return Reflect.metadata(t, e);
}
function jd(t, e, i, r) {
  function s(n) {
    return n instanceof i ? n : new i(function(o) {
      o(n);
    });
  }
  return new (i || (i = Promise))(function(n, o) {
    function a(h) {
      try {
        u(r.next(h));
      } catch (l) {
        o(l);
      }
    }
    function c(h) {
      try {
        u(r.throw(h));
      } catch (l) {
        o(l);
      }
    }
    function u(h) {
      h.done ? n(h.value) : s(h.value).then(a, c);
    }
    u((r = r.apply(t, e || [])).next());
  });
}
function zd(t, e) {
  var i = { label: 0, sent: function() {
    if (n[0] & 1)
      throw n[1];
    return n[1];
  }, trys: [], ops: [] }, r, s, n, o;
  return o = { next: a(0), throw: a(1), return: a(2) }, typeof Symbol == "function" && (o[Symbol.iterator] = function() {
    return this;
  }), o;
  function a(u) {
    return function(h) {
      return c([u, h]);
    };
  }
  function c(u) {
    if (r)
      throw new TypeError("Generator is already executing.");
    for (; i; )
      try {
        if (r = 1, s && (n = u[0] & 2 ? s.return : u[0] ? s.throw || ((n = s.return) && n.call(s), 0) : s.next) && !(n = n.call(s, u[1])).done)
          return n;
        switch (s = 0, n && (u = [u[0] & 2, n.value]), u[0]) {
          case 0:
          case 1:
            n = u;
            break;
          case 4:
            return i.label++, { value: u[1], done: !1 };
          case 5:
            i.label++, s = u[1], u = [0];
            continue;
          case 7:
            u = i.ops.pop(), i.trys.pop();
            continue;
          default:
            if (n = i.trys, !(n = n.length > 0 && n[n.length - 1]) && (u[0] === 6 || u[0] === 2)) {
              i = 0;
              continue;
            }
            if (u[0] === 3 && (!n || u[1] > n[0] && u[1] < n[3])) {
              i.label = u[1];
              break;
            }
            if (u[0] === 6 && i.label < n[1]) {
              i.label = n[1], n = u;
              break;
            }
            if (n && i.label < n[2]) {
              i.label = n[2], i.ops.push(u);
              break;
            }
            n[2] && i.ops.pop(), i.trys.pop();
            continue;
        }
        u = e.call(t, i);
      } catch (h) {
        u = [6, h], s = 0;
      } finally {
        r = n = 0;
      }
    if (u[0] & 5)
      throw u[1];
    return { value: u[0] ? u[1] : void 0, done: !0 };
  }
}
function Kd(t, e, i, r) {
  r === void 0 && (r = i), t[r] = e[i];
}
function Vd(t, e) {
  for (var i in t)
    i !== "default" && !e.hasOwnProperty(i) && (e[i] = t[i]);
}
function io(t) {
  var e = typeof Symbol == "function" && Symbol.iterator, i = e && t[e], r = 0;
  if (i)
    return i.call(t);
  if (t && typeof t.length == "number")
    return {
      next: function() {
        return t && r >= t.length && (t = void 0), { value: t && t[r++], done: !t };
      }
    };
  throw new TypeError(e ? "Object is not iterable." : "Symbol.iterator is not defined.");
}
function bh(t, e) {
  var i = typeof Symbol == "function" && t[Symbol.iterator];
  if (!i)
    return t;
  var r = i.call(t), s, n = [], o;
  try {
    for (; (e === void 0 || e-- > 0) && !(s = r.next()).done; )
      n.push(s.value);
  } catch (a) {
    o = { error: a };
  } finally {
    try {
      s && !s.done && (i = r.return) && i.call(r);
    } finally {
      if (o)
        throw o.error;
    }
  }
  return n;
}
function Hd() {
  for (var t = [], e = 0; e < arguments.length; e++)
    t = t.concat(bh(arguments[e]));
  return t;
}
function Wd() {
  for (var t = 0, e = 0, i = arguments.length; e < i; e++)
    t += arguments[e].length;
  for (var r = Array(t), s = 0, e = 0; e < i; e++)
    for (var n = arguments[e], o = 0, a = n.length; o < a; o++, s++)
      r[s] = n[o];
  return r;
}
function Br(t) {
  return this instanceof Br ? (this.v = t, this) : new Br(t);
}
function Gd(t, e, i) {
  if (!Symbol.asyncIterator)
    throw new TypeError("Symbol.asyncIterator is not defined.");
  var r = i.apply(t, e || []), s, n = [];
  return s = {}, o("next"), o("throw"), o("return"), s[Symbol.asyncIterator] = function() {
    return this;
  }, s;
  function o(f) {
    r[f] && (s[f] = function(p) {
      return new Promise(function(d, g) {
        n.push([f, p, d, g]) > 1 || a(f, p);
      });
    });
  }
  function a(f, p) {
    try {
      c(r[f](p));
    } catch (d) {
      l(n[0][3], d);
    }
  }
  function c(f) {
    f.value instanceof Br ? Promise.resolve(f.value.v).then(u, h) : l(n[0][2], f);
  }
  function u(f) {
    a("next", f);
  }
  function h(f) {
    a("throw", f);
  }
  function l(f, p) {
    f(p), n.shift(), n.length && a(n[0][0], n[0][1]);
  }
}
function Yd(t) {
  var e, i;
  return e = {}, r("next"), r("throw", function(s) {
    throw s;
  }), r("return"), e[Symbol.iterator] = function() {
    return this;
  }, e;
  function r(s, n) {
    e[s] = t[s] ? function(o) {
      return (i = !i) ? { value: Br(t[s](o)), done: s === "return" } : n ? n(o) : o;
    } : n;
  }
}
function Jd(t) {
  if (!Symbol.asyncIterator)
    throw new TypeError("Symbol.asyncIterator is not defined.");
  var e = t[Symbol.asyncIterator], i;
  return e ? e.call(t) : (t = typeof io == "function" ? io(t) : t[Symbol.iterator](), i = {}, r("next"), r("throw"), r("return"), i[Symbol.asyncIterator] = function() {
    return this;
  }, i);
  function r(n) {
    i[n] = t[n] && function(o) {
      return new Promise(function(a, c) {
        o = t[n](o), s(a, c, o.done, o.value);
      });
    };
  }
  function s(n, o, a, c) {
    Promise.resolve(c).then(function(u) {
      n({ value: u, done: a });
    }, o);
  }
}
function Zd(t, e) {
  return Object.defineProperty ? Object.defineProperty(t, "raw", { value: e }) : t.raw = e, t;
}
function Qd(t) {
  if (t && t.__esModule)
    return t;
  var e = {};
  if (t != null)
    for (var i in t)
      Object.hasOwnProperty.call(t, i) && (e[i] = t[i]);
  return e.default = t, e;
}
function Xd(t) {
  return t && t.__esModule ? t : { default: t };
}
function ep(t, e) {
  if (!e.has(t))
    throw new TypeError("attempted to get private field on non-instance");
  return e.get(t);
}
function tp(t, e, i) {
  if (!e.has(t))
    throw new TypeError("attempted to set private field on non-instance");
  return e.set(t, i), i;
}
const ip = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  get __assign() {
    return to;
  },
  __asyncDelegator: Yd,
  __asyncGenerator: Gd,
  __asyncValues: Jd,
  __await: Br,
  __awaiter: jd,
  __classPrivateFieldGet: ep,
  __classPrivateFieldSet: tp,
  __createBinding: Kd,
  __decorate: Ld,
  __exportStar: Vd,
  __extends: Nd,
  __generator: zd,
  __importDefault: Xd,
  __importStar: Qd,
  __makeTemplateObject: Zd,
  __metadata: qd,
  __param: Md,
  __read: bh,
  __rest: kd,
  __spread: Hd,
  __spreadArrays: Wd,
  __values: io
}, Symbol.toStringTag, { value: "Module" })), Wr = /* @__PURE__ */ xd(ip);
var wn = {}, ar = {}, Ba;
function rp() {
  if (Ba)
    return ar;
  Ba = 1, Object.defineProperty(ar, "__esModule", { value: !0 }), ar.delay = void 0;
  function t(e) {
    return new Promise((i) => {
      setTimeout(() => {
        i(!0);
      }, e);
    });
  }
  return ar.delay = t, ar;
}
var li = {}, mn = {}, fi = {}, Na;
function sp() {
  return Na || (Na = 1, Object.defineProperty(fi, "__esModule", { value: !0 }), fi.ONE_THOUSAND = fi.ONE_HUNDRED = void 0, fi.ONE_HUNDRED = 100, fi.ONE_THOUSAND = 1e3), fi;
}
var bn = {}, ka;
function np() {
  return ka || (ka = 1, function(t) {
    Object.defineProperty(t, "__esModule", { value: !0 }), t.ONE_YEAR = t.FOUR_WEEKS = t.THREE_WEEKS = t.TWO_WEEKS = t.ONE_WEEK = t.THIRTY_DAYS = t.SEVEN_DAYS = t.FIVE_DAYS = t.THREE_DAYS = t.ONE_DAY = t.TWENTY_FOUR_HOURS = t.TWELVE_HOURS = t.SIX_HOURS = t.THREE_HOURS = t.ONE_HOUR = t.SIXTY_MINUTES = t.THIRTY_MINUTES = t.TEN_MINUTES = t.FIVE_MINUTES = t.ONE_MINUTE = t.SIXTY_SECONDS = t.THIRTY_SECONDS = t.TEN_SECONDS = t.FIVE_SECONDS = t.ONE_SECOND = void 0, t.ONE_SECOND = 1, t.FIVE_SECONDS = 5, t.TEN_SECONDS = 10, t.THIRTY_SECONDS = 30, t.SIXTY_SECONDS = 60, t.ONE_MINUTE = t.SIXTY_SECONDS, t.FIVE_MINUTES = t.ONE_MINUTE * 5, t.TEN_MINUTES = t.ONE_MINUTE * 10, t.THIRTY_MINUTES = t.ONE_MINUTE * 30, t.SIXTY_MINUTES = t.ONE_MINUTE * 60, t.ONE_HOUR = t.SIXTY_MINUTES, t.THREE_HOURS = t.ONE_HOUR * 3, t.SIX_HOURS = t.ONE_HOUR * 6, t.TWELVE_HOURS = t.ONE_HOUR * 12, t.TWENTY_FOUR_HOURS = t.ONE_HOUR * 24, t.ONE_DAY = t.TWENTY_FOUR_HOURS, t.THREE_DAYS = t.ONE_DAY * 3, t.FIVE_DAYS = t.ONE_DAY * 5, t.SEVEN_DAYS = t.ONE_DAY * 7, t.THIRTY_DAYS = t.ONE_DAY * 30, t.ONE_WEEK = t.SEVEN_DAYS, t.TWO_WEEKS = t.ONE_WEEK * 2, t.THREE_WEEKS = t.ONE_WEEK * 3, t.FOUR_WEEKS = t.ONE_WEEK * 4, t.ONE_YEAR = t.ONE_DAY * 365;
  }(bn)), bn;
}
var La;
function vh() {
  return La || (La = 1, function(t) {
    Object.defineProperty(t, "__esModule", { value: !0 });
    const e = Wr;
    e.__exportStar(sp(), t), e.__exportStar(np(), t);
  }(mn)), mn;
}
var Ma;
function op() {
  if (Ma)
    return li;
  Ma = 1, Object.defineProperty(li, "__esModule", { value: !0 }), li.fromMiliseconds = li.toMiliseconds = void 0;
  const t = vh();
  function e(r) {
    return r * t.ONE_THOUSAND;
  }
  li.toMiliseconds = e;
  function i(r) {
    return Math.floor(r / t.ONE_THOUSAND);
  }
  return li.fromMiliseconds = i, li;
}
var qa;
function ap() {
  return qa || (qa = 1, function(t) {
    Object.defineProperty(t, "__esModule", { value: !0 });
    const e = Wr;
    e.__exportStar(rp(), t), e.__exportStar(op(), t);
  }(wn)), wn;
}
var Bi = {}, ja;
function cp() {
  if (ja)
    return Bi;
  ja = 1, Object.defineProperty(Bi, "__esModule", { value: !0 }), Bi.Watch = void 0;
  class t {
    constructor() {
      this.timestamps = /* @__PURE__ */ new Map();
    }
    start(i) {
      if (this.timestamps.has(i))
        throw new Error(`Watch already started for label: ${i}`);
      this.timestamps.set(i, { started: Date.now() });
    }
    stop(i) {
      const r = this.get(i);
      if (typeof r.elapsed < "u")
        throw new Error(`Watch already stopped for label: ${i}`);
      const s = Date.now() - r.started;
      this.timestamps.set(i, { started: r.started, elapsed: s });
    }
    get(i) {
      const r = this.timestamps.get(i);
      if (typeof r > "u")
        throw new Error(`No timestamp found for label: ${i}`);
      return r;
    }
    elapsed(i) {
      const r = this.get(i);
      return r.elapsed || Date.now() - r.started;
    }
  }
  return Bi.Watch = t, Bi.default = t, Bi;
}
var vn = {}, cr = {}, za;
function up() {
  if (za)
    return cr;
  za = 1, Object.defineProperty(cr, "__esModule", { value: !0 }), cr.IWatch = void 0;
  class t {
  }
  return cr.IWatch = t, cr;
}
var Ka;
function hp() {
  return Ka || (Ka = 1, function(t) {
    Object.defineProperty(t, "__esModule", { value: !0 }), Wr.__exportStar(up(), t);
  }(vn)), vn;
}
(function(t) {
  Object.defineProperty(t, "__esModule", { value: !0 });
  const e = Wr;
  e.__exportStar(ap(), t), e.__exportStar(cp(), t), e.__exportStar(hp(), t), e.__exportStar(vh(), t);
})(L);
class Oi {
}
let lp = class extends Oi {
  constructor(e) {
    super();
  }
};
const Va = L.FIVE_SECONDS, Ti = { pulse: "heartbeat_pulse" };
let fp = class Eh extends lp {
  constructor(e) {
    super(e), this.events = new rt.EventEmitter(), this.interval = Va, this.interval = e?.interval || Va;
  }
  static async init(e) {
    const i = new Eh(e);
    return await i.init(), i;
  }
  async init() {
    await this.initialize();
  }
  stop() {
    clearInterval(this.intervalRef);
  }
  on(e, i) {
    this.events.on(e, i);
  }
  once(e, i) {
    this.events.once(e, i);
  }
  off(e, i) {
    this.events.off(e, i);
  }
  removeListener(e, i) {
    this.events.removeListener(e, i);
  }
  async initialize() {
    this.intervalRef = setInterval(() => this.pulse(), L.toMiliseconds(this.interval));
  }
  pulse() {
    this.events.emit(Ti.pulse);
  }
};
const dp = /"(?:_|\\u0{2}5[Ff]){2}(?:p|\\u0{2}70)(?:r|\\u0{2}72)(?:o|\\u0{2}6[Ff])(?:t|\\u0{2}74)(?:o|\\u0{2}6[Ff])(?:_|\\u0{2}5[Ff]){2}"\s*:/, pp = /"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/, gp = /^\s*["[{]|^\s*-?\d{1,16}(\.\d{1,17})?([Ee][+-]?\d+)?\s*$/;
function yp(t, e) {
  if (t === "__proto__" || t === "constructor" && e && typeof e == "object" && "prototype" in e) {
    wp(t);
    return;
  }
  return e;
}
function wp(t) {
  console.warn(`[destr] Dropping "${t}" key to prevent prototype pollution.`);
}
function ns(t, e = {}) {
  if (typeof t != "string")
    return t;
  if (t[0] === '"' && t[t.length - 1] === '"' && t.indexOf("\\") === -1)
    return t.slice(1, -1);
  const i = t.trim();
  if (i.length <= 9)
    switch (i.toLowerCase()) {
      case "true":
        return !0;
      case "false":
        return !1;
      case "undefined":
        return;
      case "null":
        return null;
      case "nan":
        return Number.NaN;
      case "infinity":
        return Number.POSITIVE_INFINITY;
      case "-infinity":
        return Number.NEGATIVE_INFINITY;
    }
  if (!gp.test(t)) {
    if (e.strict)
      throw new SyntaxError("[destr] Invalid JSON");
    return t;
  }
  try {
    if (dp.test(t) || pp.test(t)) {
      if (e.strict)
        throw new Error("[destr] Possible prototype pollution");
      return JSON.parse(t, yp);
    }
    return JSON.parse(t);
  } catch (r) {
    if (e.strict)
      throw r;
    return t;
  }
}
function mp(t) {
  return !t || typeof t.then != "function" ? Promise.resolve(t) : t;
}
function _e(t, ...e) {
  try {
    return mp(t(...e));
  } catch (i) {
    return Promise.reject(i);
  }
}
function bp(t) {
  const e = typeof t;
  return t === null || e !== "object" && e !== "function";
}
function vp(t) {
  const e = Object.getPrototypeOf(t);
  return !e || e.isPrototypeOf(Object);
}
function xs(t) {
  if (bp(t))
    return String(t);
  if (vp(t) || Array.isArray(t))
    return JSON.stringify(t);
  if (typeof t.toJSON == "function")
    return xs(t.toJSON());
  throw new Error("[unstorage] Cannot stringify value!");
}
const ro = "base64:";
function Ep(t) {
  return typeof t == "string" ? t : ro + Ip(t);
}
function _p(t) {
  return typeof t != "string" || !t.startsWith(ro) ? t : xp(t.slice(ro.length));
}
function xp(t) {
  return globalThis.Buffer ? Buffer.from(t, "base64") : Uint8Array.from(
    globalThis.atob(t),
    (e) => e.codePointAt(0)
  );
}
function Ip(t) {
  return globalThis.Buffer ? Buffer.from(t).toString("base64") : globalThis.btoa(String.fromCodePoint(...t));
}
function Ve(t) {
  return t && t.split("?")[0]?.replace(/[/\\]/g, ":").replace(/:+/g, ":").replace(/^:|:$/g, "") || "";
}
function Sp(...t) {
  return Ve(t.join(":"));
}
function os(t) {
  return t = Ve(t), t ? t + ":" : "";
}
function Dp(t, e) {
  if (e === void 0)
    return !0;
  let i = 0, r = t.indexOf(":");
  for (; r > -1; )
    i++, r = t.indexOf(":", r + 1);
  return i <= e;
}
function Ap(t, e) {
  return e ? t.startsWith(e) && t[t.length - 1] !== "$" : t[t.length - 1] !== "$";
}
const $p = "memory", Op = () => {
  const t = /* @__PURE__ */ new Map();
  return {
    name: $p,
    getInstance: () => t,
    hasItem(e) {
      return t.has(e);
    },
    getItem(e) {
      return t.get(e) ?? null;
    },
    getItemRaw(e) {
      return t.get(e) ?? null;
    },
    setItem(e, i) {
      t.set(e, i);
    },
    setItemRaw(e, i) {
      t.set(e, i);
    },
    removeItem(e) {
      t.delete(e);
    },
    getKeys() {
      return [...t.keys()];
    },
    clear() {
      t.clear();
    },
    dispose() {
      t.clear();
    }
  };
};
function Tp(t = {}) {
  const e = {
    mounts: { "": t.driver || Op() },
    mountpoints: [""],
    watching: !1,
    watchListeners: [],
    unwatch: {}
  }, i = (u) => {
    for (const h of e.mountpoints)
      if (u.startsWith(h))
        return {
          base: h,
          relativeKey: u.slice(h.length),
          driver: e.mounts[h]
        };
    return {
      base: "",
      relativeKey: u,
      driver: e.mounts[""]
    };
  }, r = (u, h) => e.mountpoints.filter(
    (l) => l.startsWith(u) || h && u.startsWith(l)
  ).map((l) => ({
    relativeBase: u.length > l.length ? u.slice(l.length) : void 0,
    mountpoint: l,
    driver: e.mounts[l]
  })), s = (u, h) => {
    if (e.watching) {
      h = Ve(h);
      for (const l of e.watchListeners)
        l(u, h);
    }
  }, n = async () => {
    if (!e.watching) {
      e.watching = !0;
      for (const u in e.mounts)
        e.unwatch[u] = await Ha(
          e.mounts[u],
          s,
          u
        );
    }
  }, o = async () => {
    if (e.watching) {
      for (const u in e.unwatch)
        await e.unwatch[u]();
      e.unwatch = {}, e.watching = !1;
    }
  }, a = (u, h, l) => {
    const f = /* @__PURE__ */ new Map(), p = (d) => {
      let g = f.get(d.base);
      return g || (g = {
        driver: d.driver,
        base: d.base,
        items: []
      }, f.set(d.base, g)), g;
    };
    for (const d of u) {
      const g = typeof d == "string", y = Ve(g ? d : d.key), E = g ? void 0 : d.value, v = g || !d.options ? h : { ...h, ...d.options }, m = i(y);
      p(m).items.push({
        key: y,
        value: E,
        relativeKey: m.relativeKey,
        options: v
      });
    }
    return Promise.all([...f.values()].map((d) => l(d))).then(
      (d) => d.flat()
    );
  }, c = {
    // Item
    hasItem(u, h = {}) {
      u = Ve(u);
      const { relativeKey: l, driver: f } = i(u);
      return _e(f.hasItem, l, h);
    },
    getItem(u, h = {}) {
      u = Ve(u);
      const { relativeKey: l, driver: f } = i(u);
      return _e(f.getItem, l, h).then(
        (p) => ns(p)
      );
    },
    getItems(u, h = {}) {
      return a(u, h, (l) => l.driver.getItems ? _e(
        l.driver.getItems,
        l.items.map((f) => ({
          key: f.relativeKey,
          options: f.options
        })),
        h
      ).then(
        (f) => f.map((p) => ({
          key: Sp(l.base, p.key),
          value: ns(p.value)
        }))
      ) : Promise.all(
        l.items.map((f) => _e(
          l.driver.getItem,
          f.relativeKey,
          f.options
        ).then((p) => ({
          key: f.key,
          value: ns(p)
        })))
      ));
    },
    getItemRaw(u, h = {}) {
      u = Ve(u);
      const { relativeKey: l, driver: f } = i(u);
      return f.getItemRaw ? _e(f.getItemRaw, l, h) : _e(f.getItem, l, h).then(
        (p) => _p(p)
      );
    },
    async setItem(u, h, l = {}) {
      if (h === void 0)
        return c.removeItem(u);
      u = Ve(u);
      const { relativeKey: f, driver: p } = i(u);
      p.setItem && (await _e(p.setItem, f, xs(h), l), p.watch || s("update", u));
    },
    async setItems(u, h) {
      await a(u, h, async (l) => {
        if (l.driver.setItems)
          return _e(
            l.driver.setItems,
            l.items.map((f) => ({
              key: f.relativeKey,
              value: xs(f.value),
              options: f.options
            })),
            h
          );
        l.driver.setItem && await Promise.all(
          l.items.map((f) => _e(
            l.driver.setItem,
            f.relativeKey,
            xs(f.value),
            f.options
          ))
        );
      });
    },
    async setItemRaw(u, h, l = {}) {
      if (h === void 0)
        return c.removeItem(u, l);
      u = Ve(u);
      const { relativeKey: f, driver: p } = i(u);
      if (p.setItemRaw)
        await _e(p.setItemRaw, f, h, l);
      else if (p.setItem)
        await _e(p.setItem, f, Ep(h), l);
      else
        return;
      p.watch || s("update", u);
    },
    async removeItem(u, h = {}) {
      typeof h == "boolean" && (h = { removeMeta: h }), u = Ve(u);
      const { relativeKey: l, driver: f } = i(u);
      f.removeItem && (await _e(f.removeItem, l, h), (h.removeMeta || h.removeMata) && await _e(f.removeItem, l + "$", h), f.watch || s("remove", u));
    },
    // Meta
    async getMeta(u, h = {}) {
      typeof h == "boolean" && (h = { nativeOnly: h }), u = Ve(u);
      const { relativeKey: l, driver: f } = i(u), p = /* @__PURE__ */ Object.create(null);
      if (f.getMeta && Object.assign(p, await _e(f.getMeta, l, h)), !h.nativeOnly) {
        const d = await _e(
          f.getItem,
          l + "$",
          h
        ).then((g) => ns(g));
        d && typeof d == "object" && (typeof d.atime == "string" && (d.atime = new Date(d.atime)), typeof d.mtime == "string" && (d.mtime = new Date(d.mtime)), Object.assign(p, d));
      }
      return p;
    },
    setMeta(u, h, l = {}) {
      return this.setItem(u + "$", h, l);
    },
    removeMeta(u, h = {}) {
      return this.removeItem(u + "$", h);
    },
    // Keys
    async getKeys(u, h = {}) {
      u = os(u);
      const l = r(u, !0);
      let f = [];
      const p = [];
      let d = !0;
      for (const y of l) {
        y.driver.flags?.maxDepth || (d = !1);
        const E = await _e(
          y.driver.getKeys,
          y.relativeBase,
          h
        );
        for (const v of E) {
          const m = y.mountpoint + Ve(v);
          f.some((D) => m.startsWith(D)) || p.push(m);
        }
        f = [
          y.mountpoint,
          ...f.filter((v) => !v.startsWith(y.mountpoint))
        ];
      }
      const g = h.maxDepth !== void 0 && !d;
      return p.filter(
        (y) => (!g || Dp(y, h.maxDepth)) && Ap(y, u)
      );
    },
    // Utils
    async clear(u, h = {}) {
      u = os(u), await Promise.all(
        r(u, !1).map(async (l) => {
          if (l.driver.clear)
            return _e(l.driver.clear, l.relativeBase, h);
          if (l.driver.removeItem) {
            const f = await l.driver.getKeys(l.relativeBase || "", h);
            return Promise.all(
              f.map((p) => l.driver.removeItem(p, h))
            );
          }
        })
      );
    },
    async dispose() {
      await Promise.all(
        Object.values(e.mounts).map((u) => Wa(u))
      );
    },
    async watch(u) {
      return await n(), e.watchListeners.push(u), async () => {
        e.watchListeners = e.watchListeners.filter(
          (h) => h !== u
        ), e.watchListeners.length === 0 && await o();
      };
    },
    async unwatch() {
      e.watchListeners = [], await o();
    },
    // Mount
    mount(u, h) {
      if (u = os(u), u && e.mounts[u])
        throw new Error(`already mounted at ${u}`);
      return u && (e.mountpoints.push(u), e.mountpoints.sort((l, f) => f.length - l.length)), e.mounts[u] = h, e.watching && Promise.resolve(Ha(h, s, u)).then((l) => {
        e.unwatch[u] = l;
      }).catch(console.error), c;
    },
    async unmount(u, h = !0) {
      u = os(u), !(!u || !e.mounts[u]) && (e.watching && u in e.unwatch && (e.unwatch[u]?.(), delete e.unwatch[u]), h && await Wa(e.mounts[u]), e.mountpoints = e.mountpoints.filter((l) => l !== u), delete e.mounts[u]);
    },
    getMount(u = "") {
      u = Ve(u) + ":";
      const h = i(u);
      return {
        driver: h.driver,
        base: h.base
      };
    },
    getMounts(u = "", h = {}) {
      return u = Ve(u), r(u, h.parents).map((f) => ({
        driver: f.driver,
        base: f.mountpoint
      }));
    },
    // Aliases
    keys: (u, h = {}) => c.getKeys(u, h),
    get: (u, h = {}) => c.getItem(u, h),
    set: (u, h, l = {}) => c.setItem(u, h, l),
    has: (u, h = {}) => c.hasItem(u, h),
    del: (u, h = {}) => c.removeItem(u, h),
    remove: (u, h = {}) => c.removeItem(u, h)
  };
  return c;
}
function Ha(t, e, i) {
  return t.watch ? t.watch((r, s) => e(r, i + s)) : () => {
  };
}
async function Wa(t) {
  typeof t.dispose == "function" && await _e(t.dispose);
}
function Ci(t) {
  return new Promise((e, i) => {
    t.oncomplete = t.onsuccess = () => e(t.result), t.onabort = t.onerror = () => i(t.error);
  });
}
function _h(t, e) {
  let i;
  const r = () => {
    if (i)
      return i;
    const s = indexedDB.open(t);
    return s.onupgradeneeded = () => s.result.createObjectStore(e), i = Ci(s), i.then((n) => {
      n.onclose = () => i = void 0;
    }, () => {
    }), i;
  };
  return (s, n) => r().then((o) => n(o.transaction(e, s).objectStore(e)));
}
let En;
function Gr() {
  return En || (En = _h("keyval-store", "keyval")), En;
}
function Ga(t, e = Gr()) {
  return e("readonly", (i) => Ci(i.get(t)));
}
function Cp(t, e, i = Gr()) {
  return i("readwrite", (r) => (r.put(e, t), Ci(r.transaction)));
}
function Pp(t, e = Gr()) {
  return e("readwrite", (i) => (i.delete(t), Ci(i.transaction)));
}
function Rp(t = Gr()) {
  return t("readwrite", (e) => (e.clear(), Ci(e.transaction)));
}
function Fp(t, e) {
  return t.openCursor().onsuccess = function() {
    this.result && (e(this.result), this.result.continue());
  }, Ci(t.transaction);
}
function Up(t = Gr()) {
  return t("readonly", (e) => {
    if (e.getAllKeys)
      return Ci(e.getAllKeys());
    const i = [];
    return Fp(e, (r) => i.push(r.key)).then(() => i);
  });
}
const Bp = (t) => JSON.stringify(t, (e, i) => typeof i == "bigint" ? i.toString() + "n" : i), Np = (t) => {
  const e = /([\[:])?(\d{17,}|(?:[9](?:[1-9]07199254740991|0[1-9]7199254740991|00[8-9]199254740991|007[2-9]99254740991|007199[3-9]54740991|0071992[6-9]4740991|00719925[5-9]740991|007199254[8-9]40991|0071992547[5-9]0991|00719925474[1-9]991|00719925474099[2-9])))([,\}\]])/g, i = t.replace(e, '$1"$2n"$3');
  return JSON.parse(i, (r, s) => typeof s == "string" && s.match(/^\d+n$/) ? BigInt(s.substring(0, s.length - 1)) : s);
};
function Yi(t) {
  if (typeof t != "string")
    throw new Error(`Cannot safe json parse value of type ${typeof t}`);
  try {
    return Np(t);
  } catch {
    return t;
  }
}
function Ii(t) {
  return typeof t == "string" ? t : Bp(t) || "";
}
const kp = "idb-keyval";
var Lp = (t = {}) => {
  const e = t.base && t.base.length > 0 ? `${t.base}:` : "", i = (s) => e + s;
  let r;
  return t.dbName && t.storeName && (r = _h(t.dbName, t.storeName)), { name: kp, options: t, async hasItem(s) {
    return !(typeof await Ga(i(s), r) > "u");
  }, async getItem(s) {
    return await Ga(i(s), r) ?? null;
  }, setItem(s, n) {
    return Cp(i(s), n, r);
  }, removeItem(s) {
    return Pp(i(s), r);
  }, getKeys() {
    return Up(r);
  }, clear() {
    return Rp(r);
  } };
};
const Mp = "WALLET_CONNECT_V2_INDEXED_DB", qp = "keyvaluestorage";
let jp = class {
  constructor() {
    this.indexedDb = Tp({ driver: Lp({ dbName: Mp, storeName: qp }) });
  }
  async getKeys() {
    return this.indexedDb.getKeys();
  }
  async getEntries() {
    return (await this.indexedDb.getItems(await this.indexedDb.getKeys())).map((e) => [e.key, e.value]);
  }
  async getItem(e) {
    const i = await this.indexedDb.getItem(e);
    if (i !== null)
      return i;
  }
  async setItem(e, i) {
    await this.indexedDb.setItem(e, Ii(i));
  }
  async removeItem(e) {
    await this.indexedDb.removeItem(e);
  }
};
var _n = typeof globalThis < "u" ? globalThis : typeof window < "u" ? window : typeof global < "u" ? global : typeof self < "u" ? self : {}, Is = { exports: {} };
(function() {
  let t;
  function e() {
  }
  t = e, t.prototype.getItem = function(i) {
    return this.hasOwnProperty(i) ? String(this[i]) : null;
  }, t.prototype.setItem = function(i, r) {
    this[i] = String(r);
  }, t.prototype.removeItem = function(i) {
    delete this[i];
  }, t.prototype.clear = function() {
    const i = this;
    Object.keys(i).forEach(function(r) {
      i[r] = void 0, delete i[r];
    });
  }, t.prototype.key = function(i) {
    return i = i || 0, Object.keys(this)[i];
  }, t.prototype.__defineGetter__("length", function() {
    return Object.keys(this).length;
  }), typeof _n < "u" && _n.localStorage ? Is.exports = _n.localStorage : typeof window < "u" && window.localStorage ? Is.exports = window.localStorage : Is.exports = new e();
})();
function zp(t) {
  var e;
  return [t[0], Yi((e = t[1]) != null ? e : "")];
}
let Kp = class {
  constructor() {
    this.localStorage = Is.exports;
  }
  async getKeys() {
    return Object.keys(this.localStorage);
  }
  async getEntries() {
    return Object.entries(this.localStorage).map(zp);
  }
  async getItem(e) {
    const i = this.localStorage.getItem(e);
    if (i !== null)
      return Yi(i);
  }
  async setItem(e, i) {
    this.localStorage.setItem(e, Ii(i));
  }
  async removeItem(e) {
    this.localStorage.removeItem(e);
  }
};
const Vp = "wc_storage_version", Ya = 1, Hp = async (t, e, i) => {
  const r = Vp, s = await e.getItem(r);
  if (s && s >= Ya) {
    i(e);
    return;
  }
  const n = await t.getKeys();
  if (!n.length) {
    i(e);
    return;
  }
  const o = [];
  for (; n.length; ) {
    const a = n.shift();
    if (!a)
      continue;
    const c = a.toLowerCase();
    if (c.includes("wc@") || c.includes("walletconnect") || c.includes("wc_") || c.includes("wallet_connect")) {
      const u = await t.getItem(a);
      await e.setItem(a, u), o.push(a);
    }
  }
  await e.setItem(r, Ya), i(e), Wp(t, o);
}, Wp = async (t, e) => {
  e.length && e.forEach(async (i) => {
    await t.removeItem(i);
  });
};
let Gp = class {
  constructor() {
    this.initialized = !1, this.setInitialized = (i) => {
      this.storage = i, this.initialized = !0;
    };
    const e = new Kp();
    this.storage = e;
    try {
      const i = new jp();
      Hp(e, i, this.setInitialized);
    } catch {
      this.initialized = !0;
    }
  }
  async getKeys() {
    return await this.initialize(), this.storage.getKeys();
  }
  async getEntries() {
    return await this.initialize(), this.storage.getEntries();
  }
  async getItem(e) {
    return await this.initialize(), this.storage.getItem(e);
  }
  async setItem(e, i) {
    return await this.initialize(), this.storage.setItem(e, i);
  }
  async removeItem(e) {
    return await this.initialize(), this.storage.removeItem(e);
  }
  async initialize() {
    this.initialized || await new Promise((e) => {
      const i = setInterval(() => {
        this.initialized && (clearInterval(i), e());
      }, 20);
    });
  }
};
function Yp(t) {
  try {
    return JSON.stringify(t);
  } catch {
    return '"[Circular]"';
  }
}
var Jp = Zp;
function Zp(t, e, i) {
  var r = i && i.stringify || Yp, s = 1;
  if (typeof t == "object" && t !== null) {
    var n = e.length + s;
    if (n === 1)
      return t;
    var o = new Array(n);
    o[0] = r(t);
    for (var a = 1; a < n; a++)
      o[a] = r(e[a]);
    return o.join(" ");
  }
  if (typeof t != "string")
    return t;
  var c = e.length;
  if (c === 0)
    return t;
  for (var u = "", h = 1 - s, l = -1, f = t && t.length || 0, p = 0; p < f; ) {
    if (t.charCodeAt(p) === 37 && p + 1 < f) {
      switch (l = l > -1 ? l : 0, t.charCodeAt(p + 1)) {
        case 100:
        case 102:
          if (h >= c || e[h] == null)
            break;
          l < p && (u += t.slice(l, p)), u += Number(e[h]), l = p + 2, p++;
          break;
        case 105:
          if (h >= c || e[h] == null)
            break;
          l < p && (u += t.slice(l, p)), u += Math.floor(Number(e[h])), l = p + 2, p++;
          break;
        case 79:
        case 111:
        case 106:
          if (h >= c || e[h] === void 0)
            break;
          l < p && (u += t.slice(l, p));
          var d = typeof e[h];
          if (d === "string") {
            u += "'" + e[h] + "'", l = p + 2, p++;
            break;
          }
          if (d === "function") {
            u += e[h].name || "<anonymous>", l = p + 2, p++;
            break;
          }
          u += r(e[h]), l = p + 2, p++;
          break;
        case 115:
          if (h >= c)
            break;
          l < p && (u += t.slice(l, p)), u += String(e[h]), l = p + 2, p++;
          break;
        case 37:
          l < p && (u += t.slice(l, p)), u += "%", l = p + 2, p++, h--;
          break;
      }
      ++h;
    }
    ++p;
  }
  return l === -1 ? t : (l < f && (u += t.slice(l)), u);
}
const Ja = Jp;
var Hi = $t;
const Nr = ag().console || {}, Qp = {
  mapHttpRequest: as,
  mapHttpResponse: as,
  wrapRequestSerializer: xn,
  wrapResponseSerializer: xn,
  wrapErrorSerializer: xn,
  req: as,
  res: as,
  err: rg
};
function Xp(t, e) {
  return Array.isArray(t) ? t.filter(function(r) {
    return r !== "!stdSerializers.err";
  }) : t === !0 ? Object.keys(e) : !1;
}
function $t(t) {
  t = t || {}, t.browser = t.browser || {};
  const e = t.browser.transmit;
  if (e && typeof e.send != "function")
    throw Error("pino: transmit option must have a send function");
  const i = t.browser.write || Nr;
  t.browser.write && (t.browser.asObject = !0);
  const r = t.serializers || {}, s = Xp(t.browser.serialize, r);
  let n = t.browser.serialize;
  Array.isArray(t.browser.serialize) && t.browser.serialize.indexOf("!stdSerializers.err") > -1 && (n = !1);
  const o = ["error", "fatal", "warn", "info", "debug", "trace"];
  typeof i == "function" && (i.error = i.fatal = i.warn = i.info = i.debug = i.trace = i), t.enabled === !1 && (t.level = "silent");
  const a = t.level || "info", c = Object.create(i);
  c.log || (c.log = kr), Object.defineProperty(c, "levelVal", {
    get: h
  }), Object.defineProperty(c, "level", {
    get: l,
    set: f
  });
  const u = {
    transmit: e,
    serialize: s,
    asObject: t.browser.asObject,
    levels: o,
    timestamp: sg(t)
  };
  c.levels = $t.levels, c.level = a, c.setMaxListeners = c.getMaxListeners = c.emit = c.addListener = c.on = c.prependListener = c.once = c.prependOnceListener = c.removeListener = c.removeAllListeners = c.listeners = c.listenerCount = c.eventNames = c.write = c.flush = kr, c.serializers = r, c._serialize = s, c._stdErrSerialize = n, c.child = p, e && (c._logEvent = so());
  function h() {
    return this.level === "silent" ? 1 / 0 : this.levels.values[this.level];
  }
  function l() {
    return this._level;
  }
  function f(d) {
    if (d !== "silent" && !this.levels.values[d])
      throw Error("unknown level " + d);
    this._level = d, Ni(u, c, "error", "log"), Ni(u, c, "fatal", "error"), Ni(u, c, "warn", "error"), Ni(u, c, "info", "log"), Ni(u, c, "debug", "log"), Ni(u, c, "trace", "log");
  }
  function p(d, g) {
    if (!d)
      throw new Error("missing bindings for child Pino");
    g = g || {}, s && d.serializers && (g.serializers = d.serializers);
    const y = g.serializers;
    if (s && y) {
      var E = Object.assign({}, r, y), v = t.browser.serialize === !0 ? Object.keys(E) : s;
      delete d.serializers, Js([d], v, E, this._stdErrSerialize);
    }
    function m(D) {
      this._childLevel = (D._childLevel | 0) + 1, this.error = ki(D, d, "error"), this.fatal = ki(D, d, "fatal"), this.warn = ki(D, d, "warn"), this.info = ki(D, d, "info"), this.debug = ki(D, d, "debug"), this.trace = ki(D, d, "trace"), E && (this.serializers = E, this._serialize = v), e && (this._logEvent = so(
        [].concat(D._logEvent.bindings, d)
      ));
    }
    return m.prototype = this, new m(this);
  }
  return c;
}
$t.levels = {
  values: {
    fatal: 60,
    error: 50,
    warn: 40,
    info: 30,
    debug: 20,
    trace: 10
  },
  labels: {
    10: "trace",
    20: "debug",
    30: "info",
    40: "warn",
    50: "error",
    60: "fatal"
  }
};
$t.stdSerializers = Qp;
$t.stdTimeFunctions = Object.assign({}, { nullTime: xh, epochTime: Ih, unixTime: ng, isoTime: og });
function Ni(t, e, i, r) {
  const s = Object.getPrototypeOf(e);
  e[i] = e.levelVal > e.levels.values[i] ? kr : s[i] ? s[i] : Nr[i] || Nr[r] || kr, eg(t, e, i);
}
function eg(t, e, i) {
  !t.transmit && e[i] === kr || (e[i] = function(r) {
    return function() {
      const n = t.timestamp(), o = new Array(arguments.length), a = Object.getPrototypeOf && Object.getPrototypeOf(this) === Nr ? Nr : this;
      for (var c = 0; c < o.length; c++)
        o[c] = arguments[c];
      if (t.serialize && !t.asObject && Js(o, this._serialize, this.serializers, this._stdErrSerialize), t.asObject ? r.call(a, tg(this, i, o, n)) : r.apply(a, o), t.transmit) {
        const u = t.transmit.level || e.level, h = $t.levels.values[u], l = $t.levels.values[i];
        if (l < h)
          return;
        ig(this, {
          ts: n,
          methodLevel: i,
          methodValue: l,
          transmitLevel: u,
          transmitValue: $t.levels.values[t.transmit.level || e.level],
          send: t.transmit.send,
          val: e.levelVal
        }, o);
      }
    };
  }(e[i]));
}
function tg(t, e, i, r) {
  t._serialize && Js(i, t._serialize, t.serializers, t._stdErrSerialize);
  const s = i.slice();
  let n = s[0];
  const o = {};
  r && (o.time = r), o.level = $t.levels.values[e];
  let a = (t._childLevel | 0) + 1;
  if (a < 1 && (a = 1), n !== null && typeof n == "object") {
    for (; a-- && typeof s[0] == "object"; )
      Object.assign(o, s.shift());
    n = s.length ? Ja(s.shift(), s) : void 0;
  } else
    typeof n == "string" && (n = Ja(s.shift(), s));
  return n !== void 0 && (o.msg = n), o;
}
function Js(t, e, i, r) {
  for (const s in t)
    if (r && t[s] instanceof Error)
      t[s] = $t.stdSerializers.err(t[s]);
    else if (typeof t[s] == "object" && !Array.isArray(t[s]))
      for (const n in t[s])
        e && e.indexOf(n) > -1 && n in i && (t[s][n] = i[n](t[s][n]));
}
function ki(t, e, i) {
  return function() {
    const r = new Array(1 + arguments.length);
    r[0] = e;
    for (var s = 1; s < r.length; s++)
      r[s] = arguments[s - 1];
    return t[i].apply(this, r);
  };
}
function ig(t, e, i) {
  const r = e.send, s = e.ts, n = e.methodLevel, o = e.methodValue, a = e.val, c = t._logEvent.bindings;
  Js(
    i,
    t._serialize || Object.keys(t.serializers),
    t.serializers,
    t._stdErrSerialize === void 0 ? !0 : t._stdErrSerialize
  ), t._logEvent.ts = s, t._logEvent.messages = i.filter(function(u) {
    return c.indexOf(u) === -1;
  }), t._logEvent.level.label = n, t._logEvent.level.value = o, r(n, t._logEvent, a), t._logEvent = so(c);
}
function so(t) {
  return {
    ts: 0,
    messages: [],
    bindings: t || [],
    level: { label: "", value: 0 }
  };
}
function rg(t) {
  const e = {
    type: t.constructor.name,
    msg: t.message,
    stack: t.stack
  };
  for (const i in t)
    e[i] === void 0 && (e[i] = t[i]);
  return e;
}
function sg(t) {
  return typeof t.timestamp == "function" ? t.timestamp : t.timestamp === !1 ? xh : Ih;
}
function as() {
  return {};
}
function xn(t) {
  return t;
}
function kr() {
}
function xh() {
  return !1;
}
function Ih() {
  return Date.now();
}
function ng() {
  return Math.round(Date.now() / 1e3);
}
function og() {
  return new Date(Date.now()).toISOString();
}
function ag() {
  function t(e) {
    return typeof e < "u" && e;
  }
  try {
    return typeof globalThis < "u" || Object.defineProperty(Object.prototype, "globalThis", {
      get: function() {
        return delete Object.prototype.globalThis, this.globalThis = this;
      },
      configurable: !0
    }), globalThis;
  } catch {
    return t(self) || t(window) || t(this) || {};
  }
}
const Zs = /* @__PURE__ */ ch(Hi), cg = { level: "info" }, Yr = "custom_context", Ko = 1e3 * 1024;
let ug = class {
  constructor(e) {
    this.nodeValue = e, this.sizeInBytes = new TextEncoder().encode(this.nodeValue).length, this.next = null;
  }
  get value() {
    return this.nodeValue;
  }
  get size() {
    return this.sizeInBytes;
  }
}, Za = class {
  constructor(e) {
    this.head = null, this.tail = null, this.lengthInNodes = 0, this.maxSizeInBytes = e, this.sizeInBytes = 0;
  }
  append(e) {
    const i = new ug(e);
    if (i.size > this.maxSizeInBytes)
      throw new Error(`[LinkedList] Value too big to insert into list: ${e} with size ${i.size}`);
    for (; this.size + i.size > this.maxSizeInBytes; )
      this.shift();
    this.head ? (this.tail && (this.tail.next = i), this.tail = i) : (this.head = i, this.tail = i), this.lengthInNodes++, this.sizeInBytes += i.size;
  }
  shift() {
    if (!this.head)
      return;
    const e = this.head;
    this.head = this.head.next, this.head || (this.tail = null), this.lengthInNodes--, this.sizeInBytes -= e.size;
  }
  toArray() {
    const e = [];
    let i = this.head;
    for (; i !== null; )
      e.push(i.value), i = i.next;
    return e;
  }
  get length() {
    return this.lengthInNodes;
  }
  get size() {
    return this.sizeInBytes;
  }
  toOrderedArray() {
    return Array.from(this);
  }
  [Symbol.iterator]() {
    let e = this.head;
    return { next: () => {
      if (!e)
        return { done: !0, value: null };
      const i = e.value;
      return e = e.next, { done: !1, value: i };
    } };
  }
};
class Sh {
  constructor(e, i = Ko) {
    this.level = e ?? "error", this.levelValue = Hi.levels.values[this.level], this.MAX_LOG_SIZE_IN_BYTES = i, this.logs = new Za(this.MAX_LOG_SIZE_IN_BYTES);
  }
  forwardToConsole(e, i) {
    i === Hi.levels.values.error ? console.error(e) : i === Hi.levels.values.warn ? console.warn(e) : i === Hi.levels.values.debug ? console.debug(e) : i === Hi.levels.values.trace ? console.trace(e) : console.log(e);
  }
  appendToLogs(e) {
    this.logs.append(Ii({ timestamp: (/* @__PURE__ */ new Date()).toISOString(), log: e }));
    const i = typeof e == "string" ? JSON.parse(e).level : e.level;
    i >= this.levelValue && this.forwardToConsole(e, i);
  }
  getLogs() {
    return this.logs;
  }
  clearLogs() {
    this.logs = new Za(this.MAX_LOG_SIZE_IN_BYTES);
  }
  getLogArray() {
    return Array.from(this.logs);
  }
  logsToBlob(e) {
    const i = this.getLogArray();
    return i.push(Ii({ extraMetadata: e })), new Blob(i, { type: "application/json" });
  }
}
let hg = class {
  constructor(e, i = Ko) {
    this.baseChunkLogger = new Sh(e, i);
  }
  write(e) {
    this.baseChunkLogger.appendToLogs(e);
  }
  getLogs() {
    return this.baseChunkLogger.getLogs();
  }
  clearLogs() {
    this.baseChunkLogger.clearLogs();
  }
  getLogArray() {
    return this.baseChunkLogger.getLogArray();
  }
  logsToBlob(e) {
    return this.baseChunkLogger.logsToBlob(e);
  }
  downloadLogsBlobInBrowser(e) {
    const i = URL.createObjectURL(this.logsToBlob(e)), r = document.createElement("a");
    r.href = i, r.download = `walletconnect-logs-${(/* @__PURE__ */ new Date()).toISOString()}.txt`, document.body.appendChild(r), r.click(), document.body.removeChild(r), URL.revokeObjectURL(i);
  }
}, lg = class {
  constructor(e, i = Ko) {
    this.baseChunkLogger = new Sh(e, i);
  }
  write(e) {
    this.baseChunkLogger.appendToLogs(e);
  }
  getLogs() {
    return this.baseChunkLogger.getLogs();
  }
  clearLogs() {
    this.baseChunkLogger.clearLogs();
  }
  getLogArray() {
    return this.baseChunkLogger.getLogArray();
  }
  logsToBlob(e) {
    return this.baseChunkLogger.logsToBlob(e);
  }
};
var fg = Object.defineProperty, dg = Object.defineProperties, pg = Object.getOwnPropertyDescriptors, Qa = Object.getOwnPropertySymbols, gg = Object.prototype.hasOwnProperty, yg = Object.prototype.propertyIsEnumerable, Xa = (t, e, i) => e in t ? fg(t, e, { enumerable: !0, configurable: !0, writable: !0, value: i }) : t[e] = i, Ps = (t, e) => {
  for (var i in e || (e = {}))
    gg.call(e, i) && Xa(t, i, e[i]);
  if (Qa)
    for (var i of Qa(e))
      yg.call(e, i) && Xa(t, i, e[i]);
  return t;
}, Rs = (t, e) => dg(t, pg(e));
function Vo(t) {
  return Rs(Ps({}, t), { level: t?.level || cg.level });
}
function wg(t, e = Yr) {
  return t[e] || "";
}
function mg(t, e, i = Yr) {
  return t[i] = e, t;
}
function Qe(t, e = Yr) {
  let i = "";
  return typeof t.bindings > "u" ? i = wg(t, e) : i = t.bindings().context || "", i;
}
function bg(t, e, i = Yr) {
  const r = Qe(t, i);
  return r.trim() ? `${r}/${e}` : e;
}
function je(t, e, i = Yr) {
  const r = bg(t, e, i), s = t.child({ context: r });
  return mg(s, r, i);
}
function vg(t) {
  var e, i;
  const r = new hg((e = t.opts) == null ? void 0 : e.level, t.maxSizeInBytes);
  return { logger: Zs(Rs(Ps({}, t.opts), { level: "trace", browser: Rs(Ps({}, (i = t.opts) == null ? void 0 : i.browser), { write: (s) => r.write(s) }) })), chunkLoggerController: r };
}
function Eg(t) {
  var e;
  const i = new lg((e = t.opts) == null ? void 0 : e.level, t.maxSizeInBytes);
  return { logger: Zs(Rs(Ps({}, t.opts), { level: "trace" }), i), chunkLoggerController: i };
}
function _g(t) {
  return typeof t.loggerOverride < "u" && typeof t.loggerOverride != "string" ? { logger: t.loggerOverride, chunkLoggerController: null } : typeof window < "u" ? vg(t) : Eg(t);
}
var xg = Object.defineProperty, Ig = (t, e, i) => e in t ? xg(t, e, { enumerable: !0, configurable: !0, writable: !0, value: i }) : t[e] = i, ec = (t, e, i) => Ig(t, typeof e != "symbol" ? e + "" : e, i);
let Sg = class extends Oi {
  constructor(e) {
    super(), this.opts = e, ec(this, "protocol", "wc"), ec(this, "version", 2);
  }
};
var Dg = Object.defineProperty, Ag = (t, e, i) => e in t ? Dg(t, e, { enumerable: !0, configurable: !0, writable: !0, value: i }) : t[e] = i, $g = (t, e, i) => Ag(t, typeof e != "symbol" ? e + "" : e, i);
class Og extends Oi {
  constructor(e, i) {
    super(), this.core = e, this.logger = i, $g(this, "records", /* @__PURE__ */ new Map());
  }
}
let Tg = class {
  constructor(e, i) {
    this.logger = e, this.core = i;
  }
}, Cg = class extends Oi {
  constructor(e, i) {
    super(), this.relayer = e, this.logger = i;
  }
}, Pg = class extends Oi {
  constructor(e) {
    super();
  }
}, Rg = class {
  constructor(e, i, r, s) {
    this.core = e, this.logger = i, this.name = r;
  }
}, Fg = class extends Oi {
  constructor(e, i) {
    super(), this.relayer = e, this.logger = i;
  }
};
class Ug extends Oi {
  constructor(e, i) {
    super(), this.core = e, this.logger = i;
  }
}
let Bg = class {
  constructor(e, i, r) {
    this.core = e, this.logger = i, this.store = r;
  }
}, Ng = class {
  constructor(e, i) {
    this.projectId = e, this.logger = i;
  }
}, kg = class {
  constructor(e, i, r) {
    this.core = e, this.logger = i, this.telemetryEnabled = r;
  }
};
var Lg = Object.defineProperty, Mg = (t, e, i) => e in t ? Lg(t, e, { enumerable: !0, configurable: !0, writable: !0, value: i }) : t[e] = i, tc = (t, e, i) => Mg(t, typeof e != "symbol" ? e + "" : e, i);
let qg = class {
  constructor(e) {
    this.opts = e, tc(this, "protocol", "wc"), tc(this, "version", 2);
  }
}, jg = class {
  constructor(e) {
    this.client = e;
  }
};
function zg(t) {
  return t instanceof Uint8Array || ArrayBuffer.isView(t) && t.constructor.name === "Uint8Array";
}
function Dh(t, ...e) {
  if (!zg(t))
    throw new Error("Uint8Array expected");
  if (e.length > 0 && !e.includes(t.length))
    throw new Error("Uint8Array expected of length " + e + ", got length=" + t.length);
}
function ic(t, e = !0) {
  if (t.destroyed)
    throw new Error("Hash instance has been destroyed");
  if (e && t.finished)
    throw new Error("Hash#digest() has already been called");
}
function Kg(t, e) {
  Dh(t);
  const i = e.outputLen;
  if (t.length < i)
    throw new Error("digestInto() expects output buffer of length at least " + i);
}
const Li = typeof globalThis == "object" && "crypto" in globalThis ? globalThis.crypto : void 0;
/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */
const In = (t) => new DataView(t.buffer, t.byteOffset, t.byteLength);
function Vg(t) {
  if (typeof t != "string")
    throw new Error("utf8ToBytes expected string, got " + typeof t);
  return new Uint8Array(new TextEncoder().encode(t));
}
function Ah(t) {
  return typeof t == "string" && (t = Vg(t)), Dh(t), t;
}
let Hg = class {
  clone() {
    return this._cloneInto();
  }
};
function Wg(t) {
  const e = (r) => t().update(Ah(r)).digest(), i = t();
  return e.outputLen = i.outputLen, e.blockLen = i.blockLen, e.create = () => t(), e;
}
function $h(t = 32) {
  if (Li && typeof Li.getRandomValues == "function")
    return Li.getRandomValues(new Uint8Array(t));
  if (Li && typeof Li.randomBytes == "function")
    return Li.randomBytes(t);
  throw new Error("crypto.getRandomValues must be defined");
}
function Gg(t, e, i, r) {
  if (typeof t.setBigUint64 == "function")
    return t.setBigUint64(e, i, r);
  const s = BigInt(32), n = BigInt(4294967295), o = Number(i >> s & n), a = Number(i & n), c = r ? 4 : 0, u = r ? 0 : 4;
  t.setUint32(e + c, o, r), t.setUint32(e + u, a, r);
}
let Yg = class extends Hg {
  constructor(e, i, r, s) {
    super(), this.blockLen = e, this.outputLen = i, this.padOffset = r, this.isLE = s, this.finished = !1, this.length = 0, this.pos = 0, this.destroyed = !1, this.buffer = new Uint8Array(e), this.view = In(this.buffer);
  }
  update(e) {
    ic(this);
    const { view: i, buffer: r, blockLen: s } = this;
    e = Ah(e);
    const n = e.length;
    for (let o = 0; o < n; ) {
      const a = Math.min(s - this.pos, n - o);
      if (a === s) {
        const c = In(e);
        for (; s <= n - o; o += s)
          this.process(c, o);
        continue;
      }
      r.set(e.subarray(o, o + a), this.pos), this.pos += a, o += a, this.pos === s && (this.process(i, 0), this.pos = 0);
    }
    return this.length += e.length, this.roundClean(), this;
  }
  digestInto(e) {
    ic(this), Kg(e, this), this.finished = !0;
    const { buffer: i, view: r, blockLen: s, isLE: n } = this;
    let { pos: o } = this;
    i[o++] = 128, this.buffer.subarray(o).fill(0), this.padOffset > s - o && (this.process(r, 0), o = 0);
    for (let l = o; l < s; l++)
      i[l] = 0;
    Gg(r, s - 8, BigInt(this.length * 8), n), this.process(r, 0);
    const a = In(e), c = this.outputLen;
    if (c % 4)
      throw new Error("_sha2: outputLen should be aligned to 32bit");
    const u = c / 4, h = this.get();
    if (u > h.length)
      throw new Error("_sha2: outputLen bigger than state");
    for (let l = 0; l < u; l++)
      a.setUint32(4 * l, h[l], n);
  }
  digest() {
    const { buffer: e, outputLen: i } = this;
    this.digestInto(e);
    const r = e.slice(0, i);
    return this.destroy(), r;
  }
  _cloneInto(e) {
    e || (e = new this.constructor()), e.set(...this.get());
    const { blockLen: i, buffer: r, length: s, finished: n, destroyed: o, pos: a } = this;
    return e.length = s, e.pos = a, e.finished = n, e.destroyed = o, s % i && e.buffer.set(r), e;
  }
};
const cs = BigInt(2 ** 32 - 1), no = BigInt(32);
function Oh(t, e = !1) {
  return e ? { h: Number(t & cs), l: Number(t >> no & cs) } : { h: Number(t >> no & cs) | 0, l: Number(t & cs) | 0 };
}
function Jg(t, e = !1) {
  let i = new Uint32Array(t.length), r = new Uint32Array(t.length);
  for (let s = 0; s < t.length; s++) {
    const { h: n, l: o } = Oh(t[s], e);
    [i[s], r[s]] = [n, o];
  }
  return [i, r];
}
const Zg = (t, e) => BigInt(t >>> 0) << no | BigInt(e >>> 0), Qg = (t, e, i) => t >>> i, Xg = (t, e, i) => t << 32 - i | e >>> i, e0 = (t, e, i) => t >>> i | e << 32 - i, t0 = (t, e, i) => t << 32 - i | e >>> i, i0 = (t, e, i) => t << 64 - i | e >>> i - 32, r0 = (t, e, i) => t >>> i - 32 | e << 64 - i, s0 = (t, e) => e, n0 = (t, e) => t, o0 = (t, e, i) => t << i | e >>> 32 - i, a0 = (t, e, i) => e << i | t >>> 32 - i, c0 = (t, e, i) => e << i - 32 | t >>> 64 - i, u0 = (t, e, i) => t << i - 32 | e >>> 64 - i;
function h0(t, e, i, r) {
  const s = (e >>> 0) + (r >>> 0);
  return { h: t + i + (s / 2 ** 32 | 0) | 0, l: s | 0 };
}
const l0 = (t, e, i) => (t >>> 0) + (e >>> 0) + (i >>> 0), f0 = (t, e, i, r) => e + i + r + (t / 2 ** 32 | 0) | 0, d0 = (t, e, i, r) => (t >>> 0) + (e >>> 0) + (i >>> 0) + (r >>> 0), p0 = (t, e, i, r, s) => e + i + r + s + (t / 2 ** 32 | 0) | 0, g0 = (t, e, i, r, s) => (t >>> 0) + (e >>> 0) + (i >>> 0) + (r >>> 0) + (s >>> 0), y0 = (t, e, i, r, s, n) => e + i + r + s + n + (t / 2 ** 32 | 0) | 0, Y = { fromBig: Oh, split: Jg, toBig: Zg, shrSH: Qg, shrSL: Xg, rotrSH: e0, rotrSL: t0, rotrBH: i0, rotrBL: r0, rotr32H: s0, rotr32L: n0, rotlSH: o0, rotlSL: a0, rotlBH: c0, rotlBL: u0, add: h0, add3L: l0, add3H: f0, add4L: d0, add4H: p0, add5H: y0, add5L: g0 }, [w0, m0] = (() => Y.split(["0x428a2f98d728ae22", "0x7137449123ef65cd", "0xb5c0fbcfec4d3b2f", "0xe9b5dba58189dbbc", "0x3956c25bf348b538", "0x59f111f1b605d019", "0x923f82a4af194f9b", "0xab1c5ed5da6d8118", "0xd807aa98a3030242", "0x12835b0145706fbe", "0x243185be4ee4b28c", "0x550c7dc3d5ffb4e2", "0x72be5d74f27b896f", "0x80deb1fe3b1696b1", "0x9bdc06a725c71235", "0xc19bf174cf692694", "0xe49b69c19ef14ad2", "0xefbe4786384f25e3", "0x0fc19dc68b8cd5b5", "0x240ca1cc77ac9c65", "0x2de92c6f592b0275", "0x4a7484aa6ea6e483", "0x5cb0a9dcbd41fbd4", "0x76f988da831153b5", "0x983e5152ee66dfab", "0xa831c66d2db43210", "0xb00327c898fb213f", "0xbf597fc7beef0ee4", "0xc6e00bf33da88fc2", "0xd5a79147930aa725", "0x06ca6351e003826f", "0x142929670a0e6e70", "0x27b70a8546d22ffc", "0x2e1b21385c26c926", "0x4d2c6dfc5ac42aed", "0x53380d139d95b3df", "0x650a73548baf63de", "0x766a0abb3c77b2a8", "0x81c2c92e47edaee6", "0x92722c851482353b", "0xa2bfe8a14cf10364", "0xa81a664bbc423001", "0xc24b8b70d0f89791", "0xc76c51a30654be30", "0xd192e819d6ef5218", "0xd69906245565a910", "0xf40e35855771202a", "0x106aa07032bbd1b8", "0x19a4c116b8d2d0c8", "0x1e376c085141ab53", "0x2748774cdf8eeb99", "0x34b0bcb5e19b48a8", "0x391c0cb3c5c95a63", "0x4ed8aa4ae3418acb", "0x5b9cca4f7763e373", "0x682e6ff3d6b2b8a3", "0x748f82ee5defb2fc", "0x78a5636f43172f60", "0x84c87814a1f0ab72", "0x8cc702081a6439ec", "0x90befffa23631e28", "0xa4506cebde82bde9", "0xbef9a3f7b2c67915", "0xc67178f2e372532b", "0xca273eceea26619c", "0xd186b8c721c0c207", "0xeada7dd6cde0eb1e", "0xf57d4f7fee6ed178", "0x06f067aa72176fba", "0x0a637dc5a2c898a6", "0x113f9804bef90dae", "0x1b710b35131c471b", "0x28db77f523047d84", "0x32caab7b40c72493", "0x3c9ebe0a15c9bebc", "0x431d67c49c100d4c", "0x4cc5d4becb3e42b6", "0x597f299cfc657e2a", "0x5fcb6fab3ad6faec", "0x6c44198c4a475817"].map((t) => BigInt(t))))(), jt = new Uint32Array(80), zt = new Uint32Array(80);
let b0 = class extends Yg {
  constructor() {
    super(128, 64, 16, !1), this.Ah = 1779033703, this.Al = -205731576, this.Bh = -1150833019, this.Bl = -2067093701, this.Ch = 1013904242, this.Cl = -23791573, this.Dh = -1521486534, this.Dl = 1595750129, this.Eh = 1359893119, this.El = -1377402159, this.Fh = -1694144372, this.Fl = 725511199, this.Gh = 528734635, this.Gl = -79577749, this.Hh = 1541459225, this.Hl = 327033209;
  }
  get() {
    const { Ah: e, Al: i, Bh: r, Bl: s, Ch: n, Cl: o, Dh: a, Dl: c, Eh: u, El: h, Fh: l, Fl: f, Gh: p, Gl: d, Hh: g, Hl: y } = this;
    return [e, i, r, s, n, o, a, c, u, h, l, f, p, d, g, y];
  }
  set(e, i, r, s, n, o, a, c, u, h, l, f, p, d, g, y) {
    this.Ah = e | 0, this.Al = i | 0, this.Bh = r | 0, this.Bl = s | 0, this.Ch = n | 0, this.Cl = o | 0, this.Dh = a | 0, this.Dl = c | 0, this.Eh = u | 0, this.El = h | 0, this.Fh = l | 0, this.Fl = f | 0, this.Gh = p | 0, this.Gl = d | 0, this.Hh = g | 0, this.Hl = y | 0;
  }
  process(e, i) {
    for (let m = 0; m < 16; m++, i += 4)
      jt[m] = e.getUint32(i), zt[m] = e.getUint32(i += 4);
    for (let m = 16; m < 80; m++) {
      const D = jt[m - 15] | 0, I = zt[m - 15] | 0, R = Y.rotrSH(D, I, 1) ^ Y.rotrSH(D, I, 8) ^ Y.shrSH(D, I, 7), B = Y.rotrSL(D, I, 1) ^ Y.rotrSL(D, I, 8) ^ Y.shrSL(D, I, 7), C = jt[m - 2] | 0, w = zt[m - 2] | 0, O = Y.rotrSH(C, w, 19) ^ Y.rotrBH(C, w, 61) ^ Y.shrSH(C, w, 6), _ = Y.rotrSL(C, w, 19) ^ Y.rotrBL(C, w, 61) ^ Y.shrSL(C, w, 6), $ = Y.add4L(B, _, zt[m - 7], zt[m - 16]), P = Y.add4H($, R, O, jt[m - 7], jt[m - 16]);
      jt[m] = P | 0, zt[m] = $ | 0;
    }
    let { Ah: r, Al: s, Bh: n, Bl: o, Ch: a, Cl: c, Dh: u, Dl: h, Eh: l, El: f, Fh: p, Fl: d, Gh: g, Gl: y, Hh: E, Hl: v } = this;
    for (let m = 0; m < 80; m++) {
      const D = Y.rotrSH(l, f, 14) ^ Y.rotrSH(l, f, 18) ^ Y.rotrBH(l, f, 41), I = Y.rotrSL(l, f, 14) ^ Y.rotrSL(l, f, 18) ^ Y.rotrBL(l, f, 41), R = l & p ^ ~l & g, B = f & d ^ ~f & y, C = Y.add5L(v, I, B, m0[m], zt[m]), w = Y.add5H(C, E, D, R, w0[m], jt[m]), O = C | 0, _ = Y.rotrSH(r, s, 28) ^ Y.rotrBH(r, s, 34) ^ Y.rotrBH(r, s, 39), $ = Y.rotrSL(r, s, 28) ^ Y.rotrBL(r, s, 34) ^ Y.rotrBL(r, s, 39), P = r & n ^ r & a ^ n & a, k = s & o ^ s & c ^ o & c;
      E = g | 0, v = y | 0, g = p | 0, y = d | 0, p = l | 0, d = f | 0, { h: l, l: f } = Y.add(u | 0, h | 0, w | 0, O | 0), u = a | 0, h = c | 0, a = n | 0, c = o | 0, n = r | 0, o = s | 0;
      const x = Y.add3L(O, $, k);
      r = Y.add3H(x, w, _, P), s = x | 0;
    }
    ({ h: r, l: s } = Y.add(this.Ah | 0, this.Al | 0, r | 0, s | 0)), { h: n, l: o } = Y.add(this.Bh | 0, this.Bl | 0, n | 0, o | 0), { h: a, l: c } = Y.add(this.Ch | 0, this.Cl | 0, a | 0, c | 0), { h: u, l: h } = Y.add(this.Dh | 0, this.Dl | 0, u | 0, h | 0), { h: l, l: f } = Y.add(this.Eh | 0, this.El | 0, l | 0, f | 0), { h: p, l: d } = Y.add(this.Fh | 0, this.Fl | 0, p | 0, d | 0), { h: g, l: y } = Y.add(this.Gh | 0, this.Gl | 0, g | 0, y | 0), { h: E, l: v } = Y.add(this.Hh | 0, this.Hl | 0, E | 0, v | 0), this.set(r, s, n, o, a, c, u, h, l, f, p, d, g, y, E, v);
  }
  roundClean() {
    jt.fill(0), zt.fill(0);
  }
  destroy() {
    this.buffer.fill(0), this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  }
};
const v0 = Wg(() => new b0());
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
const Ho = BigInt(0), Th = BigInt(1), E0 = BigInt(2);
function Wo(t) {
  return t instanceof Uint8Array || ArrayBuffer.isView(t) && t.constructor.name === "Uint8Array";
}
function Go(t) {
  if (!Wo(t))
    throw new Error("Uint8Array expected");
}
function Sn(t, e) {
  if (typeof e != "boolean")
    throw new Error(t + " boolean expected, got " + e);
}
const _0 = Array.from({ length: 256 }, (t, e) => e.toString(16).padStart(2, "0"));
function Yo(t) {
  Go(t);
  let e = "";
  for (let i = 0; i < t.length; i++)
    e += _0[t[i]];
  return e;
}
function Ch(t) {
  if (typeof t != "string")
    throw new Error("hex string expected, got " + typeof t);
  return t === "" ? Ho : BigInt("0x" + t);
}
const Tt = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 };
function rc(t) {
  if (t >= Tt._0 && t <= Tt._9)
    return t - Tt._0;
  if (t >= Tt.A && t <= Tt.F)
    return t - (Tt.A - 10);
  if (t >= Tt.a && t <= Tt.f)
    return t - (Tt.a - 10);
}
function Ph(t) {
  if (typeof t != "string")
    throw new Error("hex string expected, got " + typeof t);
  const e = t.length, i = e / 2;
  if (e % 2)
    throw new Error("hex string expected, got unpadded hex of length " + e);
  const r = new Uint8Array(i);
  for (let s = 0, n = 0; s < i; s++, n += 2) {
    const o = rc(t.charCodeAt(n)), a = rc(t.charCodeAt(n + 1));
    if (o === void 0 || a === void 0) {
      const c = t[n] + t[n + 1];
      throw new Error('hex string expected, got non-hex character "' + c + '" at index ' + n);
    }
    r[s] = o * 16 + a;
  }
  return r;
}
function x0(t) {
  return Ch(Yo(t));
}
function Ss(t) {
  return Go(t), Ch(Yo(Uint8Array.from(t).reverse()));
}
function Rh(t, e) {
  return Ph(t.toString(16).padStart(e * 2, "0"));
}
function oo(t, e) {
  return Rh(t, e).reverse();
}
function Ct(t, e, i) {
  let r;
  if (typeof e == "string")
    try {
      r = Ph(e);
    } catch (n) {
      throw new Error(t + " must be hex string or Uint8Array, cause: " + n);
    }
  else if (Wo(e))
    r = Uint8Array.from(e);
  else
    throw new Error(t + " must be hex string or Uint8Array");
  const s = r.length;
  if (typeof i == "number" && s !== i)
    throw new Error(t + " of length " + i + " expected, got " + s);
  return r;
}
function sc(...t) {
  let e = 0;
  for (let r = 0; r < t.length; r++) {
    const s = t[r];
    Go(s), e += s.length;
  }
  const i = new Uint8Array(e);
  for (let r = 0, s = 0; r < t.length; r++) {
    const n = t[r];
    i.set(n, s), s += n.length;
  }
  return i;
}
const Dn = (t) => typeof t == "bigint" && Ho <= t;
function I0(t, e, i) {
  return Dn(t) && Dn(e) && Dn(i) && e <= t && t < i;
}
function ur(t, e, i, r) {
  if (!I0(e, i, r))
    throw new Error("expected valid " + t + ": " + i + " <= n < " + r + ", got " + e);
}
function S0(t) {
  let e;
  for (e = 0; t > Ho; t >>= Th, e += 1)
    ;
  return e;
}
const D0 = (t) => (E0 << BigInt(t - 1)) - Th, A0 = { bigint: (t) => typeof t == "bigint", function: (t) => typeof t == "function", boolean: (t) => typeof t == "boolean", string: (t) => typeof t == "string", stringOrUint8Array: (t) => typeof t == "string" || Wo(t), isSafeInteger: (t) => Number.isSafeInteger(t), array: (t) => Array.isArray(t), field: (t, e) => e.Fp.isValid(t), hash: (t) => typeof t == "function" && Number.isSafeInteger(t.outputLen) };
function Jo(t, e, i = {}) {
  const r = (s, n, o) => {
    const a = A0[n];
    if (typeof a != "function")
      throw new Error("invalid validator function");
    const c = t[s];
    if (!(o && c === void 0) && !a(c, t))
      throw new Error("param " + String(s) + " is invalid. Expected " + n + ", got " + c);
  };
  for (const [s, n] of Object.entries(e))
    r(s, n, !1);
  for (const [s, n] of Object.entries(i))
    r(s, n, !0);
  return t;
}
function nc(t) {
  const e = /* @__PURE__ */ new WeakMap();
  return (i, ...r) => {
    const s = e.get(i);
    if (s !== void 0)
      return s;
    const n = t(i, ...r);
    return e.set(i, n), n;
  };
}
const xe = BigInt(0), pe = BigInt(1), wi = BigInt(2), $0 = BigInt(3), ao = BigInt(4), oc = BigInt(5), ac = BigInt(8);
function be(t, e) {
  const i = t % e;
  return i >= xe ? i : e + i;
}
function O0(t, e, i) {
  if (e < xe)
    throw new Error("invalid exponent, negatives unsupported");
  if (i <= xe)
    throw new Error("invalid modulus");
  if (i === pe)
    return xe;
  let r = pe;
  for (; e > xe; )
    e & pe && (r = r * t % i), t = t * t % i, e >>= pe;
  return r;
}
function bt(t, e, i) {
  let r = t;
  for (; e-- > xe; )
    r *= r, r %= i;
  return r;
}
function cc(t, e) {
  if (t === xe)
    throw new Error("invert: expected non-zero number");
  if (e <= xe)
    throw new Error("invert: expected positive modulus, got " + e);
  let i = be(t, e), r = e, s = xe, n = pe;
  for (; i !== xe; ) {
    const o = r / i, a = r % i, c = s - n * o;
    r = i, i = a, s = n, n = c;
  }
  if (r !== pe)
    throw new Error("invert: does not exist");
  return be(s, e);
}
function T0(t) {
  const e = (t - pe) / wi;
  let i, r, s;
  for (i = t - pe, r = 0; i % wi === xe; i /= wi, r++)
    ;
  for (s = wi; s < t && O0(s, e, t) !== t - pe; s++)
    if (s > 1e3)
      throw new Error("Cannot find square root: likely non-prime P");
  if (r === 1) {
    const o = (t + pe) / ao;
    return function(a, c) {
      const u = a.pow(c, o);
      if (!a.eql(a.sqr(u), c))
        throw new Error("Cannot find square root");
      return u;
    };
  }
  const n = (i + pe) / wi;
  return function(o, a) {
    if (o.pow(a, e) === o.neg(o.ONE))
      throw new Error("Cannot find square root");
    let c = r, u = o.pow(o.mul(o.ONE, s), i), h = o.pow(a, n), l = o.pow(a, i);
    for (; !o.eql(l, o.ONE); ) {
      if (o.eql(l, o.ZERO))
        return o.ZERO;
      let f = 1;
      for (let d = o.sqr(l); f < c && !o.eql(d, o.ONE); f++)
        d = o.sqr(d);
      const p = o.pow(u, pe << BigInt(c - f - 1));
      u = o.sqr(p), h = o.mul(h, p), l = o.mul(l, u), c = f;
    }
    return h;
  };
}
function C0(t) {
  if (t % ao === $0) {
    const e = (t + pe) / ao;
    return function(i, r) {
      const s = i.pow(r, e);
      if (!i.eql(i.sqr(s), r))
        throw new Error("Cannot find square root");
      return s;
    };
  }
  if (t % ac === oc) {
    const e = (t - oc) / ac;
    return function(i, r) {
      const s = i.mul(r, wi), n = i.pow(s, e), o = i.mul(r, n), a = i.mul(i.mul(o, wi), n), c = i.mul(o, i.sub(a, i.ONE));
      if (!i.eql(i.sqr(c), r))
        throw new Error("Cannot find square root");
      return c;
    };
  }
  return T0(t);
}
const P0 = (t, e) => (be(t, e) & pe) === pe, R0 = ["create", "isValid", "is0", "neg", "inv", "sqrt", "sqr", "eql", "add", "sub", "mul", "pow", "div", "addN", "subN", "mulN", "sqrN"];
function F0(t) {
  const e = { ORDER: "bigint", MASK: "bigint", BYTES: "isSafeInteger", BITS: "isSafeInteger" }, i = R0.reduce((r, s) => (r[s] = "function", r), e);
  return Jo(t, i);
}
function U0(t, e, i) {
  if (i < xe)
    throw new Error("invalid exponent, negatives unsupported");
  if (i === xe)
    return t.ONE;
  if (i === pe)
    return e;
  let r = t.ONE, s = e;
  for (; i > xe; )
    i & pe && (r = t.mul(r, s)), s = t.sqr(s), i >>= pe;
  return r;
}
function B0(t, e) {
  const i = new Array(e.length), r = e.reduce((n, o, a) => t.is0(o) ? n : (i[a] = n, t.mul(n, o)), t.ONE), s = t.inv(r);
  return e.reduceRight((n, o, a) => t.is0(o) ? n : (i[a] = t.mul(n, i[a]), t.mul(n, o)), s), i;
}
function Fh(t, e) {
  const i = e !== void 0 ? e : t.toString(2).length, r = Math.ceil(i / 8);
  return { nBitLength: i, nByteLength: r };
}
function Uh(t, e, i = !1, r = {}) {
  if (t <= xe)
    throw new Error("invalid field: expected ORDER > 0, got " + t);
  const { nBitLength: s, nByteLength: n } = Fh(t, e);
  if (n > 2048)
    throw new Error("invalid field: expected ORDER of <= 2048 bytes");
  let o;
  const a = Object.freeze({ ORDER: t, isLE: i, BITS: s, BYTES: n, MASK: D0(s), ZERO: xe, ONE: pe, create: (c) => be(c, t), isValid: (c) => {
    if (typeof c != "bigint")
      throw new Error("invalid field element: expected bigint, got " + typeof c);
    return xe <= c && c < t;
  }, is0: (c) => c === xe, isOdd: (c) => (c & pe) === pe, neg: (c) => be(-c, t), eql: (c, u) => c === u, sqr: (c) => be(c * c, t), add: (c, u) => be(c + u, t), sub: (c, u) => be(c - u, t), mul: (c, u) => be(c * u, t), pow: (c, u) => U0(a, c, u), div: (c, u) => be(c * cc(u, t), t), sqrN: (c) => c * c, addN: (c, u) => c + u, subN: (c, u) => c - u, mulN: (c, u) => c * u, inv: (c) => cc(c, t), sqrt: r.sqrt || ((c) => (o || (o = C0(t)), o(a, c))), invertBatch: (c) => B0(a, c), cmov: (c, u, h) => h ? u : c, toBytes: (c) => i ? oo(c, n) : Rh(c, n), fromBytes: (c) => {
    if (c.length !== n)
      throw new Error("Field.fromBytes: expected " + n + " bytes, got " + c.length);
    return i ? Ss(c) : x0(c);
  } });
  return Object.freeze(a);
}
const uc = BigInt(0), us = BigInt(1);
function An(t, e) {
  const i = e.negate();
  return t ? i : e;
}
function Bh(t, e) {
  if (!Number.isSafeInteger(t) || t <= 0 || t > e)
    throw new Error("invalid window size, expected [1.." + e + "], got W=" + t);
}
function $n(t, e) {
  Bh(t, e);
  const i = Math.ceil(e / t) + 1, r = 2 ** (t - 1);
  return { windows: i, windowSize: r };
}
function N0(t, e) {
  if (!Array.isArray(t))
    throw new Error("array expected");
  t.forEach((i, r) => {
    if (!(i instanceof e))
      throw new Error("invalid point at index " + r);
  });
}
function k0(t, e) {
  if (!Array.isArray(t))
    throw new Error("array of scalars expected");
  t.forEach((i, r) => {
    if (!e.isValid(i))
      throw new Error("invalid scalar at index " + r);
  });
}
const On = /* @__PURE__ */ new WeakMap(), Nh = /* @__PURE__ */ new WeakMap();
function Tn(t) {
  return Nh.get(t) || 1;
}
function L0(t, e) {
  return { constTimeNegate: An, hasPrecomputes(i) {
    return Tn(i) !== 1;
  }, unsafeLadder(i, r, s = t.ZERO) {
    let n = i;
    for (; r > uc; )
      r & us && (s = s.add(n)), n = n.double(), r >>= us;
    return s;
  }, precomputeWindow(i, r) {
    const { windows: s, windowSize: n } = $n(r, e), o = [];
    let a = i, c = a;
    for (let u = 0; u < s; u++) {
      c = a, o.push(c);
      for (let h = 1; h < n; h++)
        c = c.add(a), o.push(c);
      a = c.double();
    }
    return o;
  }, wNAF(i, r, s) {
    const { windows: n, windowSize: o } = $n(i, e);
    let a = t.ZERO, c = t.BASE;
    const u = BigInt(2 ** i - 1), h = 2 ** i, l = BigInt(i);
    for (let f = 0; f < n; f++) {
      const p = f * o;
      let d = Number(s & u);
      s >>= l, d > o && (d -= h, s += us);
      const g = p, y = p + Math.abs(d) - 1, E = f % 2 !== 0, v = d < 0;
      d === 0 ? c = c.add(An(E, r[g])) : a = a.add(An(v, r[y]));
    }
    return { p: a, f: c };
  }, wNAFUnsafe(i, r, s, n = t.ZERO) {
    const { windows: o, windowSize: a } = $n(i, e), c = BigInt(2 ** i - 1), u = 2 ** i, h = BigInt(i);
    for (let l = 0; l < o; l++) {
      const f = l * a;
      if (s === uc)
        break;
      let p = Number(s & c);
      if (s >>= h, p > a && (p -= u, s += us), p === 0)
        continue;
      let d = r[f + Math.abs(p) - 1];
      p < 0 && (d = d.negate()), n = n.add(d);
    }
    return n;
  }, getPrecomputes(i, r, s) {
    let n = On.get(r);
    return n || (n = this.precomputeWindow(r, i), i !== 1 && On.set(r, s(n))), n;
  }, wNAFCached(i, r, s) {
    const n = Tn(i);
    return this.wNAF(n, this.getPrecomputes(n, i, s), r);
  }, wNAFCachedUnsafe(i, r, s, n) {
    const o = Tn(i);
    return o === 1 ? this.unsafeLadder(i, r, n) : this.wNAFUnsafe(o, this.getPrecomputes(o, i, s), r, n);
  }, setWindowSize(i, r) {
    Bh(r, e), Nh.set(i, r), On.delete(i);
  } };
}
function M0(t, e, i, r) {
  if (N0(i, t), k0(r, e), i.length !== r.length)
    throw new Error("arrays of points and scalars must have equal length");
  const s = t.ZERO, n = S0(BigInt(i.length)), o = n > 12 ? n - 3 : n > 4 ? n - 2 : n ? 2 : 1, a = (1 << o) - 1, c = new Array(a + 1).fill(s), u = Math.floor((e.BITS - 1) / o) * o;
  let h = s;
  for (let l = u; l >= 0; l -= o) {
    c.fill(s);
    for (let p = 0; p < r.length; p++) {
      const d = r[p], g = Number(d >> BigInt(l) & BigInt(a));
      c[g] = c[g].add(i[p]);
    }
    let f = s;
    for (let p = c.length - 1, d = s; p > 0; p--)
      d = d.add(c[p]), f = f.add(d);
    if (h = h.add(f), l !== 0)
      for (let p = 0; p < o; p++)
        h = h.double();
  }
  return h;
}
function q0(t) {
  return F0(t.Fp), Jo(t, { n: "bigint", h: "bigint", Gx: "field", Gy: "field" }, { nBitLength: "isSafeInteger", nByteLength: "isSafeInteger" }), Object.freeze({ ...Fh(t.n, t.nBitLength), ...t, p: t.Fp.ORDER });
}
const dt = BigInt(0), ze = BigInt(1), hs = BigInt(2), j0 = BigInt(8), z0 = { zip215: !0 };
function K0(t) {
  const e = q0(t);
  return Jo(t, { hash: "function", a: "bigint", d: "bigint", randomBytes: "function" }, { adjustScalarBytes: "function", domain: "function", uvRatio: "function", mapToCurve: "function" }), Object.freeze({ ...e });
}
function V0(t) {
  const e = K0(t), { Fp: i, n: r, prehash: s, hash: n, randomBytes: o, nByteLength: a, h: c } = e, u = hs << BigInt(a * 8) - ze, h = i.create, l = Uh(e.n, e.nBitLength), f = e.uvRatio || ((x, b) => {
    try {
      return { isValid: !0, value: i.sqrt(x * i.inv(b)) };
    } catch {
      return { isValid: !1, value: dt };
    }
  }), p = e.adjustScalarBytes || ((x) => x), d = e.domain || ((x, b, S) => {
    if (Sn("phflag", S), b.length || S)
      throw new Error("Contexts/pre-hash are not supported");
    return x;
  });
  function g(x, b) {
    ur("coordinate " + x, b, dt, u);
  }
  function y(x) {
    if (!(x instanceof m))
      throw new Error("ExtendedPoint expected");
  }
  const E = nc((x, b) => {
    const { ex: S, ey: T, ez: A } = x, U = x.is0();
    b == null && (b = U ? j0 : i.inv(A));
    const N = h(S * b), j = h(T * b), z = h(A * b);
    if (U)
      return { x: dt, y: ze };
    if (z !== ze)
      throw new Error("invZ was invalid");
    return { x: N, y: j };
  }), v = nc((x) => {
    const { a: b, d: S } = e;
    if (x.is0())
      throw new Error("bad point: ZERO");
    const { ex: T, ey: A, ez: U, et: N } = x, j = h(T * T), z = h(A * A), K = h(U * U), V = h(K * K), H = h(j * b), re = h(K * h(H + z)), ie = h(V + h(S * h(j * z)));
    if (re !== ie)
      throw new Error("bad point: equation left != right (1)");
    const J = h(T * A), fe = h(U * N);
    if (J !== fe)
      throw new Error("bad point: equation left != right (2)");
    return !0;
  });
  class m {
    constructor(b, S, T, A) {
      this.ex = b, this.ey = S, this.ez = T, this.et = A, g("x", b), g("y", S), g("z", T), g("t", A), Object.freeze(this);
    }
    get x() {
      return this.toAffine().x;
    }
    get y() {
      return this.toAffine().y;
    }
    static fromAffine(b) {
      if (b instanceof m)
        throw new Error("extended point not allowed");
      const { x: S, y: T } = b || {};
      return g("x", S), g("y", T), new m(S, T, ze, h(S * T));
    }
    static normalizeZ(b) {
      const S = i.invertBatch(b.map((T) => T.ez));
      return b.map((T, A) => T.toAffine(S[A])).map(m.fromAffine);
    }
    static msm(b, S) {
      return M0(m, l, b, S);
    }
    _setWindowSize(b) {
      R.setWindowSize(this, b);
    }
    assertValidity() {
      v(this);
    }
    equals(b) {
      y(b);
      const { ex: S, ey: T, ez: A } = this, { ex: U, ey: N, ez: j } = b, z = h(S * j), K = h(U * A), V = h(T * j), H = h(N * A);
      return z === K && V === H;
    }
    is0() {
      return this.equals(m.ZERO);
    }
    negate() {
      return new m(h(-this.ex), this.ey, this.ez, h(-this.et));
    }
    double() {
      const { a: b } = e, { ex: S, ey: T, ez: A } = this, U = h(S * S), N = h(T * T), j = h(hs * h(A * A)), z = h(b * U), K = S + T, V = h(h(K * K) - U - N), H = z + N, re = H - j, ie = z - N, J = h(V * re), fe = h(H * ie), Ie = h(V * ie), ui = h(re * H);
      return new m(J, fe, ui, Ie);
    }
    add(b) {
      y(b);
      const { a: S, d: T } = e, { ex: A, ey: U, ez: N, et: j } = this, { ex: z, ey: K, ez: V, et: H } = b;
      if (S === BigInt(-1)) {
        const Aa = h((U - A) * (K + z)), $a = h((U + A) * (K - z)), yn = h($a - Aa);
        if (yn === dt)
          return this.double();
        const Oa = h(N * hs * H), Ta = h(j * hs * V), Ca = Ta + Oa, Pa = $a + Aa, Ra = Ta - Oa, wd = h(Ca * yn), md = h(Pa * Ra), bd = h(Ca * Ra), vd = h(yn * Pa);
        return new m(wd, md, vd, bd);
      }
      const re = h(A * z), ie = h(U * K), J = h(j * T * H), fe = h(N * V), Ie = h((A + U) * (z + K) - re - ie), ui = fe - J, ss = fe + J, Fi = h(ie - S * re), gn = h(Ie * ui), pd = h(ss * Fi), gd = h(Ie * Fi), yd = h(ui * ss);
      return new m(gn, pd, yd, gd);
    }
    subtract(b) {
      return this.add(b.negate());
    }
    wNAF(b) {
      return R.wNAFCached(this, b, m.normalizeZ);
    }
    multiply(b) {
      const S = b;
      ur("scalar", S, ze, r);
      const { p: T, f: A } = this.wNAF(S);
      return m.normalizeZ([T, A])[0];
    }
    multiplyUnsafe(b, S = m.ZERO) {
      const T = b;
      return ur("scalar", T, dt, r), T === dt ? I : this.is0() || T === ze ? this : R.wNAFCachedUnsafe(this, T, m.normalizeZ, S);
    }
    isSmallOrder() {
      return this.multiplyUnsafe(c).is0();
    }
    isTorsionFree() {
      return R.unsafeLadder(this, r).is0();
    }
    toAffine(b) {
      return E(this, b);
    }
    clearCofactor() {
      const { h: b } = e;
      return b === ze ? this : this.multiplyUnsafe(b);
    }
    static fromHex(b, S = !1) {
      const { d: T, a: A } = e, U = i.BYTES;
      b = Ct("pointHex", b, U), Sn("zip215", S);
      const N = b.slice(), j = b[U - 1];
      N[U - 1] = j & -129;
      const z = Ss(N), K = S ? u : i.ORDER;
      ur("pointHex.y", z, dt, K);
      const V = h(z * z), H = h(V - ze), re = h(T * V - A);
      let { isValid: ie, value: J } = f(H, re);
      if (!ie)
        throw new Error("Point.fromHex: invalid y coordinate");
      const fe = (J & ze) === ze, Ie = (j & 128) !== 0;
      if (!S && J === dt && Ie)
        throw new Error("Point.fromHex: x=0 and x_0=1");
      return Ie !== fe && (J = h(-J)), m.fromAffine({ x: J, y: z });
    }
    static fromPrivateKey(b) {
      return w(b).point;
    }
    toRawBytes() {
      const { x: b, y: S } = this.toAffine(), T = oo(S, i.BYTES);
      return T[T.length - 1] |= b & ze ? 128 : 0, T;
    }
    toHex() {
      return Yo(this.toRawBytes());
    }
  }
  m.BASE = new m(e.Gx, e.Gy, ze, h(e.Gx * e.Gy)), m.ZERO = new m(dt, ze, ze, dt);
  const { BASE: D, ZERO: I } = m, R = L0(m, a * 8);
  function B(x) {
    return be(x, r);
  }
  function C(x) {
    return B(Ss(x));
  }
  function w(x) {
    const b = i.BYTES;
    x = Ct("private key", x, b);
    const S = Ct("hashed private key", n(x), 2 * b), T = p(S.slice(0, b)), A = S.slice(b, 2 * b), U = C(T), N = D.multiply(U), j = N.toRawBytes();
    return { head: T, prefix: A, scalar: U, point: N, pointBytes: j };
  }
  function O(x) {
    return w(x).pointBytes;
  }
  function _(x = new Uint8Array(), ...b) {
    const S = sc(...b);
    return C(n(d(S, Ct("context", x), !!s)));
  }
  function $(x, b, S = {}) {
    x = Ct("message", x), s && (x = s(x));
    const { prefix: T, scalar: A, pointBytes: U } = w(b), N = _(S.context, T, x), j = D.multiply(N).toRawBytes(), z = _(S.context, j, U, x), K = B(N + z * A);
    ur("signature.s", K, dt, r);
    const V = sc(j, oo(K, i.BYTES));
    return Ct("result", V, i.BYTES * 2);
  }
  const P = z0;
  function k(x, b, S, T = P) {
    const { context: A, zip215: U } = T, N = i.BYTES;
    x = Ct("signature", x, 2 * N), b = Ct("message", b), S = Ct("publicKey", S, N), U !== void 0 && Sn("zip215", U), s && (b = s(b));
    const j = Ss(x.slice(N, 2 * N));
    let z, K, V;
    try {
      z = m.fromHex(S, U), K = m.fromHex(x.slice(0, N), U), V = D.multiplyUnsafe(j);
    } catch {
      return !1;
    }
    if (!U && z.isSmallOrder())
      return !1;
    const H = _(A, K.toRawBytes(), z.toRawBytes(), b);
    return K.add(z.multiplyUnsafe(H)).subtract(V).clearCofactor().equals(m.ZERO);
  }
  return D._setWindowSize(8), { CURVE: e, getPublicKey: O, sign: $, verify: k, ExtendedPoint: m, utils: { getExtendedPublicKey: w, randomPrivateKey: () => o(i.BYTES), precompute(x = 8, b = m.BASE) {
    return b._setWindowSize(x), b.multiply(BigInt(3)), b;
  } } };
}
BigInt(0), BigInt(1);
const Zo = BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"), hc = BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");
BigInt(0);
const H0 = BigInt(1), lc = BigInt(2);
BigInt(3);
const W0 = BigInt(5), G0 = BigInt(8);
function Y0(t) {
  const e = BigInt(10), i = BigInt(20), r = BigInt(40), s = BigInt(80), n = Zo, o = t * t % n * t % n, a = bt(o, lc, n) * o % n, c = bt(a, H0, n) * t % n, u = bt(c, W0, n) * c % n, h = bt(u, e, n) * u % n, l = bt(h, i, n) * h % n, f = bt(l, r, n) * l % n, p = bt(f, s, n) * f % n, d = bt(p, s, n) * f % n, g = bt(d, e, n) * u % n;
  return { pow_p_5_8: bt(g, lc, n) * t % n, b2: o };
}
function J0(t) {
  return t[0] &= 248, t[31] &= 127, t[31] |= 64, t;
}
function Z0(t, e) {
  const i = Zo, r = be(e * e * e, i), s = be(r * r * e, i), n = Y0(t * s).pow_p_5_8;
  let o = be(t * r * n, i);
  const a = be(e * o * o, i), c = o, u = be(o * hc, i), h = a === t, l = a === be(-t, i), f = a === be(-t * hc, i);
  return h && (o = c), (l || f) && (o = u), P0(o, i) && (o = be(-o, i)), { isValid: h || l, value: o };
}
const Q0 = (() => Uh(Zo, void 0, !0))(), X0 = (() => ({ a: BigInt(-1), d: BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"), Fp: Q0, n: BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"), h: G0, Gx: BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"), Gy: BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"), hash: v0, randomBytes: $h, adjustScalarBytes: J0, uvRatio: Z0 }))(), kh = (() => V0(X0))(), ey = "EdDSA", ty = "JWT", Fs = ".", Qs = "base64url", Lh = "utf8", Mh = "utf8", iy = ":", ry = "did", sy = "key", fc = "base58btc", ny = "z", oy = "K36", ay = 32;
function Qo(t) {
  return globalThis.Buffer != null ? new Uint8Array(t.buffer, t.byteOffset, t.byteLength) : t;
}
function qh(t = 0) {
  return globalThis.Buffer != null && globalThis.Buffer.allocUnsafe != null ? Qo(globalThis.Buffer.allocUnsafe(t)) : new Uint8Array(t);
}
function jh(t, e) {
  e || (e = t.reduce((s, n) => s + n.length, 0));
  const i = qh(e);
  let r = 0;
  for (const s of t)
    i.set(s, r), r += s.length;
  return Qo(i);
}
function cy(t, e) {
  if (t.length >= 255)
    throw new TypeError("Alphabet too long");
  for (var i = new Uint8Array(256), r = 0; r < i.length; r++)
    i[r] = 255;
  for (var s = 0; s < t.length; s++) {
    var n = t.charAt(s), o = n.charCodeAt(0);
    if (i[o] !== 255)
      throw new TypeError(n + " is ambiguous");
    i[o] = s;
  }
  var a = t.length, c = t.charAt(0), u = Math.log(a) / Math.log(256), h = Math.log(256) / Math.log(a);
  function l(d) {
    if (d instanceof Uint8Array || (ArrayBuffer.isView(d) ? d = new Uint8Array(d.buffer, d.byteOffset, d.byteLength) : Array.isArray(d) && (d = Uint8Array.from(d))), !(d instanceof Uint8Array))
      throw new TypeError("Expected Uint8Array");
    if (d.length === 0)
      return "";
    for (var g = 0, y = 0, E = 0, v = d.length; E !== v && d[E] === 0; )
      E++, g++;
    for (var m = (v - E) * h + 1 >>> 0, D = new Uint8Array(m); E !== v; ) {
      for (var I = d[E], R = 0, B = m - 1; (I !== 0 || R < y) && B !== -1; B--, R++)
        I += 256 * D[B] >>> 0, D[B] = I % a >>> 0, I = I / a >>> 0;
      if (I !== 0)
        throw new Error("Non-zero carry");
      y = R, E++;
    }
    for (var C = m - y; C !== m && D[C] === 0; )
      C++;
    for (var w = c.repeat(g); C < m; ++C)
      w += t.charAt(D[C]);
    return w;
  }
  function f(d) {
    if (typeof d != "string")
      throw new TypeError("Expected String");
    if (d.length === 0)
      return new Uint8Array();
    var g = 0;
    if (d[g] !== " ") {
      for (var y = 0, E = 0; d[g] === c; )
        y++, g++;
      for (var v = (d.length - g) * u + 1 >>> 0, m = new Uint8Array(v); d[g]; ) {
        var D = i[d.charCodeAt(g)];
        if (D === 255)
          return;
        for (var I = 0, R = v - 1; (D !== 0 || I < E) && R !== -1; R--, I++)
          D += a * m[R] >>> 0, m[R] = D % 256 >>> 0, D = D / 256 >>> 0;
        if (D !== 0)
          throw new Error("Non-zero carry");
        E = I, g++;
      }
      if (d[g] !== " ") {
        for (var B = v - E; B !== v && m[B] === 0; )
          B++;
        for (var C = new Uint8Array(y + (v - B)), w = y; B !== v; )
          C[w++] = m[B++];
        return C;
      }
    }
  }
  function p(d) {
    var g = f(d);
    if (g)
      return g;
    throw new Error(`Non-${e} character`);
  }
  return { encode: l, decodeUnsafe: f, decode: p };
}
var uy = cy, hy = uy;
const zh = (t) => {
  if (t instanceof Uint8Array && t.constructor.name === "Uint8Array")
    return t;
  if (t instanceof ArrayBuffer)
    return new Uint8Array(t);
  if (ArrayBuffer.isView(t))
    return new Uint8Array(t.buffer, t.byteOffset, t.byteLength);
  throw new Error("Unknown type, must be binary type");
}, ly = (t) => new TextEncoder().encode(t), fy = (t) => new TextDecoder().decode(t);
let dy = class {
  constructor(e, i, r) {
    this.name = e, this.prefix = i, this.baseEncode = r;
  }
  encode(e) {
    if (e instanceof Uint8Array)
      return `${this.prefix}${this.baseEncode(e)}`;
    throw Error("Unknown type, must be binary type");
  }
}, py = class {
  constructor(e, i, r) {
    if (this.name = e, this.prefix = i, i.codePointAt(0) === void 0)
      throw new Error("Invalid prefix character");
    this.prefixCodePoint = i.codePointAt(0), this.baseDecode = r;
  }
  decode(e) {
    if (typeof e == "string") {
      if (e.codePointAt(0) !== this.prefixCodePoint)
        throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);
      return this.baseDecode(e.slice(this.prefix.length));
    } else
      throw Error("Can only multibase decode strings");
  }
  or(e) {
    return Kh(this, e);
  }
}, gy = class {
  constructor(e) {
    this.decoders = e;
  }
  or(e) {
    return Kh(this, e);
  }
  decode(e) {
    const i = e[0], r = this.decoders[i];
    if (r)
      return r.decode(e);
    throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`);
  }
};
const Kh = (t, e) => new gy({ ...t.decoders || { [t.prefix]: t }, ...e.decoders || { [e.prefix]: e } });
let yy = class {
  constructor(e, i, r, s) {
    this.name = e, this.prefix = i, this.baseEncode = r, this.baseDecode = s, this.encoder = new dy(e, i, r), this.decoder = new py(e, i, s);
  }
  encode(e) {
    return this.encoder.encode(e);
  }
  decode(e) {
    return this.decoder.decode(e);
  }
};
const Xs = ({ name: t, prefix: e, encode: i, decode: r }) => new yy(t, e, i, r), Jr = ({ prefix: t, name: e, alphabet: i }) => {
  const { encode: r, decode: s } = hy(i, e);
  return Xs({ prefix: t, name: e, encode: r, decode: (n) => zh(s(n)) });
}, wy = (t, e, i, r) => {
  const s = {};
  for (let h = 0; h < e.length; ++h)
    s[e[h]] = h;
  let n = t.length;
  for (; t[n - 1] === "="; )
    --n;
  const o = new Uint8Array(n * i / 8 | 0);
  let a = 0, c = 0, u = 0;
  for (let h = 0; h < n; ++h) {
    const l = s[t[h]];
    if (l === void 0)
      throw new SyntaxError(`Non-${r} character`);
    c = c << i | l, a += i, a >= 8 && (a -= 8, o[u++] = 255 & c >> a);
  }
  if (a >= i || 255 & c << 8 - a)
    throw new SyntaxError("Unexpected end of data");
  return o;
}, my = (t, e, i) => {
  const r = e[e.length - 1] === "=", s = (1 << i) - 1;
  let n = "", o = 0, a = 0;
  for (let c = 0; c < t.length; ++c)
    for (a = a << 8 | t[c], o += 8; o > i; )
      o -= i, n += e[s & a >> o];
  if (o && (n += e[s & a << i - o]), r)
    for (; n.length * i & 7; )
      n += "=";
  return n;
}, Te = ({ name: t, prefix: e, bitsPerChar: i, alphabet: r }) => Xs({ prefix: e, name: t, encode(s) {
  return my(s, r, i);
}, decode(s) {
  return wy(s, r, i, t);
} }), by = Xs({ prefix: "\0", name: "identity", encode: (t) => fy(t), decode: (t) => ly(t) });
var vy = Object.freeze({ __proto__: null, identity: by });
const Ey = Te({ prefix: "0", name: "base2", alphabet: "01", bitsPerChar: 1 });
var _y = Object.freeze({ __proto__: null, base2: Ey });
const xy = Te({ prefix: "7", name: "base8", alphabet: "01234567", bitsPerChar: 3 });
var Iy = Object.freeze({ __proto__: null, base8: xy });
const Sy = Jr({ prefix: "9", name: "base10", alphabet: "0123456789" });
var Dy = Object.freeze({ __proto__: null, base10: Sy });
const Ay = Te({ prefix: "f", name: "base16", alphabet: "0123456789abcdef", bitsPerChar: 4 }), $y = Te({ prefix: "F", name: "base16upper", alphabet: "0123456789ABCDEF", bitsPerChar: 4 });
var Oy = Object.freeze({ __proto__: null, base16: Ay, base16upper: $y });
const Ty = Te({ prefix: "b", name: "base32", alphabet: "abcdefghijklmnopqrstuvwxyz234567", bitsPerChar: 5 }), Cy = Te({ prefix: "B", name: "base32upper", alphabet: "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567", bitsPerChar: 5 }), Py = Te({ prefix: "c", name: "base32pad", alphabet: "abcdefghijklmnopqrstuvwxyz234567=", bitsPerChar: 5 }), Ry = Te({ prefix: "C", name: "base32padupper", alphabet: "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=", bitsPerChar: 5 }), Fy = Te({ prefix: "v", name: "base32hex", alphabet: "0123456789abcdefghijklmnopqrstuv", bitsPerChar: 5 }), Uy = Te({ prefix: "V", name: "base32hexupper", alphabet: "0123456789ABCDEFGHIJKLMNOPQRSTUV", bitsPerChar: 5 }), By = Te({ prefix: "t", name: "base32hexpad", alphabet: "0123456789abcdefghijklmnopqrstuv=", bitsPerChar: 5 }), Ny = Te({ prefix: "T", name: "base32hexpadupper", alphabet: "0123456789ABCDEFGHIJKLMNOPQRSTUV=", bitsPerChar: 5 }), ky = Te({ prefix: "h", name: "base32z", alphabet: "ybndrfg8ejkmcpqxot1uwisza345h769", bitsPerChar: 5 });
var Ly = Object.freeze({ __proto__: null, base32: Ty, base32upper: Cy, base32pad: Py, base32padupper: Ry, base32hex: Fy, base32hexupper: Uy, base32hexpad: By, base32hexpadupper: Ny, base32z: ky });
const My = Jr({ prefix: "k", name: "base36", alphabet: "0123456789abcdefghijklmnopqrstuvwxyz" }), qy = Jr({ prefix: "K", name: "base36upper", alphabet: "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ" });
var jy = Object.freeze({ __proto__: null, base36: My, base36upper: qy });
const zy = Jr({ name: "base58btc", prefix: "z", alphabet: "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" }), Ky = Jr({ name: "base58flickr", prefix: "Z", alphabet: "123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ" });
var Vy = Object.freeze({ __proto__: null, base58btc: zy, base58flickr: Ky });
const Hy = Te({ prefix: "m", name: "base64", alphabet: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/", bitsPerChar: 6 }), Wy = Te({ prefix: "M", name: "base64pad", alphabet: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=", bitsPerChar: 6 }), Gy = Te({ prefix: "u", name: "base64url", alphabet: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_", bitsPerChar: 6 }), Yy = Te({ prefix: "U", name: "base64urlpad", alphabet: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=", bitsPerChar: 6 });
var Jy = Object.freeze({ __proto__: null, base64: Hy, base64pad: Wy, base64url: Gy, base64urlpad: Yy });
const Vh = Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"), Zy = Vh.reduce((t, e, i) => (t[i] = e, t), []), Qy = Vh.reduce((t, e, i) => (t[e.codePointAt(0)] = i, t), []);
function Xy(t) {
  return t.reduce((e, i) => (e += Zy[i], e), "");
}
function e1(t) {
  const e = [];
  for (const i of t) {
    const r = Qy[i.codePointAt(0)];
    if (r === void 0)
      throw new Error(`Non-base256emoji character: ${i}`);
    e.push(r);
  }
  return new Uint8Array(e);
}
const t1 = Xs({ prefix: "🚀", name: "base256emoji", encode: Xy, decode: e1 });
var i1 = Object.freeze({ __proto__: null, base256emoji: t1 }), r1 = Hh, dc = 128, s1 = 127, n1 = ~s1, o1 = Math.pow(2, 31);
function Hh(t, e, i) {
  e = e || [], i = i || 0;
  for (var r = i; t >= o1; )
    e[i++] = t & 255 | dc, t /= 128;
  for (; t & n1; )
    e[i++] = t & 255 | dc, t >>>= 7;
  return e[i] = t | 0, Hh.bytes = i - r + 1, e;
}
var a1 = co, c1 = 128, pc = 127;
function co(t, r) {
  var i = 0, r = r || 0, s = 0, n = r, o, a = t.length;
  do {
    if (n >= a)
      throw co.bytes = 0, new RangeError("Could not decode varint");
    o = t[n++], i += s < 28 ? (o & pc) << s : (o & pc) * Math.pow(2, s), s += 7;
  } while (o >= c1);
  return co.bytes = n - r, i;
}
var u1 = Math.pow(2, 7), h1 = Math.pow(2, 14), l1 = Math.pow(2, 21), f1 = Math.pow(2, 28), d1 = Math.pow(2, 35), p1 = Math.pow(2, 42), g1 = Math.pow(2, 49), y1 = Math.pow(2, 56), w1 = Math.pow(2, 63), m1 = function(t) {
  return t < u1 ? 1 : t < h1 ? 2 : t < l1 ? 3 : t < f1 ? 4 : t < d1 ? 5 : t < p1 ? 6 : t < g1 ? 7 : t < y1 ? 8 : t < w1 ? 9 : 10;
}, b1 = { encode: r1, decode: a1, encodingLength: m1 }, Wh = b1;
const gc = (t, e, i = 0) => (Wh.encode(t, e, i), e), yc = (t) => Wh.encodingLength(t), uo = (t, e) => {
  const i = e.byteLength, r = yc(t), s = r + yc(i), n = new Uint8Array(s + i);
  return gc(t, n, 0), gc(i, n, r), n.set(e, s), new v1(t, i, e, n);
};
let v1 = class {
  constructor(e, i, r, s) {
    this.code = e, this.size = i, this.digest = r, this.bytes = s;
  }
};
const Gh = ({ name: t, code: e, encode: i }) => new E1(t, e, i);
let E1 = class {
  constructor(e, i, r) {
    this.name = e, this.code = i, this.encode = r;
  }
  digest(e) {
    if (e instanceof Uint8Array) {
      const i = this.encode(e);
      return i instanceof Uint8Array ? uo(this.code, i) : i.then((r) => uo(this.code, r));
    } else
      throw Error("Unknown type, must be binary type");
  }
};
const Yh = (t) => async (e) => new Uint8Array(await crypto.subtle.digest(t, e)), _1 = Gh({ name: "sha2-256", code: 18, encode: Yh("SHA-256") }), x1 = Gh({ name: "sha2-512", code: 19, encode: Yh("SHA-512") });
var I1 = Object.freeze({ __proto__: null, sha256: _1, sha512: x1 });
const Jh = 0, S1 = "identity", Zh = zh, D1 = (t) => uo(Jh, Zh(t)), A1 = { code: Jh, name: S1, encode: Zh, digest: D1 };
var $1 = Object.freeze({ __proto__: null, identity: A1 });
new TextEncoder(), new TextDecoder();
const wc = { ...vy, ..._y, ...Iy, ...Dy, ...Oy, ...Ly, ...jy, ...Vy, ...Jy, ...i1 };
({ ...I1, ...$1 });
function Qh(t, e, i, r) {
  return { name: t, prefix: e, encoder: { name: t, prefix: e, encode: i }, decoder: { decode: r } };
}
const mc = Qh("utf8", "u", (t) => "u" + new TextDecoder("utf8").decode(t), (t) => new TextEncoder().encode(t.substring(1))), Cn = Qh("ascii", "a", (t) => {
  let e = "a";
  for (let i = 0; i < t.length; i++)
    e += String.fromCharCode(t[i]);
  return e;
}, (t) => {
  t = t.substring(1);
  const e = qh(t.length);
  for (let i = 0; i < t.length; i++)
    e[i] = t.charCodeAt(i);
  return e;
}), Xh = { utf8: mc, "utf-8": mc, hex: wc.base16, latin1: Cn, ascii: Cn, binary: Cn, ...wc };
function en(t, e = "utf8") {
  const i = Xh[e];
  if (!i)
    throw new Error(`Unsupported encoding "${e}"`);
  return (e === "utf8" || e === "utf-8") && globalThis.Buffer != null && globalThis.Buffer.from != null ? globalThis.Buffer.from(t.buffer, t.byteOffset, t.byteLength).toString("utf8") : i.encoder.encode(t).substring(1);
}
function Xi(t, e = "utf8") {
  const i = Xh[e];
  if (!i)
    throw new Error(`Unsupported encoding "${e}"`);
  return (e === "utf8" || e === "utf-8") && globalThis.Buffer != null && globalThis.Buffer.from != null ? Qo(globalThis.Buffer.from(t, "utf-8")) : i.decoder.decode(`${i.prefix}${t}`);
}
function bc(t) {
  return Yi(en(Xi(t, Qs), Lh));
}
function Us(t) {
  return en(Xi(Ii(t), Lh), Qs);
}
function el(t) {
  const e = Xi(oy, fc), i = ny + en(jh([e, t]), fc);
  return [ry, sy, i].join(iy);
}
function O1(t) {
  return en(t, Qs);
}
function T1(t) {
  return Xi(t, Qs);
}
function C1(t) {
  return Xi([Us(t.header), Us(t.payload)].join(Fs), Mh);
}
function P1(t) {
  return [Us(t.header), Us(t.payload), O1(t.signature)].join(Fs);
}
function ho(t) {
  const e = t.split(Fs), i = bc(e[0]), r = bc(e[1]), s = T1(e[2]), n = Xi(e.slice(0, 2).join(Fs), Mh);
  return { header: i, payload: r, signature: s, data: n };
}
function vc(t = $h(ay)) {
  const e = kh.getPublicKey(t);
  return { secretKey: jh([t, e]), publicKey: e };
}
async function R1(t, e, i, r, s = L.fromMiliseconds(Date.now())) {
  const n = { alg: ey, typ: ty }, o = el(r.publicKey), a = s + i, c = { iss: o, sub: t, aud: e, iat: s, exp: a }, u = C1({ header: n, payload: c }), h = kh.sign(u, r.secretKey.slice(0, 32));
  return P1({ header: n, payload: c, signature: h });
}
var ue = {};
Object.defineProperty(ue, "__esModule", { value: !0 });
ue.getLocalStorage = ue.getLocalStorageOrThrow = ue.getCrypto = ue.getCryptoOrThrow = tl = ue.getLocation = ue.getLocationOrThrow = Xo = ue.getNavigator = ue.getNavigatorOrThrow = Si = ue.getDocument = ue.getDocumentOrThrow = ue.getFromWindowOrThrow = ue.getFromWindow = void 0;
function Pi(t) {
  let e;
  return typeof window < "u" && typeof window[t] < "u" && (e = window[t]), e;
}
ue.getFromWindow = Pi;
function er(t) {
  const e = Pi(t);
  if (!e)
    throw new Error(`${t} is not defined in Window`);
  return e;
}
ue.getFromWindowOrThrow = er;
function F1() {
  return er("document");
}
ue.getDocumentOrThrow = F1;
function U1() {
  return Pi("document");
}
var Si = ue.getDocument = U1;
function B1() {
  return er("navigator");
}
ue.getNavigatorOrThrow = B1;
function N1() {
  return Pi("navigator");
}
var Xo = ue.getNavigator = N1;
function k1() {
  return er("location");
}
ue.getLocationOrThrow = k1;
function L1() {
  return Pi("location");
}
var tl = ue.getLocation = L1;
function M1() {
  return er("crypto");
}
ue.getCryptoOrThrow = M1;
function q1() {
  return Pi("crypto");
}
ue.getCrypto = q1;
function j1() {
  return er("localStorage");
}
ue.getLocalStorageOrThrow = j1;
function z1() {
  return Pi("localStorage");
}
ue.getLocalStorage = z1;
var ea = {};
Object.defineProperty(ea, "__esModule", { value: !0 });
var il = ea.getWindowMetadata = void 0;
const Ec = ue;
function K1() {
  let t, e;
  try {
    t = Ec.getDocumentOrThrow(), e = Ec.getLocationOrThrow();
  } catch {
    return null;
  }
  function i() {
    const l = t.getElementsByTagName("link"), f = [];
    for (let p = 0; p < l.length; p++) {
      const d = l[p], g = d.getAttribute("rel");
      if (g && g.toLowerCase().indexOf("icon") > -1) {
        const y = d.getAttribute("href");
        if (y)
          if (y.toLowerCase().indexOf("https:") === -1 && y.toLowerCase().indexOf("http:") === -1 && y.indexOf("//") !== 0) {
            let E = e.protocol + "//" + e.host;
            if (y.indexOf("/") === 0)
              E += y;
            else {
              const v = e.pathname.split("/");
              v.pop();
              const m = v.join("/");
              E += m + "/" + y;
            }
            f.push(E);
          } else if (y.indexOf("//") === 0) {
            const E = e.protocol + y;
            f.push(E);
          } else
            f.push(y);
      }
    }
    return f;
  }
  function r(...l) {
    const f = t.getElementsByTagName("meta");
    for (let p = 0; p < f.length; p++) {
      const d = f[p], g = ["itemprop", "property", "name"].map((y) => d.getAttribute(y)).filter((y) => y ? l.includes(y) : !1);
      if (g.length && g) {
        const y = d.getAttribute("content");
        if (y)
          return y;
      }
    }
    return "";
  }
  function s() {
    let l = r("name", "og:site_name", "og:title", "twitter:title");
    return l || (l = t.title), l;
  }
  function n() {
    return r("description", "og:description", "twitter:description", "keywords");
  }
  const o = s(), a = n(), c = e.origin, u = i();
  return {
    description: a,
    url: c,
    icons: u,
    name: o
  };
}
il = ea.getWindowMetadata = K1;
function Lr(t, { strict: e = !0 } = {}) {
  return !t || typeof t != "string" ? !1 : e ? /^0x[0-9a-fA-F]*$/.test(t) : t.startsWith("0x");
}
function lo(t) {
  return Lr(t, { strict: !1 }) ? Math.ceil((t.length - 2) / 2) : t.length;
}
const rl = "2.31.0";
let Pn = {
  getDocsUrl: ({ docsBaseUrl: t, docsPath: e = "", docsSlug: i }) => e ? `${t ?? "https://viem.sh"}${e}${i ? `#${i}` : ""}` : void 0,
  version: `viem@${rl}`
};
class Di extends Error {
  constructor(e, i = {}) {
    const r = (() => i.cause instanceof Di ? i.cause.details : i.cause?.message ? i.cause.message : i.details)(), s = (() => i.cause instanceof Di && i.cause.docsPath || i.docsPath)(), n = Pn.getDocsUrl?.({ ...i, docsPath: s }), o = [
      e || "An error occurred.",
      "",
      ...i.metaMessages ? [...i.metaMessages, ""] : [],
      ...n ? [`Docs: ${n}`] : [],
      ...r ? [`Details: ${r}`] : [],
      ...Pn.version ? [`Version: ${Pn.version}`] : []
    ].join(`
`);
    super(o, i.cause ? { cause: i.cause } : void 0), Object.defineProperty(this, "details", {
      enumerable: !0,
      configurable: !0,
      writable: !0,
      value: void 0
    }), Object.defineProperty(this, "docsPath", {
      enumerable: !0,
      configurable: !0,
      writable: !0,
      value: void 0
    }), Object.defineProperty(this, "metaMessages", {
      enumerable: !0,
      configurable: !0,
      writable: !0,
      value: void 0
    }), Object.defineProperty(this, "shortMessage", {
      enumerable: !0,
      configurable: !0,
      writable: !0,
      value: void 0
    }), Object.defineProperty(this, "version", {
      enumerable: !0,
      configurable: !0,
      writable: !0,
      value: void 0
    }), Object.defineProperty(this, "name", {
      enumerable: !0,
      configurable: !0,
      writable: !0,
      value: "BaseError"
    }), this.details = r, this.docsPath = s, this.metaMessages = i.metaMessages, this.name = i.name ?? this.name, this.shortMessage = e, this.version = rl;
  }
  walk(e) {
    return sl(this, e);
  }
}
function sl(t, e) {
  return e?.(t) ? t : t && typeof t == "object" && "cause" in t && t.cause !== void 0 ? sl(t.cause, e) : e ? null : t;
}
class nl extends Di {
  constructor({ size: e, targetSize: i, type: r }) {
    super(`${r.charAt(0).toUpperCase()}${r.slice(1).toLowerCase()} size (${e}) exceeds padding size (${i}).`, { name: "SizeExceedsPaddingSizeError" });
  }
}
function tr(t, { dir: e, size: i = 32 } = {}) {
  return typeof t == "string" ? V1(t, { dir: e, size: i }) : H1(t, { dir: e, size: i });
}
function V1(t, { dir: e, size: i = 32 } = {}) {
  if (i === null)
    return t;
  const r = t.replace("0x", "");
  if (r.length > i * 2)
    throw new nl({
      size: Math.ceil(r.length / 2),
      targetSize: i,
      type: "hex"
    });
  return `0x${r[e === "right" ? "padEnd" : "padStart"](i * 2, "0")}`;
}
function H1(t, { dir: e, size: i = 32 } = {}) {
  if (i === null)
    return t;
  if (t.length > i)
    throw new nl({
      size: t.length,
      targetSize: i,
      type: "bytes"
    });
  const r = new Uint8Array(i);
  for (let s = 0; s < i; s++) {
    const n = e === "right";
    r[n ? s : i - s - 1] = t[n ? s : t.length - s - 1];
  }
  return r;
}
class W1 extends Di {
  constructor({ max: e, min: i, signed: r, size: s, value: n }) {
    super(`Number "${n}" is not in safe ${s ? `${s * 8}-bit ${r ? "signed" : "unsigned"} ` : ""}integer range ${e ? `(${i} to ${e})` : `(above ${i})`}`, { name: "IntegerOutOfRangeError" });
  }
}
class G1 extends Di {
  constructor({ givenSize: e, maxSize: i }) {
    super(`Size cannot exceed ${i} bytes. Given size: ${e} bytes.`, { name: "SizeOverflowError" });
  }
}
function ir(t, { size: e }) {
  if (lo(t) > e)
    throw new G1({
      givenSize: lo(t),
      maxSize: e
    });
}
function fo(t, e = {}) {
  const { signed: i } = e;
  e.size && ir(t, { size: e.size });
  const r = BigInt(t);
  if (!i)
    return r;
  const s = (t.length - 2) / 2, n = (1n << BigInt(s) * 8n - 1n) - 1n;
  return r <= n ? r : r - BigInt(`0x${"f".padStart(s * 2, "f")}`) - 1n;
}
function Y1(t, e = {}) {
  return Number(fo(t, e));
}
const J1 = /* @__PURE__ */ Array.from({ length: 256 }, (t, e) => e.toString(16).padStart(2, "0"));
function po(t, e = {}) {
  return typeof t == "number" || typeof t == "bigint" ? al(t, e) : typeof t == "string" ? X1(t, e) : typeof t == "boolean" ? Z1(t, e) : ol(t, e);
}
function Z1(t, e = {}) {
  const i = `0x${Number(t)}`;
  return typeof e.size == "number" ? (ir(i, { size: e.size }), tr(i, { size: e.size })) : i;
}
function ol(t, e = {}) {
  let i = "";
  for (let s = 0; s < t.length; s++)
    i += J1[t[s]];
  const r = `0x${i}`;
  return typeof e.size == "number" ? (ir(r, { size: e.size }), tr(r, { dir: "right", size: e.size })) : r;
}
function al(t, e = {}) {
  const { signed: i, size: r } = e, s = BigInt(t);
  let n;
  r ? i ? n = (1n << BigInt(r) * 8n - 1n) - 1n : n = 2n ** (BigInt(r) * 8n) - 1n : typeof t == "number" && (n = BigInt(Number.MAX_SAFE_INTEGER));
  const o = typeof n == "bigint" && i ? -n - 1n : 0;
  if (n && s > n || s < o) {
    const c = typeof t == "bigint" ? "n" : "";
    throw new W1({
      max: n ? `${n}${c}` : void 0,
      min: `${o}${c}`,
      signed: i,
      size: r,
      value: `${t}${c}`
    });
  }
  const a = `0x${(i && s < 0 ? (1n << BigInt(r * 8)) + BigInt(s) : s).toString(16)}`;
  return r ? tr(a, { size: r }) : a;
}
const Q1 = /* @__PURE__ */ new TextEncoder();
function X1(t, e = {}) {
  const i = Q1.encode(t);
  return ol(i, e);
}
const ew = /* @__PURE__ */ new TextEncoder();
function tw(t, e = {}) {
  return typeof t == "number" || typeof t == "bigint" ? rw(t, e) : typeof t == "boolean" ? iw(t, e) : Lr(t) ? cl(t, e) : ul(t, e);
}
function iw(t, e = {}) {
  const i = new Uint8Array(1);
  return i[0] = Number(t), typeof e.size == "number" ? (ir(i, { size: e.size }), tr(i, { size: e.size })) : i;
}
const Pt = {
  zero: 48,
  nine: 57,
  A: 65,
  F: 70,
  a: 97,
  f: 102
};
function _c(t) {
  if (t >= Pt.zero && t <= Pt.nine)
    return t - Pt.zero;
  if (t >= Pt.A && t <= Pt.F)
    return t - (Pt.A - 10);
  if (t >= Pt.a && t <= Pt.f)
    return t - (Pt.a - 10);
}
function cl(t, e = {}) {
  let i = t;
  e.size && (ir(i, { size: e.size }), i = tr(i, { dir: "right", size: e.size }));
  let r = i.slice(2);
  r.length % 2 && (r = `0${r}`);
  const s = r.length / 2, n = new Uint8Array(s);
  for (let o = 0, a = 0; o < s; o++) {
    const c = _c(r.charCodeAt(a++)), u = _c(r.charCodeAt(a++));
    if (c === void 0 || u === void 0)
      throw new Di(`Invalid byte sequence ("${r[a - 2]}${r[a - 1]}" in "${r}").`);
    n[o] = c * 16 + u;
  }
  return n;
}
function rw(t, e) {
  const i = al(t, e);
  return cl(i);
}
function ul(t, e = {}) {
  const i = ew.encode(t);
  return typeof e.size == "number" ? (ir(i, { size: e.size }), tr(i, { dir: "right", size: e.size })) : i;
}
const ls = /* @__PURE__ */ BigInt(2 ** 32 - 1), xc = /* @__PURE__ */ BigInt(32);
function sw(t, e = !1) {
  return e ? { h: Number(t & ls), l: Number(t >> xc & ls) } : { h: Number(t >> xc & ls) | 0, l: Number(t & ls) | 0 };
}
function nw(t, e = !1) {
  const i = t.length;
  let r = new Uint32Array(i), s = new Uint32Array(i);
  for (let n = 0; n < i; n++) {
    const { h: o, l: a } = sw(t[n], e);
    [r[n], s[n]] = [o, a];
  }
  return [r, s];
}
const ow = (t, e, i) => t << i | e >>> 32 - i, aw = (t, e, i) => e << i | t >>> 32 - i, cw = (t, e, i) => e << i - 32 | t >>> 64 - i, uw = (t, e, i) => t << i - 32 | e >>> 64 - i, Mi = typeof globalThis == "object" && "crypto" in globalThis ? globalThis.crypto : void 0;
/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */
function hw(t) {
  return t instanceof Uint8Array || ArrayBuffer.isView(t) && t.constructor.name === "Uint8Array";
}
function Bs(t) {
  if (!Number.isSafeInteger(t) || t < 0)
    throw new Error("positive integer expected, got " + t);
}
function Mr(t, ...e) {
  if (!hw(t))
    throw new Error("Uint8Array expected");
  if (e.length > 0 && !e.includes(t.length))
    throw new Error("Uint8Array expected of length " + e + ", got length=" + t.length);
}
function TD(t) {
  if (typeof t != "function" || typeof t.create != "function")
    throw new Error("Hash should be wrapped by utils.createHasher");
  Bs(t.outputLen), Bs(t.blockLen);
}
function Ic(t, e = !0) {
  if (t.destroyed)
    throw new Error("Hash instance has been destroyed");
  if (e && t.finished)
    throw new Error("Hash#digest() has already been called");
}
function lw(t, e) {
  Mr(t);
  const i = e.outputLen;
  if (t.length < i)
    throw new Error("digestInto() expects output buffer of length at least " + i);
}
function fw(t) {
  return new Uint32Array(t.buffer, t.byteOffset, Math.floor(t.byteLength / 4));
}
function hl(...t) {
  for (let e = 0; e < t.length; e++)
    t[e].fill(0);
}
function CD(t) {
  return new DataView(t.buffer, t.byteOffset, t.byteLength);
}
function PD(t, e) {
  return t << 32 - e | t >>> e;
}
const dw = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([287454020]).buffer)[0] === 68)();
function pw(t) {
  return t << 24 & 4278190080 | t << 8 & 16711680 | t >>> 8 & 65280 | t >>> 24 & 255;
}
function gw(t) {
  for (let e = 0; e < t.length; e++)
    t[e] = pw(t[e]);
  return t;
}
const Sc = dw ? (t) => t : gw;
function yw(t) {
  if (typeof t != "string")
    throw new Error("string expected");
  return new Uint8Array(new TextEncoder().encode(t));
}
function ll(t) {
  return typeof t == "string" && (t = yw(t)), Mr(t), t;
}
function RD(...t) {
  let e = 0;
  for (let r = 0; r < t.length; r++) {
    const s = t[r];
    Mr(s), e += s.length;
  }
  const i = new Uint8Array(e);
  for (let r = 0, s = 0; r < t.length; r++) {
    const n = t[r];
    i.set(n, s), s += n.length;
  }
  return i;
}
class ww {
}
function mw(t) {
  const e = (r) => t().update(ll(r)).digest(), i = t();
  return e.outputLen = i.outputLen, e.blockLen = i.blockLen, e.create = () => t(), e;
}
function FD(t = 32) {
  if (Mi && typeof Mi.getRandomValues == "function")
    return Mi.getRandomValues(new Uint8Array(t));
  if (Mi && typeof Mi.randomBytes == "function")
    return Uint8Array.from(Mi.randomBytes(t));
  throw new Error("crypto.getRandomValues must be defined");
}
const bw = BigInt(0), hr = BigInt(1), vw = BigInt(2), Ew = BigInt(7), _w = BigInt(256), xw = BigInt(113), fl = [], dl = [], pl = [];
for (let t = 0, e = hr, i = 1, r = 0; t < 24; t++) {
  [i, r] = [r, (2 * i + 3 * r) % 5], fl.push(2 * (5 * r + i)), dl.push((t + 1) * (t + 2) / 2 % 64);
  let s = bw;
  for (let n = 0; n < 7; n++)
    e = (e << hr ^ (e >> Ew) * xw) % _w, e & vw && (s ^= hr << (hr << /* @__PURE__ */ BigInt(n)) - hr);
  pl.push(s);
}
const gl = nw(pl, !0), Iw = gl[0], Sw = gl[1], Dc = (t, e, i) => i > 32 ? cw(t, e, i) : ow(t, e, i), Ac = (t, e, i) => i > 32 ? uw(t, e, i) : aw(t, e, i);
function Dw(t, e = 24) {
  const i = new Uint32Array(10);
  for (let r = 24 - e; r < 24; r++) {
    for (let o = 0; o < 10; o++)
      i[o] = t[o] ^ t[o + 10] ^ t[o + 20] ^ t[o + 30] ^ t[o + 40];
    for (let o = 0; o < 10; o += 2) {
      const a = (o + 8) % 10, c = (o + 2) % 10, u = i[c], h = i[c + 1], l = Dc(u, h, 1) ^ i[a], f = Ac(u, h, 1) ^ i[a + 1];
      for (let p = 0; p < 50; p += 10)
        t[o + p] ^= l, t[o + p + 1] ^= f;
    }
    let s = t[2], n = t[3];
    for (let o = 0; o < 24; o++) {
      const a = dl[o], c = Dc(s, n, a), u = Ac(s, n, a), h = fl[o];
      s = t[h], n = t[h + 1], t[h] = c, t[h + 1] = u;
    }
    for (let o = 0; o < 50; o += 10) {
      for (let a = 0; a < 10; a++)
        i[a] = t[o + a];
      for (let a = 0; a < 10; a++)
        t[o + a] ^= ~i[(a + 2) % 10] & i[(a + 4) % 10];
    }
    t[0] ^= Iw[r], t[1] ^= Sw[r];
  }
  hl(i);
}
class ta extends ww {
  // NOTE: we accept arguments in bytes instead of bits here.
  constructor(e, i, r, s = !1, n = 24) {
    if (super(), this.pos = 0, this.posOut = 0, this.finished = !1, this.destroyed = !1, this.enableXOF = !1, this.blockLen = e, this.suffix = i, this.outputLen = r, this.enableXOF = s, this.rounds = n, Bs(r), !(0 < e && e < 200))
      throw new Error("only keccak-f1600 function is supported");
    this.state = new Uint8Array(200), this.state32 = fw(this.state);
  }
  clone() {
    return this._cloneInto();
  }
  keccak() {
    Sc(this.state32), Dw(this.state32, this.rounds), Sc(this.state32), this.posOut = 0, this.pos = 0;
  }
  update(e) {
    Ic(this), e = ll(e), Mr(e);
    const { blockLen: i, state: r } = this, s = e.length;
    for (let n = 0; n < s; ) {
      const o = Math.min(i - this.pos, s - n);
      for (let a = 0; a < o; a++)
        r[this.pos++] ^= e[n++];
      this.pos === i && this.keccak();
    }
    return this;
  }
  finish() {
    if (this.finished)
      return;
    this.finished = !0;
    const { state: e, suffix: i, pos: r, blockLen: s } = this;
    e[r] ^= i, i & 128 && r === s - 1 && this.keccak(), e[s - 1] ^= 128, this.keccak();
  }
  writeInto(e) {
    Ic(this, !1), Mr(e), this.finish();
    const i = this.state, { blockLen: r } = this;
    for (let s = 0, n = e.length; s < n; ) {
      this.posOut >= r && this.keccak();
      const o = Math.min(r - this.posOut, n - s);
      e.set(i.subarray(this.posOut, this.posOut + o), s), this.posOut += o, s += o;
    }
    return e;
  }
  xofInto(e) {
    if (!this.enableXOF)
      throw new Error("XOF is not possible for this instance");
    return this.writeInto(e);
  }
  xof(e) {
    return Bs(e), this.xofInto(new Uint8Array(e));
  }
  digestInto(e) {
    if (lw(e, this), this.finished)
      throw new Error("digest() was already called");
    return this.writeInto(e), this.destroy(), e;
  }
  digest() {
    return this.digestInto(new Uint8Array(this.outputLen));
  }
  destroy() {
    this.destroyed = !0, hl(this.state);
  }
  _cloneInto(e) {
    const { blockLen: i, suffix: r, outputLen: s, rounds: n, enableXOF: o } = this;
    return e || (e = new ta(i, r, s, o, n)), e.state32.set(this.state32), e.pos = this.pos, e.posOut = this.posOut, e.finished = this.finished, e.rounds = n, e.suffix = r, e.outputLen = s, e.enableXOF = o, e.destroyed = this.destroyed, e;
  }
}
const Aw = (t, e, i) => mw(() => new ta(e, t, i)), $w = /* @__PURE__ */ (() => Aw(1, 136, 256 / 8))();
function yl(t, e) {
  const i = e || "hex", r = $w(Lr(t, { strict: !1 }) ? tw(t) : t);
  return i === "bytes" ? r : po(r);
}
class Ow extends Map {
  constructor(e) {
    super(), Object.defineProperty(this, "maxSize", {
      enumerable: !0,
      configurable: !0,
      writable: !0,
      value: void 0
    }), this.maxSize = e;
  }
  get(e) {
    const i = super.get(e);
    return super.has(e) && i !== void 0 && (this.delete(e), super.set(e, i)), i;
  }
  set(e, i) {
    if (super.set(e, i), this.maxSize && this.size > this.maxSize) {
      const r = this.keys().next().value;
      r && this.delete(r);
    }
    return this;
  }
}
const Rn = /* @__PURE__ */ new Ow(8192);
function Tw(t, e) {
  if (Rn.has(`${t}.${e}`))
    return Rn.get(`${t}.${e}`);
  const i = e ? `${e}${t.toLowerCase()}` : t.substring(2).toLowerCase(), r = yl(ul(i), "bytes"), s = (e ? i.substring(`${e}0x`.length) : i).split("");
  for (let o = 0; o < 40; o += 2)
    r[o >> 1] >> 4 >= 8 && s[o] && (s[o] = s[o].toUpperCase()), (r[o >> 1] & 15) >= 8 && s[o + 1] && (s[o + 1] = s[o + 1].toUpperCase());
  const n = `0x${s.join("")}`;
  return Rn.set(`${t}.${e}`, n), n;
}
function Cw(t) {
  const e = yl(`0x${t.substring(4)}`).substring(26);
  return Tw(`0x${e}`);
}
async function Pw({ hash: t, signature: e }) {
  const i = Lr(t) ? t : po(t), { secp256k1: r } = await import("./secp256k1-19d3c11c.js");
  return `0x${(() => {
    if (typeof e == "object" && "r" in e && "s" in e) {
      const { r: u, s: h, v: l, yParity: f } = e, p = Number(f ?? l), d = $c(p);
      return new r.Signature(fo(u), fo(h)).addRecoveryBit(d);
    }
    const o = Lr(e) ? e : po(e);
    if (lo(o) !== 65)
      throw new Error("invalid signature length");
    const a = Y1(`0x${o.slice(130)}`), c = $c(a);
    return r.Signature.fromCompact(o.substring(2, 130)).addRecoveryBit(c);
  })().recoverPublicKey(i.substring(2)).toHex(!1)}`;
}
function $c(t) {
  if (t === 0 || t === 1)
    return t;
  if (t === 27)
    return 0;
  if (t === 28)
    return 1;
  throw new Error("Invalid yParityOrV value");
}
async function Rw({ hash: t, signature: e }) {
  return Cw(await Pw({ hash: t, signature: e }));
}
function Fw(t) {
  if (t.length >= 255)
    throw new TypeError("Alphabet too long");
  const e = new Uint8Array(256);
  for (let u = 0; u < e.length; u++)
    e[u] = 255;
  for (let u = 0; u < t.length; u++) {
    const h = t.charAt(u), l = h.charCodeAt(0);
    if (e[l] !== 255)
      throw new TypeError(h + " is ambiguous");
    e[l] = u;
  }
  const i = t.length, r = t.charAt(0), s = Math.log(i) / Math.log(256), n = Math.log(256) / Math.log(i);
  function o(u) {
    if (u instanceof Uint8Array || (ArrayBuffer.isView(u) ? u = new Uint8Array(u.buffer, u.byteOffset, u.byteLength) : Array.isArray(u) && (u = Uint8Array.from(u))), !(u instanceof Uint8Array))
      throw new TypeError("Expected Uint8Array");
    if (u.length === 0)
      return "";
    let h = 0, l = 0, f = 0;
    const p = u.length;
    for (; f !== p && u[f] === 0; )
      f++, h++;
    const d = (p - f) * n + 1 >>> 0, g = new Uint8Array(d);
    for (; f !== p; ) {
      let v = u[f], m = 0;
      for (let D = d - 1; (v !== 0 || m < l) && D !== -1; D--, m++)
        v += 256 * g[D] >>> 0, g[D] = v % i >>> 0, v = v / i >>> 0;
      if (v !== 0)
        throw new Error("Non-zero carry");
      l = m, f++;
    }
    let y = d - l;
    for (; y !== d && g[y] === 0; )
      y++;
    let E = r.repeat(h);
    for (; y < d; ++y)
      E += t.charAt(g[y]);
    return E;
  }
  function a(u) {
    if (typeof u != "string")
      throw new TypeError("Expected String");
    if (u.length === 0)
      return new Uint8Array();
    let h = 0, l = 0, f = 0;
    for (; u[h] === r; )
      l++, h++;
    const p = (u.length - h) * s + 1 >>> 0, d = new Uint8Array(p);
    for (; h < u.length; ) {
      const v = u.charCodeAt(h);
      if (v > 255)
        return;
      let m = e[v];
      if (m === 255)
        return;
      let D = 0;
      for (let I = p - 1; (m !== 0 || D < f) && I !== -1; I--, D++)
        m += i * d[I] >>> 0, d[I] = m % 256 >>> 0, m = m / 256 >>> 0;
      if (m !== 0)
        throw new Error("Non-zero carry");
      f = D, h++;
    }
    let g = p - f;
    for (; g !== p && d[g] === 0; )
      g++;
    const y = new Uint8Array(l + (p - g));
    let E = l;
    for (; g !== p; )
      y[E++] = d[g++];
    return y;
  }
  function c(u) {
    const h = a(u);
    if (h)
      return h;
    throw new Error("Non-base" + i + " character");
  }
  return {
    encode: o,
    decodeUnsafe: a,
    decode: c
  };
}
var Uw = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
const Zr = Fw(Uw);
function Bw(t) {
  const e = t.length;
  let i = 0, r = 0;
  for (; r < e; ) {
    let s = t.charCodeAt(r++);
    if (s & 4294967168)
      if (!(s & 4294965248))
        i += 2;
      else {
        if (s >= 55296 && s <= 56319 && r < e) {
          const n = t.charCodeAt(r);
          (n & 64512) === 56320 && (++r, s = ((s & 1023) << 10) + (n & 1023) + 65536);
        }
        s & 4294901760 ? i += 4 : i += 3;
      }
    else {
      i++;
      continue;
    }
  }
  return i;
}
function Nw(t, e, i) {
  const r = t.length;
  let s = i, n = 0;
  for (; n < r; ) {
    let o = t.charCodeAt(n++);
    if (o & 4294967168)
      if (!(o & 4294965248))
        e[s++] = o >> 6 & 31 | 192;
      else {
        if (o >= 55296 && o <= 56319 && n < r) {
          const a = t.charCodeAt(n);
          (a & 64512) === 56320 && (++n, o = ((o & 1023) << 10) + (a & 1023) + 65536);
        }
        o & 4294901760 ? (e[s++] = o >> 18 & 7 | 240, e[s++] = o >> 12 & 63 | 128, e[s++] = o >> 6 & 63 | 128) : (e[s++] = o >> 12 & 15 | 224, e[s++] = o >> 6 & 63 | 128);
      }
    else {
      e[s++] = o;
      continue;
    }
    e[s++] = o & 63 | 128;
  }
}
const kw = new TextEncoder(), Lw = 50;
function Mw(t, e, i) {
  kw.encodeInto(t, e.subarray(i));
}
function qw(t, e, i) {
  t.length > Lw ? Mw(t, e, i) : Nw(t, e, i);
}
const jw = 4096;
function wl(t, e, i) {
  let r = e;
  const s = r + i, n = [];
  let o = "";
  for (; r < s; ) {
    const a = t[r++];
    if (!(a & 128))
      n.push(a);
    else if ((a & 224) === 192) {
      const c = t[r++] & 63;
      n.push((a & 31) << 6 | c);
    } else if ((a & 240) === 224) {
      const c = t[r++] & 63, u = t[r++] & 63;
      n.push((a & 31) << 12 | c << 6 | u);
    } else if ((a & 248) === 240) {
      const c = t[r++] & 63, u = t[r++] & 63, h = t[r++] & 63;
      let l = (a & 7) << 18 | c << 12 | u << 6 | h;
      l > 65535 && (l -= 65536, n.push(l >>> 10 & 1023 | 55296), l = 56320 | l & 1023), n.push(l);
    } else
      n.push(a);
    n.length >= jw && (o += String.fromCharCode(...n), n.length = 0);
  }
  return n.length > 0 && (o += String.fromCharCode(...n)), o;
}
const zw = new TextDecoder(), Kw = 200;
function Vw(t, e, i) {
  const r = t.subarray(e, e + i);
  return zw.decode(r);
}
function Hw(t, e, i) {
  return i > Kw ? Vw(t, e, i) : wl(t, e, i);
}
class fs {
  constructor(e, i) {
    this.type = e, this.data = i;
  }
}
class tt extends Error {
  constructor(e) {
    super(e);
    const i = Object.create(tt.prototype);
    Object.setPrototypeOf(this, i), Object.defineProperty(this, "name", {
      configurable: !0,
      enumerable: !1,
      value: tt.name
    });
  }
}
const lr = 4294967295;
function Ww(t, e, i) {
  const r = i / 4294967296, s = i;
  t.setUint32(e, r), t.setUint32(e + 4, s);
}
function ml(t, e, i) {
  const r = Math.floor(i / 4294967296), s = i;
  t.setUint32(e, r), t.setUint32(e + 4, s);
}
function bl(t, e) {
  const i = t.getInt32(e), r = t.getUint32(e + 4);
  return i * 4294967296 + r;
}
function Gw(t, e) {
  const i = t.getUint32(e), r = t.getUint32(e + 4);
  return i * 4294967296 + r;
}
const Yw = -1, Jw = 4294967296 - 1, Zw = 17179869184 - 1;
function Qw({ sec: t, nsec: e }) {
  if (t >= 0 && e >= 0 && t <= Zw)
    if (e === 0 && t <= Jw) {
      const i = new Uint8Array(4);
      return new DataView(i.buffer).setUint32(0, t), i;
    } else {
      const i = t / 4294967296, r = t & 4294967295, s = new Uint8Array(8), n = new DataView(s.buffer);
      return n.setUint32(0, e << 2 | i & 3), n.setUint32(4, r), s;
    }
  else {
    const i = new Uint8Array(12), r = new DataView(i.buffer);
    return r.setUint32(0, e), ml(r, 4, t), i;
  }
}
function Xw(t) {
  const e = t.getTime(), i = Math.floor(e / 1e3), r = (e - i * 1e3) * 1e6, s = Math.floor(r / 1e9);
  return {
    sec: i + s,
    nsec: r - s * 1e9
  };
}
function em(t) {
  if (t instanceof Date) {
    const e = Xw(t);
    return Qw(e);
  } else
    return null;
}
function tm(t) {
  const e = new DataView(t.buffer, t.byteOffset, t.byteLength);
  switch (t.byteLength) {
    case 4:
      return { sec: e.getUint32(0), nsec: 0 };
    case 8: {
      const i = e.getUint32(0), r = e.getUint32(4), s = (i & 3) * 4294967296 + r, n = i >>> 2;
      return { sec: s, nsec: n };
    }
    case 12: {
      const i = bl(e, 4), r = e.getUint32(0);
      return { sec: i, nsec: r };
    }
    default:
      throw new tt(`Unrecognized data size for timestamp (expected 4, 8, or 12): ${t.length}`);
  }
}
function im(t) {
  const e = tm(t);
  return new Date(e.sec * 1e3 + e.nsec / 1e6);
}
const rm = {
  type: Yw,
  encode: em,
  decode: im
};
class Ns {
  constructor() {
    this.builtInEncoders = [], this.builtInDecoders = [], this.encoders = [], this.decoders = [], this.register(rm);
  }
  register({ type: e, encode: i, decode: r }) {
    if (e >= 0)
      this.encoders[e] = i, this.decoders[e] = r;
    else {
      const s = -1 - e;
      this.builtInEncoders[s] = i, this.builtInDecoders[s] = r;
    }
  }
  tryToEncode(e, i) {
    for (let r = 0; r < this.builtInEncoders.length; r++) {
      const s = this.builtInEncoders[r];
      if (s != null) {
        const n = s(e, i);
        if (n != null) {
          const o = -1 - r;
          return new fs(o, n);
        }
      }
    }
    for (let r = 0; r < this.encoders.length; r++) {
      const s = this.encoders[r];
      if (s != null) {
        const n = s(e, i);
        if (n != null) {
          const o = r;
          return new fs(o, n);
        }
      }
    }
    return e instanceof fs ? e : null;
  }
  decode(e, i, r) {
    const s = i < 0 ? this.builtInDecoders[-1 - i] : this.decoders[i];
    return s ? s(e, i, r) : new fs(i, e);
  }
}
Ns.defaultCodec = new Ns();
function sm(t) {
  return t instanceof ArrayBuffer || typeof SharedArrayBuffer < "u" && t instanceof SharedArrayBuffer;
}
function go(t) {
  return t instanceof Uint8Array ? t : ArrayBuffer.isView(t) ? new Uint8Array(t.buffer, t.byteOffset, t.byteLength) : sm(t) ? new Uint8Array(t) : Uint8Array.from(t);
}
const nm = 100, om = 2048;
let am = class vl {
  constructor(e) {
    this.entered = !1, this.extensionCodec = e?.extensionCodec ?? Ns.defaultCodec, this.context = e?.context, this.useBigInt64 = e?.useBigInt64 ?? !1, this.maxDepth = e?.maxDepth ?? nm, this.initialBufferSize = e?.initialBufferSize ?? om, this.sortKeys = e?.sortKeys ?? !1, this.forceFloat32 = e?.forceFloat32 ?? !1, this.ignoreUndefined = e?.ignoreUndefined ?? !1, this.forceIntegerToFloat = e?.forceIntegerToFloat ?? !1, this.pos = 0, this.view = new DataView(new ArrayBuffer(this.initialBufferSize)), this.bytes = new Uint8Array(this.view.buffer);
  }
  clone() {
    return new vl({
      extensionCodec: this.extensionCodec,
      context: this.context,
      useBigInt64: this.useBigInt64,
      maxDepth: this.maxDepth,
      initialBufferSize: this.initialBufferSize,
      sortKeys: this.sortKeys,
      forceFloat32: this.forceFloat32,
      ignoreUndefined: this.ignoreUndefined,
      forceIntegerToFloat: this.forceIntegerToFloat
    });
  }
  reinitializeState() {
    this.pos = 0;
  }
  /**
   * This is almost equivalent to {@link Encoder#encode}, but it returns an reference of the encoder's internal buffer and thus much faster than {@link Encoder#encode}.
   *
   * @returns Encodes the object and returns a shared reference the encoder's internal buffer.
   */
  encodeSharedRef(e) {
    if (this.entered)
      return this.clone().encodeSharedRef(e);
    try {
      return this.entered = !0, this.reinitializeState(), this.doEncode(e, 1), this.bytes.subarray(0, this.pos);
    } finally {
      this.entered = !1;
    }
  }
  /**
   * @returns Encodes the object and returns a copy of the encoder's internal buffer.
   */
  encode(e) {
    if (this.entered)
      return this.clone().encode(e);
    try {
      return this.entered = !0, this.reinitializeState(), this.doEncode(e, 1), this.bytes.slice(0, this.pos);
    } finally {
      this.entered = !1;
    }
  }
  doEncode(e, i) {
    if (i > this.maxDepth)
      throw new Error(`Too deep objects in depth ${i}`);
    e == null ? this.encodeNil() : typeof e == "boolean" ? this.encodeBoolean(e) : typeof e == "number" ? this.forceIntegerToFloat ? this.encodeNumberAsFloat(e) : this.encodeNumber(e) : typeof e == "string" ? this.encodeString(e) : this.useBigInt64 && typeof e == "bigint" ? this.encodeBigInt64(e) : this.encodeObject(e, i);
  }
  ensureBufferSizeToWrite(e) {
    const i = this.pos + e;
    this.view.byteLength < i && this.resizeBuffer(i * 2);
  }
  resizeBuffer(e) {
    const i = new ArrayBuffer(e), r = new Uint8Array(i), s = new DataView(i);
    r.set(this.bytes), this.view = s, this.bytes = r;
  }
  encodeNil() {
    this.writeU8(192);
  }
  encodeBoolean(e) {
    e === !1 ? this.writeU8(194) : this.writeU8(195);
  }
  encodeNumber(e) {
    !this.forceIntegerToFloat && Number.isSafeInteger(e) ? e >= 0 ? e < 128 ? this.writeU8(e) : e < 256 ? (this.writeU8(204), this.writeU8(e)) : e < 65536 ? (this.writeU8(205), this.writeU16(e)) : e < 4294967296 ? (this.writeU8(206), this.writeU32(e)) : this.useBigInt64 ? this.encodeNumberAsFloat(e) : (this.writeU8(207), this.writeU64(e)) : e >= -32 ? this.writeU8(224 | e + 32) : e >= -128 ? (this.writeU8(208), this.writeI8(e)) : e >= -32768 ? (this.writeU8(209), this.writeI16(e)) : e >= -2147483648 ? (this.writeU8(210), this.writeI32(e)) : this.useBigInt64 ? this.encodeNumberAsFloat(e) : (this.writeU8(211), this.writeI64(e)) : this.encodeNumberAsFloat(e);
  }
  encodeNumberAsFloat(e) {
    this.forceFloat32 ? (this.writeU8(202), this.writeF32(e)) : (this.writeU8(203), this.writeF64(e));
  }
  encodeBigInt64(e) {
    e >= BigInt(0) ? (this.writeU8(207), this.writeBigUint64(e)) : (this.writeU8(211), this.writeBigInt64(e));
  }
  writeStringHeader(e) {
    if (e < 32)
      this.writeU8(160 + e);
    else if (e < 256)
      this.writeU8(217), this.writeU8(e);
    else if (e < 65536)
      this.writeU8(218), this.writeU16(e);
    else if (e < 4294967296)
      this.writeU8(219), this.writeU32(e);
    else
      throw new Error(`Too long string: ${e} bytes in UTF-8`);
  }
  encodeString(e) {
    const r = Bw(e);
    this.ensureBufferSizeToWrite(5 + r), this.writeStringHeader(r), qw(e, this.bytes, this.pos), this.pos += r;
  }
  encodeObject(e, i) {
    const r = this.extensionCodec.tryToEncode(e, this.context);
    if (r != null)
      this.encodeExtension(r);
    else if (Array.isArray(e))
      this.encodeArray(e, i);
    else if (ArrayBuffer.isView(e))
      this.encodeBinary(e);
    else if (typeof e == "object")
      this.encodeMap(e, i);
    else
      throw new Error(`Unrecognized object: ${Object.prototype.toString.apply(e)}`);
  }
  encodeBinary(e) {
    const i = e.byteLength;
    if (i < 256)
      this.writeU8(196), this.writeU8(i);
    else if (i < 65536)
      this.writeU8(197), this.writeU16(i);
    else if (i < 4294967296)
      this.writeU8(198), this.writeU32(i);
    else
      throw new Error(`Too large binary: ${i}`);
    const r = go(e);
    this.writeU8a(r);
  }
  encodeArray(e, i) {
    const r = e.length;
    if (r < 16)
      this.writeU8(144 + r);
    else if (r < 65536)
      this.writeU8(220), this.writeU16(r);
    else if (r < 4294967296)
      this.writeU8(221), this.writeU32(r);
    else
      throw new Error(`Too large array: ${r}`);
    for (const s of e)
      this.doEncode(s, i + 1);
  }
  countWithoutUndefined(e, i) {
    let r = 0;
    for (const s of i)
      e[s] !== void 0 && r++;
    return r;
  }
  encodeMap(e, i) {
    const r = Object.keys(e);
    this.sortKeys && r.sort();
    const s = this.ignoreUndefined ? this.countWithoutUndefined(e, r) : r.length;
    if (s < 16)
      this.writeU8(128 + s);
    else if (s < 65536)
      this.writeU8(222), this.writeU16(s);
    else if (s < 4294967296)
      this.writeU8(223), this.writeU32(s);
    else
      throw new Error(`Too large map object: ${s}`);
    for (const n of r) {
      const o = e[n];
      this.ignoreUndefined && o === void 0 || (this.encodeString(n), this.doEncode(o, i + 1));
    }
  }
  encodeExtension(e) {
    if (typeof e.data == "function") {
      const r = e.data(this.pos + 6), s = r.length;
      if (s >= 4294967296)
        throw new Error(`Too large extension object: ${s}`);
      this.writeU8(201), this.writeU32(s), this.writeI8(e.type), this.writeU8a(r);
      return;
    }
    const i = e.data.length;
    if (i === 1)
      this.writeU8(212);
    else if (i === 2)
      this.writeU8(213);
    else if (i === 4)
      this.writeU8(214);
    else if (i === 8)
      this.writeU8(215);
    else if (i === 16)
      this.writeU8(216);
    else if (i < 256)
      this.writeU8(199), this.writeU8(i);
    else if (i < 65536)
      this.writeU8(200), this.writeU16(i);
    else if (i < 4294967296)
      this.writeU8(201), this.writeU32(i);
    else
      throw new Error(`Too large extension object: ${i}`);
    this.writeI8(e.type), this.writeU8a(e.data);
  }
  writeU8(e) {
    this.ensureBufferSizeToWrite(1), this.view.setUint8(this.pos, e), this.pos++;
  }
  writeU8a(e) {
    const i = e.length;
    this.ensureBufferSizeToWrite(i), this.bytes.set(e, this.pos), this.pos += i;
  }
  writeI8(e) {
    this.ensureBufferSizeToWrite(1), this.view.setInt8(this.pos, e), this.pos++;
  }
  writeU16(e) {
    this.ensureBufferSizeToWrite(2), this.view.setUint16(this.pos, e), this.pos += 2;
  }
  writeI16(e) {
    this.ensureBufferSizeToWrite(2), this.view.setInt16(this.pos, e), this.pos += 2;
  }
  writeU32(e) {
    this.ensureBufferSizeToWrite(4), this.view.setUint32(this.pos, e), this.pos += 4;
  }
  writeI32(e) {
    this.ensureBufferSizeToWrite(4), this.view.setInt32(this.pos, e), this.pos += 4;
  }
  writeF32(e) {
    this.ensureBufferSizeToWrite(4), this.view.setFloat32(this.pos, e), this.pos += 4;
  }
  writeF64(e) {
    this.ensureBufferSizeToWrite(8), this.view.setFloat64(this.pos, e), this.pos += 8;
  }
  writeU64(e) {
    this.ensureBufferSizeToWrite(8), Ww(this.view, this.pos, e), this.pos += 8;
  }
  writeI64(e) {
    this.ensureBufferSizeToWrite(8), ml(this.view, this.pos, e), this.pos += 8;
  }
  writeBigUint64(e) {
    this.ensureBufferSizeToWrite(8), this.view.setBigUint64(this.pos, e), this.pos += 8;
  }
  writeBigInt64(e) {
    this.ensureBufferSizeToWrite(8), this.view.setBigInt64(this.pos, e), this.pos += 8;
  }
};
function cm(t, e) {
  return new am(e).encodeSharedRef(t);
}
function Fn(t) {
  return `${t < 0 ? "-" : ""}0x${Math.abs(t).toString(16).padStart(2, "0")}`;
}
const um = 16, hm = 16;
class lm {
  constructor(e = um, i = hm) {
    this.hit = 0, this.miss = 0, this.maxKeyLength = e, this.maxLengthPerKey = i, this.caches = [];
    for (let r = 0; r < this.maxKeyLength; r++)
      this.caches.push([]);
  }
  canBeCached(e) {
    return e > 0 && e <= this.maxKeyLength;
  }
  find(e, i, r) {
    const s = this.caches[r - 1];
    e:
      for (const n of s) {
        const o = n.bytes;
        for (let a = 0; a < r; a++)
          if (o[a] !== e[i + a])
            continue e;
        return n.str;
      }
    return null;
  }
  store(e, i) {
    const r = this.caches[e.length - 1], s = { bytes: e, str: i };
    r.length >= this.maxLengthPerKey ? r[Math.random() * r.length | 0] = s : r.push(s);
  }
  decode(e, i, r) {
    const s = this.find(e, i, r);
    if (s != null)
      return this.hit++, s;
    this.miss++;
    const n = wl(e, i, r), o = Uint8Array.prototype.slice.call(e, i, i + r);
    return this.store(o, n), n;
  }
}
const yo = "array", Ar = "map_key", El = "map_value", fm = (t) => {
  if (typeof t == "string" || typeof t == "number")
    return t;
  throw new tt("The type of key must be string or number but " + typeof t);
};
class dm {
  constructor() {
    this.stack = [], this.stackHeadPosition = -1;
  }
  get length() {
    return this.stackHeadPosition + 1;
  }
  top() {
    return this.stack[this.stackHeadPosition];
  }
  pushArrayState(e) {
    const i = this.getUninitializedStateFromPool();
    i.type = yo, i.position = 0, i.size = e, i.array = new Array(e);
  }
  pushMapState(e) {
    const i = this.getUninitializedStateFromPool();
    i.type = Ar, i.readCount = 0, i.size = e, i.map = {};
  }
  getUninitializedStateFromPool() {
    if (this.stackHeadPosition++, this.stackHeadPosition === this.stack.length) {
      const e = {
        type: void 0,
        size: 0,
        array: void 0,
        position: 0,
        readCount: 0,
        map: void 0,
        key: null
      };
      this.stack.push(e);
    }
    return this.stack[this.stackHeadPosition];
  }
  release(e) {
    if (this.stack[this.stackHeadPosition] !== e)
      throw new Error("Invalid stack state. Released state is not on top of the stack.");
    if (e.type === yo) {
      const r = e;
      r.size = 0, r.array = void 0, r.position = 0, r.type = void 0;
    }
    if (e.type === Ar || e.type === El) {
      const r = e;
      r.size = 0, r.map = void 0, r.readCount = 0, r.type = void 0;
    }
    this.stackHeadPosition--;
  }
  reset() {
    this.stack.length = 0, this.stackHeadPosition = -1;
  }
}
const fr = -1, ia = new DataView(new ArrayBuffer(0)), pm = new Uint8Array(ia.buffer);
try {
  ia.getInt8(0);
} catch (t) {
  if (!(t instanceof RangeError))
    throw new Error("This module is not supported in the current JavaScript engine because DataView does not throw RangeError on out-of-bounds access");
}
const Oc = new RangeError("Insufficient data"), gm = new lm();
let ym = class _l {
  constructor(e) {
    this.totalPos = 0, this.pos = 0, this.view = ia, this.bytes = pm, this.headByte = fr, this.stack = new dm(), this.entered = !1, this.extensionCodec = e?.extensionCodec ?? Ns.defaultCodec, this.context = e?.context, this.useBigInt64 = e?.useBigInt64 ?? !1, this.rawStrings = e?.rawStrings ?? !1, this.maxStrLength = e?.maxStrLength ?? lr, this.maxBinLength = e?.maxBinLength ?? lr, this.maxArrayLength = e?.maxArrayLength ?? lr, this.maxMapLength = e?.maxMapLength ?? lr, this.maxExtLength = e?.maxExtLength ?? lr, this.keyDecoder = e?.keyDecoder !== void 0 ? e.keyDecoder : gm, this.mapKeyConverter = e?.mapKeyConverter ?? fm;
  }
  clone() {
    return new _l({
      extensionCodec: this.extensionCodec,
      context: this.context,
      useBigInt64: this.useBigInt64,
      rawStrings: this.rawStrings,
      maxStrLength: this.maxStrLength,
      maxBinLength: this.maxBinLength,
      maxArrayLength: this.maxArrayLength,
      maxMapLength: this.maxMapLength,
      maxExtLength: this.maxExtLength,
      keyDecoder: this.keyDecoder
    });
  }
  reinitializeState() {
    this.totalPos = 0, this.headByte = fr, this.stack.reset();
  }
  setBuffer(e) {
    const i = go(e);
    this.bytes = i, this.view = new DataView(i.buffer, i.byteOffset, i.byteLength), this.pos = 0;
  }
  appendBuffer(e) {
    if (this.headByte === fr && !this.hasRemaining(1))
      this.setBuffer(e);
    else {
      const i = this.bytes.subarray(this.pos), r = go(e), s = new Uint8Array(i.length + r.length);
      s.set(i), s.set(r, i.length), this.setBuffer(s);
    }
  }
  hasRemaining(e) {
    return this.view.byteLength - this.pos >= e;
  }
  createExtraByteError(e) {
    const { view: i, pos: r } = this;
    return new RangeError(`Extra ${i.byteLength - r} of ${i.byteLength} byte(s) found at buffer[${e}]`);
  }
  /**
   * @throws {@link DecodeError}
   * @throws {@link RangeError}
   */
  decode(e) {
    if (this.entered)
      return this.clone().decode(e);
    try {
      this.entered = !0, this.reinitializeState(), this.setBuffer(e);
      const i = this.doDecodeSync();
      if (this.hasRemaining(1))
        throw this.createExtraByteError(this.pos);
      return i;
    } finally {
      this.entered = !1;
    }
  }
  *decodeMulti(e) {
    if (this.entered) {
      yield* this.clone().decodeMulti(e);
      return;
    }
    try {
      for (this.entered = !0, this.reinitializeState(), this.setBuffer(e); this.hasRemaining(1); )
        yield this.doDecodeSync();
    } finally {
      this.entered = !1;
    }
  }
  async decodeAsync(e) {
    if (this.entered)
      return this.clone().decodeAsync(e);
    try {
      this.entered = !0;
      let i = !1, r;
      for await (const a of e) {
        if (i)
          throw this.entered = !1, this.createExtraByteError(this.totalPos);
        this.appendBuffer(a);
        try {
          r = this.doDecodeSync(), i = !0;
        } catch (c) {
          if (!(c instanceof RangeError))
            throw c;
        }
        this.totalPos += this.pos;
      }
      if (i) {
        if (this.hasRemaining(1))
          throw this.createExtraByteError(this.totalPos);
        return r;
      }
      const { headByte: s, pos: n, totalPos: o } = this;
      throw new RangeError(`Insufficient data in parsing ${Fn(s)} at ${o} (${n} in the current buffer)`);
    } finally {
      this.entered = !1;
    }
  }
  decodeArrayStream(e) {
    return this.decodeMultiAsync(e, !0);
  }
  decodeStream(e) {
    return this.decodeMultiAsync(e, !1);
  }
  async *decodeMultiAsync(e, i) {
    if (this.entered) {
      yield* this.clone().decodeMultiAsync(e, i);
      return;
    }
    try {
      this.entered = !0;
      let r = i, s = -1;
      for await (const n of e) {
        if (i && s === 0)
          throw this.createExtraByteError(this.totalPos);
        this.appendBuffer(n), r && (s = this.readArraySize(), r = !1, this.complete());
        try {
          for (; yield this.doDecodeSync(), --s !== 0; )
            ;
        } catch (o) {
          if (!(o instanceof RangeError))
            throw o;
        }
        this.totalPos += this.pos;
      }
    } finally {
      this.entered = !1;
    }
  }
  doDecodeSync() {
    e:
      for (; ; ) {
        const e = this.readHeadByte();
        let i;
        if (e >= 224)
          i = e - 256;
        else if (e < 192)
          if (e < 128)
            i = e;
          else if (e < 144) {
            const s = e - 128;
            if (s !== 0) {
              this.pushMapState(s), this.complete();
              continue e;
            } else
              i = {};
          } else if (e < 160) {
            const s = e - 144;
            if (s !== 0) {
              this.pushArrayState(s), this.complete();
              continue e;
            } else
              i = [];
          } else {
            const s = e - 160;
            i = this.decodeString(s, 0);
          }
        else if (e === 192)
          i = null;
        else if (e === 194)
          i = !1;
        else if (e === 195)
          i = !0;
        else if (e === 202)
          i = this.readF32();
        else if (e === 203)
          i = this.readF64();
        else if (e === 204)
          i = this.readU8();
        else if (e === 205)
          i = this.readU16();
        else if (e === 206)
          i = this.readU32();
        else if (e === 207)
          this.useBigInt64 ? i = this.readU64AsBigInt() : i = this.readU64();
        else if (e === 208)
          i = this.readI8();
        else if (e === 209)
          i = this.readI16();
        else if (e === 210)
          i = this.readI32();
        else if (e === 211)
          this.useBigInt64 ? i = this.readI64AsBigInt() : i = this.readI64();
        else if (e === 217) {
          const s = this.lookU8();
          i = this.decodeString(s, 1);
        } else if (e === 218) {
          const s = this.lookU16();
          i = this.decodeString(s, 2);
        } else if (e === 219) {
          const s = this.lookU32();
          i = this.decodeString(s, 4);
        } else if (e === 220) {
          const s = this.readU16();
          if (s !== 0) {
            this.pushArrayState(s), this.complete();
            continue e;
          } else
            i = [];
        } else if (e === 221) {
          const s = this.readU32();
          if (s !== 0) {
            this.pushArrayState(s), this.complete();
            continue e;
          } else
            i = [];
        } else if (e === 222) {
          const s = this.readU16();
          if (s !== 0) {
            this.pushMapState(s), this.complete();
            continue e;
          } else
            i = {};
        } else if (e === 223) {
          const s = this.readU32();
          if (s !== 0) {
            this.pushMapState(s), this.complete();
            continue e;
          } else
            i = {};
        } else if (e === 196) {
          const s = this.lookU8();
          i = this.decodeBinary(s, 1);
        } else if (e === 197) {
          const s = this.lookU16();
          i = this.decodeBinary(s, 2);
        } else if (e === 198) {
          const s = this.lookU32();
          i = this.decodeBinary(s, 4);
        } else if (e === 212)
          i = this.decodeExtension(1, 0);
        else if (e === 213)
          i = this.decodeExtension(2, 0);
        else if (e === 214)
          i = this.decodeExtension(4, 0);
        else if (e === 215)
          i = this.decodeExtension(8, 0);
        else if (e === 216)
          i = this.decodeExtension(16, 0);
        else if (e === 199) {
          const s = this.lookU8();
          i = this.decodeExtension(s, 1);
        } else if (e === 200) {
          const s = this.lookU16();
          i = this.decodeExtension(s, 2);
        } else if (e === 201) {
          const s = this.lookU32();
          i = this.decodeExtension(s, 4);
        } else
          throw new tt(`Unrecognized type byte: ${Fn(e)}`);
        this.complete();
        const r = this.stack;
        for (; r.length > 0; ) {
          const s = r.top();
          if (s.type === yo)
            if (s.array[s.position] = i, s.position++, s.position === s.size)
              i = s.array, r.release(s);
            else
              continue e;
          else if (s.type === Ar) {
            if (i === "__proto__")
              throw new tt("The key __proto__ is not allowed");
            s.key = this.mapKeyConverter(i), s.type = El;
            continue e;
          } else if (s.map[s.key] = i, s.readCount++, s.readCount === s.size)
            i = s.map, r.release(s);
          else {
            s.key = null, s.type = Ar;
            continue e;
          }
        }
        return i;
      }
  }
  readHeadByte() {
    return this.headByte === fr && (this.headByte = this.readU8()), this.headByte;
  }
  complete() {
    this.headByte = fr;
  }
  readArraySize() {
    const e = this.readHeadByte();
    switch (e) {
      case 220:
        return this.readU16();
      case 221:
        return this.readU32();
      default: {
        if (e < 160)
          return e - 144;
        throw new tt(`Unrecognized array type byte: ${Fn(e)}`);
      }
    }
  }
  pushMapState(e) {
    if (e > this.maxMapLength)
      throw new tt(`Max length exceeded: map length (${e}) > maxMapLengthLength (${this.maxMapLength})`);
    this.stack.pushMapState(e);
  }
  pushArrayState(e) {
    if (e > this.maxArrayLength)
      throw new tt(`Max length exceeded: array length (${e}) > maxArrayLength (${this.maxArrayLength})`);
    this.stack.pushArrayState(e);
  }
  decodeString(e, i) {
    return !this.rawStrings || this.stateIsMapKey() ? this.decodeUtf8String(e, i) : this.decodeBinary(e, i);
  }
  /**
   * @throws {@link RangeError}
   */
  decodeUtf8String(e, i) {
    if (e > this.maxStrLength)
      throw new tt(`Max length exceeded: UTF-8 byte length (${e}) > maxStrLength (${this.maxStrLength})`);
    if (this.bytes.byteLength < this.pos + i + e)
      throw Oc;
    const r = this.pos + i;
    let s;
    return this.stateIsMapKey() && this.keyDecoder?.canBeCached(e) ? s = this.keyDecoder.decode(this.bytes, r, e) : s = Hw(this.bytes, r, e), this.pos += i + e, s;
  }
  stateIsMapKey() {
    return this.stack.length > 0 ? this.stack.top().type === Ar : !1;
  }
  /**
   * @throws {@link RangeError}
   */
  decodeBinary(e, i) {
    if (e > this.maxBinLength)
      throw new tt(`Max length exceeded: bin length (${e}) > maxBinLength (${this.maxBinLength})`);
    if (!this.hasRemaining(e + i))
      throw Oc;
    const r = this.pos + i, s = this.bytes.subarray(r, r + e);
    return this.pos += i + e, s;
  }
  decodeExtension(e, i) {
    if (e > this.maxExtLength)
      throw new tt(`Max length exceeded: ext length (${e}) > maxExtLength (${this.maxExtLength})`);
    const r = this.view.getInt8(this.pos + i), s = this.decodeBinary(
      e,
      i + 1
      /* extType */
    );
    return this.extensionCodec.decode(s, r, this.context);
  }
  lookU8() {
    return this.view.getUint8(this.pos);
  }
  lookU16() {
    return this.view.getUint16(this.pos);
  }
  lookU32() {
    return this.view.getUint32(this.pos);
  }
  readU8() {
    const e = this.view.getUint8(this.pos);
    return this.pos++, e;
  }
  readI8() {
    const e = this.view.getInt8(this.pos);
    return this.pos++, e;
  }
  readU16() {
    const e = this.view.getUint16(this.pos);
    return this.pos += 2, e;
  }
  readI16() {
    const e = this.view.getInt16(this.pos);
    return this.pos += 2, e;
  }
  readU32() {
    const e = this.view.getUint32(this.pos);
    return this.pos += 4, e;
  }
  readI32() {
    const e = this.view.getInt32(this.pos);
    return this.pos += 4, e;
  }
  readU64() {
    const e = Gw(this.view, this.pos);
    return this.pos += 8, e;
  }
  readI64() {
    const e = bl(this.view, this.pos);
    return this.pos += 8, e;
  }
  readU64AsBigInt() {
    const e = this.view.getBigUint64(this.pos);
    return this.pos += 8, e;
  }
  readI64AsBigInt() {
    const e = this.view.getBigInt64(this.pos);
    return this.pos += 8, e;
  }
  readF32() {
    const e = this.view.getFloat32(this.pos);
    return this.pos += 4, e;
  }
  readF64() {
    const e = this.view.getFloat64(this.pos);
    return this.pos += 8, e;
  }
};
function wm(t, e) {
  return new ym(e).decode(t);
}
/*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) */
function mm(t) {
  return t instanceof Uint8Array || ArrayBuffer.isView(t) && t.constructor.name === "Uint8Array";
}
function xl(t, e) {
  return Array.isArray(e) ? e.length === 0 ? !0 : t ? e.every((i) => typeof i == "string") : e.every((i) => Number.isSafeInteger(i)) : !1;
}
function ks(t, e) {
  if (typeof e != "string")
    throw new Error(`${t}: string expected`);
  return !0;
}
function ra(t) {
  if (!Number.isSafeInteger(t))
    throw new Error(`invalid integer: ${t}`);
}
function wo(t) {
  if (!Array.isArray(t))
    throw new Error("array expected");
}
function Ls(t, e) {
  if (!xl(!0, e))
    throw new Error(`${t}: array of strings expected`);
}
function bm(t, e) {
  if (!xl(!1, e))
    throw new Error(`${t}: array of numbers expected`);
}
// @__NO_SIDE_EFFECTS__
function vm(...t) {
  const e = (n) => n, i = (n, o) => (a) => n(o(a)), r = t.map((n) => n.encode).reduceRight(i, e), s = t.map((n) => n.decode).reduce(i, e);
  return { encode: r, decode: s };
}
// @__NO_SIDE_EFFECTS__
function Em(t) {
  const e = typeof t == "string" ? t.split("") : t, i = e.length;
  Ls("alphabet", e);
  const r = new Map(e.map((s, n) => [s, n]));
  return {
    encode: (s) => (wo(s), s.map((n) => {
      if (!Number.isSafeInteger(n) || n < 0 || n >= i)
        throw new Error(`alphabet.encode: digit index outside alphabet "${n}". Allowed: ${t}`);
      return e[n];
    })),
    decode: (s) => (wo(s), s.map((n) => {
      ks("alphabet.decode", n);
      const o = r.get(n);
      if (o === void 0)
        throw new Error(`Unknown letter: "${n}". Allowed: ${t}`);
      return o;
    }))
  };
}
// @__NO_SIDE_EFFECTS__
function _m(t = "") {
  return ks("join", t), {
    encode: (e) => (Ls("join.decode", e), e.join(t)),
    decode: (e) => (ks("join.decode", e), e.split(t))
  };
}
// @__NO_SIDE_EFFECTS__
function xm(t, e = "=") {
  return ra(t), ks("padding", e), {
    encode(i) {
      for (Ls("padding.encode", i); i.length * t % 8; )
        i.push(e);
      return i;
    },
    decode(i) {
      Ls("padding.decode", i);
      let r = i.length;
      if (r * t % 8)
        throw new Error("padding: invalid, string should have whole number of bytes");
      for (; r > 0 && i[r - 1] === e; r--)
        if ((r - 1) * t % 8 === 0)
          throw new Error("padding: invalid, string has too much padding");
      return i.slice(0, r);
    }
  };
}
const Il = (t, e) => e === 0 ? t : Il(e, t % e), Ms = /* @__NO_SIDE_EFFECTS__ */ (t, e) => t + (e - Il(t, e)), Un = /* @__PURE__ */ (() => {
  let t = [];
  for (let e = 0; e < 40; e++)
    t.push(2 ** e);
  return t;
})();
function Tc(t, e, i, r) {
  if (wo(t), e <= 0 || e > 32)
    throw new Error(`convertRadix2: wrong from=${e}`);
  if (i <= 0 || i > 32)
    throw new Error(`convertRadix2: wrong to=${i}`);
  if (/* @__PURE__ */ Ms(e, i) > 32)
    throw new Error(`convertRadix2: carry overflow from=${e} to=${i} carryBits=${/* @__PURE__ */ Ms(e, i)}`);
  let s = 0, n = 0;
  const o = Un[e], a = Un[i] - 1, c = [];
  for (const u of t) {
    if (ra(u), u >= o)
      throw new Error(`convertRadix2: invalid data word=${u} from=${e}`);
    if (s = s << e | u, n + e > 32)
      throw new Error(`convertRadix2: carry overflow pos=${n} from=${e}`);
    for (n += e; n >= i; n -= i)
      c.push((s >> n - i & a) >>> 0);
    const h = Un[n];
    if (h === void 0)
      throw new Error("invalid carry");
    s &= h - 1;
  }
  if (s = s << i - n & a, !r && n >= e)
    throw new Error("Excess padding");
  if (!r && s > 0)
    throw new Error(`Non-zero padding: ${s}`);
  return r && n > 0 && c.push(s >>> 0), c;
}
// @__NO_SIDE_EFFECTS__
function Im(t, e = !1) {
  if (ra(t), t <= 0 || t > 32)
    throw new Error("radix2: bits should be in (0..32]");
  if (/* @__PURE__ */ Ms(8, t) > 32 || /* @__PURE__ */ Ms(t, 8) > 32)
    throw new Error("radix2: carry overflow");
  return {
    encode: (i) => {
      if (!mm(i))
        throw new Error("radix2.encode input should be Uint8Array");
      return Tc(Array.from(i), 8, t, !e);
    },
    decode: (i) => (bm("radix2.decode", i), Uint8Array.from(Tc(i, t, 8, e)))
  };
}
const Sm = /* @__PURE__ */ vm(/* @__PURE__ */ Im(5), /* @__PURE__ */ Em("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"), /* @__PURE__ */ xm(5), /* @__PURE__ */ _m(""));
function sa(t) {
  return globalThis.Buffer != null ? new Uint8Array(t.buffer, t.byteOffset, t.byteLength) : t;
}
function Sl(t = 0) {
  return globalThis.Buffer != null && globalThis.Buffer.allocUnsafe != null ? sa(globalThis.Buffer.allocUnsafe(t)) : new Uint8Array(t);
}
function $r(t, e) {
  e || (e = t.reduce((s, n) => s + n.length, 0));
  const i = Sl(e);
  let r = 0;
  for (const s of t)
    i.set(s, r), r += s.length;
  return sa(i);
}
function Dm(t, e) {
  if (t.length >= 255)
    throw new TypeError("Alphabet too long");
  for (var i = new Uint8Array(256), r = 0; r < i.length; r++)
    i[r] = 255;
  for (var s = 0; s < t.length; s++) {
    var n = t.charAt(s), o = n.charCodeAt(0);
    if (i[o] !== 255)
      throw new TypeError(n + " is ambiguous");
    i[o] = s;
  }
  var a = t.length, c = t.charAt(0), u = Math.log(a) / Math.log(256), h = Math.log(256) / Math.log(a);
  function l(d) {
    if (d instanceof Uint8Array || (ArrayBuffer.isView(d) ? d = new Uint8Array(d.buffer, d.byteOffset, d.byteLength) : Array.isArray(d) && (d = Uint8Array.from(d))), !(d instanceof Uint8Array))
      throw new TypeError("Expected Uint8Array");
    if (d.length === 0)
      return "";
    for (var g = 0, y = 0, E = 0, v = d.length; E !== v && d[E] === 0; )
      E++, g++;
    for (var m = (v - E) * h + 1 >>> 0, D = new Uint8Array(m); E !== v; ) {
      for (var I = d[E], R = 0, B = m - 1; (I !== 0 || R < y) && B !== -1; B--, R++)
        I += 256 * D[B] >>> 0, D[B] = I % a >>> 0, I = I / a >>> 0;
      if (I !== 0)
        throw new Error("Non-zero carry");
      y = R, E++;
    }
    for (var C = m - y; C !== m && D[C] === 0; )
      C++;
    for (var w = c.repeat(g); C < m; ++C)
      w += t.charAt(D[C]);
    return w;
  }
  function f(d) {
    if (typeof d != "string")
      throw new TypeError("Expected String");
    if (d.length === 0)
      return new Uint8Array();
    var g = 0;
    if (d[g] !== " ") {
      for (var y = 0, E = 0; d[g] === c; )
        y++, g++;
      for (var v = (d.length - g) * u + 1 >>> 0, m = new Uint8Array(v); d[g]; ) {
        var D = i[d.charCodeAt(g)];
        if (D === 255)
          return;
        for (var I = 0, R = v - 1; (D !== 0 || I < E) && R !== -1; R--, I++)
          D += a * m[R] >>> 0, m[R] = D % 256 >>> 0, D = D / 256 >>> 0;
        if (D !== 0)
          throw new Error("Non-zero carry");
        E = I, g++;
      }
      if (d[g] !== " ") {
        for (var B = v - E; B !== v && m[B] === 0; )
          B++;
        for (var C = new Uint8Array(y + (v - B)), w = y; B !== v; )
          C[w++] = m[B++];
        return C;
      }
    }
  }
  function p(d) {
    var g = f(d);
    if (g)
      return g;
    throw new Error(`Non-${e} character`);
  }
  return {
    encode: l,
    decodeUnsafe: f,
    decode: p
  };
}
var Am = Dm, $m = Am;
const Om = (t) => {
  if (t instanceof Uint8Array && t.constructor.name === "Uint8Array")
    return t;
  if (t instanceof ArrayBuffer)
    return new Uint8Array(t);
  if (ArrayBuffer.isView(t))
    return new Uint8Array(t.buffer, t.byteOffset, t.byteLength);
  throw new Error("Unknown type, must be binary type");
}, Tm = (t) => new TextEncoder().encode(t), Cm = (t) => new TextDecoder().decode(t);
class Pm {
  constructor(e, i, r) {
    this.name = e, this.prefix = i, this.baseEncode = r;
  }
  encode(e) {
    if (e instanceof Uint8Array)
      return `${this.prefix}${this.baseEncode(e)}`;
    throw Error("Unknown type, must be binary type");
  }
}
class Rm {
  constructor(e, i, r) {
    if (this.name = e, this.prefix = i, i.codePointAt(0) === void 0)
      throw new Error("Invalid prefix character");
    this.prefixCodePoint = i.codePointAt(0), this.baseDecode = r;
  }
  decode(e) {
    if (typeof e == "string") {
      if (e.codePointAt(0) !== this.prefixCodePoint)
        throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);
      return this.baseDecode(e.slice(this.prefix.length));
    } else
      throw Error("Can only multibase decode strings");
  }
  or(e) {
    return Dl(this, e);
  }
}
class Fm {
  constructor(e) {
    this.decoders = e;
  }
  or(e) {
    return Dl(this, e);
  }
  decode(e) {
    const i = e[0], r = this.decoders[i];
    if (r)
      return r.decode(e);
    throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`);
  }
}
const Dl = (t, e) => new Fm({
  ...t.decoders || { [t.prefix]: t },
  ...e.decoders || { [e.prefix]: e }
});
class Um {
  constructor(e, i, r, s) {
    this.name = e, this.prefix = i, this.baseEncode = r, this.baseDecode = s, this.encoder = new Pm(e, i, r), this.decoder = new Rm(e, i, s);
  }
  encode(e) {
    return this.encoder.encode(e);
  }
  decode(e) {
    return this.decoder.decode(e);
  }
}
const tn = ({ name: t, prefix: e, encode: i, decode: r }) => new Um(t, e, i, r), Qr = ({ prefix: t, name: e, alphabet: i }) => {
  const { encode: r, decode: s } = $m(i, e);
  return tn({
    prefix: t,
    name: e,
    encode: r,
    decode: (n) => Om(s(n))
  });
}, Bm = (t, e, i, r) => {
  const s = {};
  for (let h = 0; h < e.length; ++h)
    s[e[h]] = h;
  let n = t.length;
  for (; t[n - 1] === "="; )
    --n;
  const o = new Uint8Array(n * i / 8 | 0);
  let a = 0, c = 0, u = 0;
  for (let h = 0; h < n; ++h) {
    const l = s[t[h]];
    if (l === void 0)
      throw new SyntaxError(`Non-${r} character`);
    c = c << i | l, a += i, a >= 8 && (a -= 8, o[u++] = 255 & c >> a);
  }
  if (a >= i || 255 & c << 8 - a)
    throw new SyntaxError("Unexpected end of data");
  return o;
}, Nm = (t, e, i) => {
  const r = e[e.length - 1] === "=", s = (1 << i) - 1;
  let n = "", o = 0, a = 0;
  for (let c = 0; c < t.length; ++c)
    for (a = a << 8 | t[c], o += 8; o > i; )
      o -= i, n += e[s & a >> o];
  if (o && (n += e[s & a << i - o]), r)
    for (; n.length * i & 7; )
      n += "=";
  return n;
}, Ce = ({ name: t, prefix: e, bitsPerChar: i, alphabet: r }) => tn({
  prefix: e,
  name: t,
  encode(s) {
    return Nm(s, r, i);
  },
  decode(s) {
    return Bm(s, r, i, t);
  }
}), km = tn({
  prefix: "\0",
  name: "identity",
  encode: (t) => Cm(t),
  decode: (t) => Tm(t)
}), Lm = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  identity: km
}, Symbol.toStringTag, { value: "Module" })), Mm = Ce({
  prefix: "0",
  name: "base2",
  alphabet: "01",
  bitsPerChar: 1
}), qm = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  base2: Mm
}, Symbol.toStringTag, { value: "Module" })), jm = Ce({
  prefix: "7",
  name: "base8",
  alphabet: "01234567",
  bitsPerChar: 3
}), zm = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  base8: jm
}, Symbol.toStringTag, { value: "Module" })), Km = Qr({
  prefix: "9",
  name: "base10",
  alphabet: "0123456789"
}), Vm = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  base10: Km
}, Symbol.toStringTag, { value: "Module" })), Hm = Ce({
  prefix: "f",
  name: "base16",
  alphabet: "0123456789abcdef",
  bitsPerChar: 4
}), Wm = Ce({
  prefix: "F",
  name: "base16upper",
  alphabet: "0123456789ABCDEF",
  bitsPerChar: 4
}), Gm = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  base16: Hm,
  base16upper: Wm
}, Symbol.toStringTag, { value: "Module" })), Ym = Ce({
  prefix: "b",
  name: "base32",
  alphabet: "abcdefghijklmnopqrstuvwxyz234567",
  bitsPerChar: 5
}), Jm = Ce({
  prefix: "B",
  name: "base32upper",
  alphabet: "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",
  bitsPerChar: 5
}), Zm = Ce({
  prefix: "c",
  name: "base32pad",
  alphabet: "abcdefghijklmnopqrstuvwxyz234567=",
  bitsPerChar: 5
}), Qm = Ce({
  prefix: "C",
  name: "base32padupper",
  alphabet: "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",
  bitsPerChar: 5
}), Xm = Ce({
  prefix: "v",
  name: "base32hex",
  alphabet: "0123456789abcdefghijklmnopqrstuv",
  bitsPerChar: 5
}), eb = Ce({
  prefix: "V",
  name: "base32hexupper",
  alphabet: "0123456789ABCDEFGHIJKLMNOPQRSTUV",
  bitsPerChar: 5
}), tb = Ce({
  prefix: "t",
  name: "base32hexpad",
  alphabet: "0123456789abcdefghijklmnopqrstuv=",
  bitsPerChar: 5
}), ib = Ce({
  prefix: "T",
  name: "base32hexpadupper",
  alphabet: "0123456789ABCDEFGHIJKLMNOPQRSTUV=",
  bitsPerChar: 5
}), rb = Ce({
  prefix: "h",
  name: "base32z",
  alphabet: "ybndrfg8ejkmcpqxot1uwisza345h769",
  bitsPerChar: 5
}), sb = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  base32: Ym,
  base32hex: Xm,
  base32hexpad: tb,
  base32hexpadupper: ib,
  base32hexupper: eb,
  base32pad: Zm,
  base32padupper: Qm,
  base32upper: Jm,
  base32z: rb
}, Symbol.toStringTag, { value: "Module" })), nb = Qr({
  prefix: "k",
  name: "base36",
  alphabet: "0123456789abcdefghijklmnopqrstuvwxyz"
}), ob = Qr({
  prefix: "K",
  name: "base36upper",
  alphabet: "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
}), ab = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  base36: nb,
  base36upper: ob
}, Symbol.toStringTag, { value: "Module" })), cb = Qr({
  name: "base58btc",
  prefix: "z",
  alphabet: "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
}), ub = Qr({
  name: "base58flickr",
  prefix: "Z",
  alphabet: "123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"
}), hb = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  base58btc: cb,
  base58flickr: ub
}, Symbol.toStringTag, { value: "Module" })), lb = Ce({
  prefix: "m",
  name: "base64",
  alphabet: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",
  bitsPerChar: 6
}), fb = Ce({
  prefix: "M",
  name: "base64pad",
  alphabet: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
  bitsPerChar: 6
}), db = Ce({
  prefix: "u",
  name: "base64url",
  alphabet: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",
  bitsPerChar: 6
}), pb = Ce({
  prefix: "U",
  name: "base64urlpad",
  alphabet: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",
  bitsPerChar: 6
}), gb = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  base64: lb,
  base64pad: fb,
  base64url: db,
  base64urlpad: pb
}, Symbol.toStringTag, { value: "Module" })), Al = Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"), yb = Al.reduce((t, e, i) => (t[i] = e, t), []), wb = Al.reduce((t, e, i) => (t[e.codePointAt(0)] = i, t), []);
function mb(t) {
  return t.reduce((e, i) => (e += yb[i], e), "");
}
function bb(t) {
  const e = [];
  for (const i of t) {
    const r = wb[i.codePointAt(0)];
    if (r === void 0)
      throw new Error(`Non-base256emoji character: ${i}`);
    e.push(r);
  }
  return new Uint8Array(e);
}
const vb = tn({
  prefix: "🚀",
  name: "base256emoji",
  encode: mb,
  decode: bb
}), Eb = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  base256emoji: vb
}, Symbol.toStringTag, { value: "Module" }));
new TextEncoder();
new TextDecoder();
const Cc = {
  ...Lm,
  ...qm,
  ...zm,
  ...Vm,
  ...Gm,
  ...sb,
  ...ab,
  ...hb,
  ...gb,
  ...Eb
};
function $l(t, e, i, r) {
  return {
    name: t,
    prefix: e,
    encoder: {
      name: t,
      prefix: e,
      encode: i
    },
    decoder: { decode: r }
  };
}
const Pc = $l("utf8", "u", (t) => "u" + new TextDecoder("utf8").decode(t), (t) => new TextEncoder().encode(t.substring(1))), Bn = $l("ascii", "a", (t) => {
  let e = "a";
  for (let i = 0; i < t.length; i++)
    e += String.fromCharCode(t[i]);
  return e;
}, (t) => {
  t = t.substring(1);
  const e = Sl(t.length);
  for (let i = 0; i < t.length; i++)
    e[i] = t.charCodeAt(i);
  return e;
}), Ol = {
  utf8: Pc,
  "utf-8": Pc,
  hex: Cc.base16,
  latin1: Bn,
  ascii: Bn,
  binary: Bn,
  ...Cc
};
function ht(t, e = "utf8") {
  const i = Ol[e];
  if (!i)
    throw new Error(`Unsupported encoding "${e}"`);
  return (e === "utf8" || e === "utf-8") && globalThis.Buffer != null && globalThis.Buffer.from != null ? sa(globalThis.Buffer.from(t, "utf-8")) : i.decoder.decode(`${i.prefix}${t}`);
}
function Ze(t, e = "utf8") {
  const i = Ol[e];
  if (!i)
    throw new Error(`Unsupported encoding "${e}"`);
  return (e === "utf8" || e === "utf-8") && globalThis.Buffer != null && globalThis.Buffer.from != null ? globalThis.Buffer.from(t.buffer, t.byteOffset, t.byteLength).toString("utf8") : i.encoder.encode(t).substring(1);
}
const _b = { waku: { publish: "waku_publish", batchPublish: "waku_batchPublish", subscribe: "waku_subscribe", batchSubscribe: "waku_batchSubscribe", subscription: "waku_subscription", unsubscribe: "waku_unsubscribe", batchUnsubscribe: "waku_batchUnsubscribe", batchFetchMessages: "waku_batchFetchMessages" }, irn: { publish: "irn_publish", batchPublish: "irn_batchPublish", subscribe: "irn_subscribe", batchSubscribe: "irn_batchSubscribe", subscription: "irn_subscription", unsubscribe: "irn_unsubscribe", batchUnsubscribe: "irn_batchUnsubscribe", batchFetchMessages: "irn_batchFetchMessages" }, iridium: { publish: "iridium_publish", batchPublish: "iridium_batchPublish", subscribe: "iridium_subscribe", batchSubscribe: "iridium_batchSubscribe", subscription: "iridium_subscription", unsubscribe: "iridium_unsubscribe", batchUnsubscribe: "iridium_batchUnsubscribe", batchFetchMessages: "iridium_batchFetchMessages" } }, xb = "Input must be an string, Buffer or Uint8Array";
function Ib(t) {
  let e;
  if (t instanceof Uint8Array)
    e = t;
  else if (typeof t == "string")
    e = new TextEncoder().encode(t);
  else
    throw new Error(xb);
  return e;
}
function Sb(t) {
  return Array.prototype.map.call(t, function(e) {
    return (e < 16 ? "0" : "") + e.toString(16);
  }).join("");
}
function ds(t) {
  return (4294967296 + t).toString(16).substring(1);
}
function Db(t, e, i) {
  let r = `
` + t + " = ";
  for (let s = 0; s < e.length; s += 2) {
    if (i === 32)
      r += ds(e[s]).toUpperCase(), r += " ", r += ds(e[s + 1]).toUpperCase();
    else if (i === 64)
      r += ds(e[s + 1]).toUpperCase(), r += ds(e[s]).toUpperCase();
    else
      throw new Error("Invalid size " + i);
    s % 6 === 4 ? r += `
` + new Array(t.length + 4).join(" ") : s < e.length - 2 && (r += " ");
  }
  console.log(r);
}
function Ab(t, e, i) {
  let r = (/* @__PURE__ */ new Date()).getTime();
  const s = new Uint8Array(e);
  for (let o = 0; o < e; o++)
    s[o] = o % 256;
  const n = (/* @__PURE__ */ new Date()).getTime();
  console.log("Generated random input in " + (n - r) + "ms"), r = n;
  for (let o = 0; o < i; o++) {
    const a = t(s), c = (/* @__PURE__ */ new Date()).getTime(), u = c - r;
    r = c, console.log("Hashed in " + u + "ms: " + a.substring(0, 20) + "..."), console.log(
      Math.round(e / (1 << 20) / (u / 1e3) * 100) / 100 + " MB PER SECOND"
    );
  }
}
var Tl = {
  normalizeInput: Ib,
  toHex: Sb,
  debugPrint: Db,
  testSpeed: Ab
};
const Ds = Tl;
function ps(t, e, i) {
  const r = t[e] + t[i];
  let s = t[e + 1] + t[i + 1];
  r >= 4294967296 && s++, t[e] = r, t[e + 1] = s;
}
function Rc(t, e, i, r) {
  let s = t[e] + i;
  i < 0 && (s += 4294967296);
  let n = t[e + 1] + r;
  s >= 4294967296 && n++, t[e] = s, t[e + 1] = n;
}
function Cl(t, e) {
  return t[e] ^ t[e + 1] << 8 ^ t[e + 2] << 16 ^ t[e + 3] << 24;
}
function Kt(t, e, i, r, s, n) {
  const o = xr[s], a = xr[s + 1], c = xr[n], u = xr[n + 1];
  ps(G, t, e), Rc(G, t, o, a);
  let h = G[r] ^ G[t], l = G[r + 1] ^ G[t + 1];
  G[r] = l, G[r + 1] = h, ps(G, i, r), h = G[e] ^ G[i], l = G[e + 1] ^ G[i + 1], G[e] = h >>> 24 ^ l << 8, G[e + 1] = l >>> 24 ^ h << 8, ps(G, t, e), Rc(G, t, c, u), h = G[r] ^ G[t], l = G[r + 1] ^ G[t + 1], G[r] = h >>> 16 ^ l << 16, G[r + 1] = l >>> 16 ^ h << 16, ps(G, i, r), h = G[e] ^ G[i], l = G[e + 1] ^ G[i + 1], G[e] = l >>> 31 ^ h << 1, G[e + 1] = h >>> 31 ^ l << 1;
}
const Pl = new Uint32Array([
  4089235720,
  1779033703,
  2227873595,
  3144134277,
  4271175723,
  1013904242,
  1595750129,
  2773480762,
  2917565137,
  1359893119,
  725511199,
  2600822924,
  4215389547,
  528734635,
  327033209,
  1541459225
]), $b = [
  0,
  1,
  2,
  3,
  4,
  5,
  6,
  7,
  8,
  9,
  10,
  11,
  12,
  13,
  14,
  15,
  14,
  10,
  4,
  8,
  9,
  15,
  13,
  6,
  1,
  12,
  0,
  2,
  11,
  7,
  5,
  3,
  11,
  8,
  12,
  0,
  5,
  2,
  15,
  13,
  10,
  14,
  3,
  6,
  7,
  1,
  9,
  4,
  7,
  9,
  3,
  1,
  13,
  12,
  11,
  14,
  2,
  6,
  5,
  10,
  4,
  0,
  15,
  8,
  9,
  0,
  5,
  7,
  2,
  4,
  10,
  15,
  14,
  1,
  11,
  12,
  6,
  8,
  3,
  13,
  2,
  12,
  6,
  10,
  0,
  11,
  8,
  3,
  4,
  13,
  7,
  5,
  15,
  14,
  1,
  9,
  12,
  5,
  1,
  15,
  14,
  13,
  4,
  10,
  0,
  7,
  6,
  3,
  9,
  2,
  8,
  11,
  13,
  11,
  7,
  14,
  12,
  1,
  3,
  9,
  5,
  0,
  15,
  4,
  8,
  6,
  2,
  10,
  6,
  15,
  14,
  9,
  11,
  3,
  0,
  8,
  12,
  2,
  13,
  7,
  1,
  4,
  10,
  5,
  10,
  2,
  8,
  4,
  7,
  6,
  1,
  5,
  15,
  11,
  9,
  14,
  3,
  12,
  13,
  0,
  0,
  1,
  2,
  3,
  4,
  5,
  6,
  7,
  8,
  9,
  10,
  11,
  12,
  13,
  14,
  15,
  14,
  10,
  4,
  8,
  9,
  15,
  13,
  6,
  1,
  12,
  0,
  2,
  11,
  7,
  5,
  3
], Re = new Uint8Array(
  $b.map(function(t) {
    return t * 2;
  })
), G = new Uint32Array(32), xr = new Uint32Array(32);
function Rl(t, e) {
  let i = 0;
  for (i = 0; i < 16; i++)
    G[i] = t.h[i], G[i + 16] = Pl[i];
  for (G[24] = G[24] ^ t.t, G[25] = G[25] ^ t.t / 4294967296, e && (G[28] = ~G[28], G[29] = ~G[29]), i = 0; i < 32; i++)
    xr[i] = Cl(t.b, 4 * i);
  for (i = 0; i < 12; i++)
    Kt(0, 8, 16, 24, Re[i * 16 + 0], Re[i * 16 + 1]), Kt(2, 10, 18, 26, Re[i * 16 + 2], Re[i * 16 + 3]), Kt(4, 12, 20, 28, Re[i * 16 + 4], Re[i * 16 + 5]), Kt(6, 14, 22, 30, Re[i * 16 + 6], Re[i * 16 + 7]), Kt(0, 10, 20, 30, Re[i * 16 + 8], Re[i * 16 + 9]), Kt(2, 12, 22, 24, Re[i * 16 + 10], Re[i * 16 + 11]), Kt(4, 14, 16, 26, Re[i * 16 + 12], Re[i * 16 + 13]), Kt(6, 8, 18, 28, Re[i * 16 + 14], Re[i * 16 + 15]);
  for (i = 0; i < 16; i++)
    t.h[i] = t.h[i] ^ G[i] ^ G[i + 16];
}
const Vt = new Uint8Array([
  0,
  0,
  0,
  0,
  //  0: outlen, keylen, fanout, depth
  0,
  0,
  0,
  0,
  //  4: leaf length, sequential mode
  0,
  0,
  0,
  0,
  //  8: node offset
  0,
  0,
  0,
  0,
  // 12: node offset
  0,
  0,
  0,
  0,
  // 16: node depth, inner length, rfu
  0,
  0,
  0,
  0,
  // 20: rfu
  0,
  0,
  0,
  0,
  // 24: rfu
  0,
  0,
  0,
  0,
  // 28: rfu
  0,
  0,
  0,
  0,
  // 32: salt
  0,
  0,
  0,
  0,
  // 36: salt
  0,
  0,
  0,
  0,
  // 40: salt
  0,
  0,
  0,
  0,
  // 44: salt
  0,
  0,
  0,
  0,
  // 48: personal
  0,
  0,
  0,
  0,
  // 52: personal
  0,
  0,
  0,
  0,
  // 56: personal
  0,
  0,
  0,
  0
  // 60: personal
]);
function Fl(t, e, i, r) {
  if (t === 0 || t > 64)
    throw new Error("Illegal output length, expected 0 < length <= 64");
  if (e && e.length > 64)
    throw new Error("Illegal key, expected Uint8Array with 0 < length <= 64");
  if (i && i.length !== 16)
    throw new Error("Illegal salt, expected Uint8Array with length is 16");
  if (r && r.length !== 16)
    throw new Error("Illegal personal, expected Uint8Array with length is 16");
  const s = {
    b: new Uint8Array(128),
    h: new Uint32Array(16),
    t: 0,
    // input count
    c: 0,
    // pointer within buffer
    outlen: t
    // output length in bytes
  };
  Vt.fill(0), Vt[0] = t, e && (Vt[1] = e.length), Vt[2] = 1, Vt[3] = 1, i && Vt.set(i, 32), r && Vt.set(r, 48);
  for (let n = 0; n < 16; n++)
    s.h[n] = Pl[n] ^ Cl(Vt, n * 4);
  return e && (na(s, e), s.c = 128), s;
}
function na(t, e) {
  for (let i = 0; i < e.length; i++)
    t.c === 128 && (t.t += t.c, Rl(t, !1), t.c = 0), t.b[t.c++] = e[i];
}
function Ul(t) {
  for (t.t += t.c; t.c < 128; )
    t.b[t.c++] = 0;
  Rl(t, !0);
  const e = new Uint8Array(t.outlen);
  for (let i = 0; i < t.outlen; i++)
    e[i] = t.h[i >> 2] >> 8 * (i & 3);
  return e;
}
function Bl(t, e, i, r, s) {
  i = i || 64, t = Ds.normalizeInput(t), r && (r = Ds.normalizeInput(r)), s && (s = Ds.normalizeInput(s));
  const n = Fl(i, e, r, s);
  return na(n, t), Ul(n);
}
function Ob(t, e, i, r, s) {
  const n = Bl(t, e, i, r, s);
  return Ds.toHex(n);
}
var Tb = {
  blake2b: Bl,
  blake2bHex: Ob,
  blake2bInit: Fl,
  blake2bUpdate: na,
  blake2bFinal: Ul
};
const Nl = Tl;
function Cb(t, e) {
  return t[e] ^ t[e + 1] << 8 ^ t[e + 2] << 16 ^ t[e + 3] << 24;
}
function Ht(t, e, i, r, s, n) {
  te[t] = te[t] + te[e] + s, te[r] = gs(te[r] ^ te[t], 16), te[i] = te[i] + te[r], te[e] = gs(te[e] ^ te[i], 12), te[t] = te[t] + te[e] + n, te[r] = gs(te[r] ^ te[t], 8), te[i] = te[i] + te[r], te[e] = gs(te[e] ^ te[i], 7);
}
function gs(t, e) {
  return t >>> e ^ t << 32 - e;
}
const kl = new Uint32Array([
  1779033703,
  3144134277,
  1013904242,
  2773480762,
  1359893119,
  2600822924,
  528734635,
  1541459225
]), Fe = new Uint8Array([
  0,
  1,
  2,
  3,
  4,
  5,
  6,
  7,
  8,
  9,
  10,
  11,
  12,
  13,
  14,
  15,
  14,
  10,
  4,
  8,
  9,
  15,
  13,
  6,
  1,
  12,
  0,
  2,
  11,
  7,
  5,
  3,
  11,
  8,
  12,
  0,
  5,
  2,
  15,
  13,
  10,
  14,
  3,
  6,
  7,
  1,
  9,
  4,
  7,
  9,
  3,
  1,
  13,
  12,
  11,
  14,
  2,
  6,
  5,
  10,
  4,
  0,
  15,
  8,
  9,
  0,
  5,
  7,
  2,
  4,
  10,
  15,
  14,
  1,
  11,
  12,
  6,
  8,
  3,
  13,
  2,
  12,
  6,
  10,
  0,
  11,
  8,
  3,
  4,
  13,
  7,
  5,
  15,
  14,
  1,
  9,
  12,
  5,
  1,
  15,
  14,
  13,
  4,
  10,
  0,
  7,
  6,
  3,
  9,
  2,
  8,
  11,
  13,
  11,
  7,
  14,
  12,
  1,
  3,
  9,
  5,
  0,
  15,
  4,
  8,
  6,
  2,
  10,
  6,
  15,
  14,
  9,
  11,
  3,
  0,
  8,
  12,
  2,
  13,
  7,
  1,
  4,
  10,
  5,
  10,
  2,
  8,
  4,
  7,
  6,
  1,
  5,
  15,
  11,
  9,
  14,
  3,
  12,
  13,
  0
]), te = new Uint32Array(16), Se = new Uint32Array(16);
function Ll(t, e) {
  let i = 0;
  for (i = 0; i < 8; i++)
    te[i] = t.h[i], te[i + 8] = kl[i];
  for (te[12] ^= t.t, te[13] ^= t.t / 4294967296, e && (te[14] = ~te[14]), i = 0; i < 16; i++)
    Se[i] = Cb(t.b, 4 * i);
  for (i = 0; i < 10; i++)
    Ht(0, 4, 8, 12, Se[Fe[i * 16 + 0]], Se[Fe[i * 16 + 1]]), Ht(1, 5, 9, 13, Se[Fe[i * 16 + 2]], Se[Fe[i * 16 + 3]]), Ht(2, 6, 10, 14, Se[Fe[i * 16 + 4]], Se[Fe[i * 16 + 5]]), Ht(3, 7, 11, 15, Se[Fe[i * 16 + 6]], Se[Fe[i * 16 + 7]]), Ht(0, 5, 10, 15, Se[Fe[i * 16 + 8]], Se[Fe[i * 16 + 9]]), Ht(1, 6, 11, 12, Se[Fe[i * 16 + 10]], Se[Fe[i * 16 + 11]]), Ht(2, 7, 8, 13, Se[Fe[i * 16 + 12]], Se[Fe[i * 16 + 13]]), Ht(3, 4, 9, 14, Se[Fe[i * 16 + 14]], Se[Fe[i * 16 + 15]]);
  for (i = 0; i < 8; i++)
    t.h[i] ^= te[i] ^ te[i + 8];
}
function Ml(t, e) {
  if (!(t > 0 && t <= 32))
    throw new Error("Incorrect output length, should be in [1, 32]");
  const i = e ? e.length : 0;
  if (e && !(i > 0 && i <= 32))
    throw new Error("Incorrect key length, should be in [1, 32]");
  const r = {
    h: new Uint32Array(kl),
    // hash state
    b: new Uint8Array(64),
    // input block
    c: 0,
    // pointer within block
    t: 0,
    // input count
    outlen: t
    // output length in bytes
  };
  return r.h[0] ^= 16842752 ^ i << 8 ^ t, i > 0 && (oa(r, e), r.c = 64), r;
}
function oa(t, e) {
  for (let i = 0; i < e.length; i++)
    t.c === 64 && (t.t += t.c, Ll(t, !1), t.c = 0), t.b[t.c++] = e[i];
}
function ql(t) {
  for (t.t += t.c; t.c < 64; )
    t.b[t.c++] = 0;
  Ll(t, !0);
  const e = new Uint8Array(t.outlen);
  for (let i = 0; i < t.outlen; i++)
    e[i] = t.h[i >> 2] >> 8 * (i & 3) & 255;
  return e;
}
function jl(t, e, i) {
  i = i || 32, t = Nl.normalizeInput(t);
  const r = Ml(i, e);
  return oa(r, t), ql(r);
}
function Pb(t, e, i) {
  const r = jl(t, e, i);
  return Nl.toHex(r);
}
var Rb = {
  blake2s: jl,
  blake2sHex: Pb,
  blake2sInit: Ml,
  blake2sUpdate: oa,
  blake2sFinal: ql
};
const dr = Tb, pr = Rb;
var Fb = {
  blake2b: dr.blake2b,
  blake2bHex: dr.blake2bHex,
  blake2bInit: dr.blake2bInit,
  blake2bUpdate: dr.blake2bUpdate,
  blake2bFinal: dr.blake2bFinal,
  blake2s: pr.blake2s,
  blake2sHex: pr.blake2sHex,
  blake2sInit: pr.blake2sInit,
  blake2sUpdate: pr.blake2sUpdate,
  blake2sFinal: pr.blake2sFinal
};
const aa = ":";
function As(t) {
  const [e, i] = t.split(aa);
  return { namespace: e, reference: i };
}
function Ub(t) {
  const { namespace: e, reference: i } = t;
  return [e, i].join(aa);
}
function Bb(t) {
  const [e, i, r] = t.split(aa);
  return { namespace: e, reference: i, address: r };
}
function Nb(t, e) {
  const i = [];
  return t.forEach((r) => {
    const s = e(r);
    i.includes(s) || i.push(s);
  }), i;
}
function kb(t) {
  const { namespace: e, reference: i } = Bb(t);
  return Ub({ namespace: e, reference: i });
}
function Lb(t) {
  return Nb(t, kb);
}
function zl(t, e = []) {
  const i = [];
  return Object.keys(t).forEach((r) => {
    if (e.length && !e.includes(r))
      return;
    const s = t[r];
    i.push(...s.accounts);
  }), i;
}
function Kl(t, e = []) {
  const i = [];
  return Object.keys(t).forEach((r) => {
    if (e.length && !e.includes(r))
      return;
    const s = t[r];
    i.push(...Lb(s.accounts));
  }), i;
}
function Mb(t, e = []) {
  const i = [];
  return Object.keys(t).forEach((r) => {
    if (e.length && !e.includes(r))
      return;
    const s = t[r];
    i.push(...ca(r, s));
  }), i;
}
function ca(t, e) {
  return t.includes(":") ? [t] : e.chains || [];
}
var qb = Object.defineProperty, jb = Object.defineProperties, zb = Object.getOwnPropertyDescriptors, Fc = Object.getOwnPropertySymbols, Kb = Object.prototype.hasOwnProperty, Vb = Object.prototype.propertyIsEnumerable, mo = (t, e, i) => e in t ? qb(t, e, { enumerable: !0, configurable: !0, writable: !0, value: i }) : t[e] = i, Uc = (t, e) => {
  for (var i in e || (e = {}))
    Kb.call(e, i) && mo(t, i, e[i]);
  if (Fc)
    for (var i of Fc(e))
      Vb.call(e, i) && mo(t, i, e[i]);
  return t;
}, Hb = (t, e) => jb(t, zb(e)), Bc = (t, e, i) => mo(t, typeof e != "symbol" ? e + "" : e, i);
const Wb = "ReactNative", it = { reactNative: "react-native", node: "node", browser: "browser", unknown: "unknown" }, Gb = "js";
function qs() {
  return typeof process < "u" && typeof process.versions < "u" && typeof process.versions.node < "u";
}
function ci() {
  return !Si() && !!Xo() && navigator.product === Wb;
}
function Yb() {
  return ci() && typeof global < "u" && typeof (global == null ? void 0 : global.Platform) < "u" && (global == null ? void 0 : global.Platform.OS) === "android";
}
function Jb() {
  return ci() && typeof global < "u" && typeof (global == null ? void 0 : global.Platform) < "u" && (global == null ? void 0 : global.Platform.OS) === "ios";
}
function rr() {
  return !qs() && !!Xo() && !!Si();
}
function Xr() {
  return ci() ? it.reactNative : qs() ? it.node : rr() ? it.browser : it.unknown;
}
function Nc() {
  var t;
  try {
    return ci() && typeof global < "u" && typeof (global == null ? void 0 : global.Application) < "u" ? (t = global.Application) == null ? void 0 : t.applicationId : void 0;
  } catch {
    return;
  }
}
function Zb(t, e) {
  const i = new URLSearchParams(t);
  for (const r of Object.keys(e).sort())
    if (e.hasOwnProperty(r)) {
      const s = e[r];
      s !== void 0 && i.set(r, s);
    }
  return i.toString();
}
function Qb(t) {
  var e, i;
  const r = Vl();
  try {
    return t != null && t.url && r.url && new URL(t.url).host !== new URL(r.url).host && (console.warn(`The configured WalletConnect 'metadata.url':${t.url} differs from the actual page url:${r.url}. This is probably unintended and can lead to issues.`), t.url = r.url), (e = t?.icons) != null && e.length && t.icons.length > 0 && (t.icons = t.icons.filter((s) => s !== "")), Hb(Uc(Uc({}, r), t), { url: t?.url || r.url, name: t?.name || r.name, description: t?.description || r.description, icons: (i = t?.icons) != null && i.length && t.icons.length > 0 ? t.icons : r.icons });
  } catch (s) {
    return console.warn("Error populating app metadata", s), t || r;
  }
}
function Vl() {
  return il() || { name: "", description: "", url: "", icons: [""] };
}
function Xb() {
  if (Xr() === it.reactNative && typeof global < "u" && typeof (global == null ? void 0 : global.Platform) < "u") {
    const { OS: i, Version: r } = global.Platform;
    return [i, r].join("-");
  }
  const t = Id();
  if (t === null)
    return "unknown";
  const e = t.os ? t.os.replace(" ", "").toLowerCase() : "unknown";
  return t.type === "browser" ? [e, t.name, t.version].join("-") : [e, t.version].join("-");
}
function ev() {
  var t;
  const e = Xr();
  return e === it.browser ? [e, ((t = tl()) == null ? void 0 : t.host) || "unknown"].join(":") : e;
}
function Hl(t, e, i) {
  const r = Xb(), s = ev();
  return [[t, e].join("-"), [Gb, i].join("-"), r, s].join("/");
}
function tv({ protocol: t, version: e, relayUrl: i, sdkVersion: r, auth: s, projectId: n, useOnCloseEvent: o, bundleId: a, packageName: c }) {
  const u = i.split("?"), h = Hl(t, e, r), l = { auth: s, ua: h, projectId: n, useOnCloseEvent: o || void 0, packageName: c || void 0, bundleId: a || void 0 }, f = Zb(u[1] || "", l);
  return u[0] + "?" + f;
}
function bi(t, e) {
  return t.filter((i) => e.includes(i)).length === t.length;
}
function bo(t) {
  return Object.fromEntries(t.entries());
}
function vo(t) {
  return new Map(Object.entries(t));
}
function yi(t = L.FIVE_MINUTES, e) {
  const i = L.toMiliseconds(t || L.FIVE_MINUTES);
  let r, s, n, o;
  return { resolve: (a) => {
    n && r && (clearTimeout(n), r(a), o = Promise.resolve(a));
  }, reject: (a) => {
    n && s && (clearTimeout(n), s(a));
  }, done: () => new Promise((a, c) => {
    if (o)
      return a(o);
    n = setTimeout(() => {
      const u = new Error(e);
      o = Promise.reject(u), c(u);
    }, i), r = a, s = c;
  }) };
}
function At(t, e, i) {
  return new Promise(async (r, s) => {
    const n = setTimeout(() => s(new Error(i)), e);
    try {
      const o = await t;
      r(o);
    } catch (o) {
      s(o);
    }
    clearTimeout(n);
  });
}
function Wl(t, e) {
  if (typeof e == "string" && e.startsWith(`${t}:`))
    return e;
  if (t.toLowerCase() === "topic") {
    if (typeof e != "string")
      throw new Error('Value must be "string" for expirer target type: topic');
    return `topic:${e}`;
  } else if (t.toLowerCase() === "id") {
    if (typeof e != "number")
      throw new Error('Value must be "number" for expirer target type: id');
    return `id:${e}`;
  }
  throw new Error(`Unknown expirer target type: ${t}`);
}
function iv(t) {
  return Wl("topic", t);
}
function rv(t) {
  return Wl("id", t);
}
function Gl(t) {
  const [e, i] = t.split(":"), r = { id: void 0, topic: void 0 };
  if (e === "topic" && typeof i == "string")
    r.topic = i;
  else if (e === "id" && Number.isInteger(Number(i)))
    r.id = Number(i);
  else
    throw new Error(`Invalid target, expected id:number or topic:string, got ${e}:${i}`);
  return r;
}
function me(t, e) {
  return L.fromMiliseconds((e || Date.now()) + L.toMiliseconds(t));
}
function ei(t) {
  return Date.now() >= L.toMiliseconds(t);
}
function se(t, e) {
  return `${t}${e ? `:${e}` : ""}`;
}
function xi(t = [], e = []) {
  return [.../* @__PURE__ */ new Set([...t, ...e])];
}
async function sv({ id: t, topic: e, wcDeepLink: i }) {
  var r;
  try {
    if (!i)
      return;
    const s = typeof i == "string" ? JSON.parse(i) : i, n = s?.href;
    if (typeof n != "string")
      return;
    const o = nv(n, t, e), a = Xr();
    if (a === it.browser) {
      if (!((r = Si()) != null && r.hasFocus())) {
        console.warn("Document does not have focus, skipping deeplink.");
        return;
      }
      ov(o);
    } else
      a === it.reactNative && typeof (global == null ? void 0 : global.Linking) < "u" && await global.Linking.openURL(o);
  } catch (s) {
    console.error(s);
  }
}
function nv(t, e, i) {
  const r = `requestId=${e}&sessionTopic=${i}`;
  t.endsWith("/") && (t = t.slice(0, -1));
  let s = `${t}`;
  if (t.startsWith("https://t.me")) {
    const n = t.includes("?") ? "&startapp=" : "?startapp=";
    s = `${s}${n}${hv(r, !0)}`;
  } else
    s = `${s}/wc?${r}`;
  return s;
}
function ov(t) {
  let e = "_self";
  uv() ? e = "_top" : (cv() || t.startsWith("https://") || t.startsWith("http://")) && (e = "_blank"), window.open(t, e, "noreferrer noopener");
}
async function av(t, e) {
  let i = "";
  try {
    if (rr() && (i = localStorage.getItem(e), i))
      return i;
    i = await t.getItem(e);
  } catch (r) {
    console.error(r);
  }
  return i;
}
function kc(t, e) {
  if (!t.includes(e))
    return null;
  const i = t.split(/([&,?,=])/), r = i.indexOf(e);
  return i[r + 2];
}
function Lc() {
  return typeof crypto < "u" && crypto != null && crypto.randomUUID ? crypto.randomUUID() : "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/gu, (t) => {
    const e = Math.random() * 16 | 0;
    return (t === "x" ? e : e & 3 | 8).toString(16);
  });
}
function ua() {
  return typeof process < "u" && process.env.IS_VITEST === "true";
}
function cv() {
  return typeof window < "u" && (!!window.TelegramWebviewProxy || !!window.Telegram || !!window.TelegramWebviewProxyProto);
}
function uv() {
  try {
    return window.self !== window.top;
  } catch {
    return !1;
  }
}
function hv(t, e = !1) {
  const i = Buffer.from(t).toString("base64");
  return e ? i.replace(/[=]/g, "") : i;
}
function Yl(t) {
  return Buffer.from(t, "base64").toString("utf-8");
}
function lv(t) {
  return new Promise((e) => setTimeout(e, t));
}
let fv = class {
  constructor({ limit: e }) {
    Bc(this, "limit"), Bc(this, "set"), this.limit = e, this.set = /* @__PURE__ */ new Set();
  }
  add(e) {
    if (!this.set.has(e)) {
      if (this.set.size >= this.limit) {
        const i = this.set.values().next().value;
        i && this.set.delete(i);
      }
      this.set.add(e);
    }
  }
  has(e) {
    return this.set.has(e);
  }
};
const ys = BigInt(2 ** 32 - 1), Mc = BigInt(32);
function Jl(t, e = !1) {
  return e ? { h: Number(t & ys), l: Number(t >> Mc & ys) } : { h: Number(t >> Mc & ys) | 0, l: Number(t & ys) | 0 };
}
function Zl(t, e = !1) {
  const i = t.length;
  let r = new Uint32Array(i), s = new Uint32Array(i);
  for (let n = 0; n < i; n++) {
    const { h: o, l: a } = Jl(t[n], e);
    [r[n], s[n]] = [o, a];
  }
  return [r, s];
}
const qc = (t, e, i) => t >>> i, jc = (t, e, i) => t << 32 - i | e >>> i, ti = (t, e, i) => t >>> i | e << 32 - i, ii = (t, e, i) => t << 32 - i | e >>> i, Ir = (t, e, i) => t << 64 - i | e >>> i - 32, Sr = (t, e, i) => t >>> i - 32 | e << 64 - i, dv = (t, e) => e, pv = (t, e) => t, gv = (t, e, i) => t << i | e >>> 32 - i, yv = (t, e, i) => e << i | t >>> 32 - i, wv = (t, e, i) => e << i - 32 | t >>> 64 - i, mv = (t, e, i) => t << i - 32 | e >>> 64 - i;
function yt(t, e, i, r) {
  const s = (e >>> 0) + (r >>> 0);
  return { h: t + i + (s / 2 ** 32 | 0) | 0, l: s | 0 };
}
const ha = (t, e, i) => (t >>> 0) + (e >>> 0) + (i >>> 0), la = (t, e, i, r) => e + i + r + (t / 2 ** 32 | 0) | 0, bv = (t, e, i, r) => (t >>> 0) + (e >>> 0) + (i >>> 0) + (r >>> 0), vv = (t, e, i, r, s) => e + i + r + s + (t / 2 ** 32 | 0) | 0, Ev = (t, e, i, r, s) => (t >>> 0) + (e >>> 0) + (i >>> 0) + (r >>> 0) + (s >>> 0), _v = (t, e, i, r, s, n) => e + i + r + s + n + (t / 2 ** 32 | 0) | 0, qi = typeof globalThis == "object" && "crypto" in globalThis ? globalThis.crypto : void 0;
function fa(t) {
  return t instanceof Uint8Array || ArrayBuffer.isView(t) && t.constructor.name === "Uint8Array";
}
function qt(t) {
  if (!Number.isSafeInteger(t) || t < 0)
    throw new Error("positive integer expected, got " + t);
}
function lt(t, ...e) {
  if (!fa(t))
    throw new Error("Uint8Array expected");
  if (e.length > 0 && !e.includes(t.length))
    throw new Error("Uint8Array expected of length " + e + ", got length=" + t.length);
}
function da(t) {
  if (typeof t != "function" || typeof t.create != "function")
    throw new Error("Hash should be wrapped by utils.createHasher");
  qt(t.outputLen), qt(t.blockLen);
}
function ai(t, e = !0) {
  if (t.destroyed)
    throw new Error("Hash instance has been destroyed");
  if (e && t.finished)
    throw new Error("Hash#digest() has already been called");
}
function pa(t, e) {
  lt(t);
  const i = e.outputLen;
  if (t.length < i)
    throw new Error("digestInto() expects output buffer of length at least " + i);
}
function qr(t) {
  return new Uint32Array(t.buffer, t.byteOffset, Math.floor(t.byteLength / 4));
}
function ft(...t) {
  for (let e = 0; e < t.length; e++)
    t[e].fill(0);
}
function Nn(t) {
  return new DataView(t.buffer, t.byteOffset, t.byteLength);
}
function vt(t, e) {
  return t << 32 - e | t >>> e;
}
const Ql = new Uint8Array(new Uint32Array([287454020]).buffer)[0] === 68;
function Xl(t) {
  return t << 24 & 4278190080 | t << 8 & 16711680 | t >>> 8 & 65280 | t >>> 24 & 255;
}
const Bt = Ql ? (t) => t : (t) => Xl(t);
function xv(t) {
  for (let e = 0; e < t.length; e++)
    t[e] = Xl(t[e]);
  return t;
}
const ri = Ql ? (t) => t : xv, ef = typeof Uint8Array.from([]).toHex == "function" && typeof Uint8Array.fromHex == "function", Iv = Array.from({ length: 256 }, (t, e) => e.toString(16).padStart(2, "0"));
function jr(t) {
  if (lt(t), ef)
    return t.toHex();
  let e = "";
  for (let i = 0; i < t.length; i++)
    e += Iv[t[i]];
  return e;
}
const Rt = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 };
function zc(t) {
  if (t >= Rt._0 && t <= Rt._9)
    return t - Rt._0;
  if (t >= Rt.A && t <= Rt.F)
    return t - (Rt.A - 10);
  if (t >= Rt.a && t <= Rt.f)
    return t - (Rt.a - 10);
}
function ga(t) {
  if (typeof t != "string")
    throw new Error("hex string expected, got " + typeof t);
  if (ef)
    return Uint8Array.fromHex(t);
  const e = t.length, i = e / 2;
  if (e % 2)
    throw new Error("hex string expected, got unpadded hex of length " + e);
  const r = new Uint8Array(i);
  for (let s = 0, n = 0; s < i; s++, n += 2) {
    const o = zc(t.charCodeAt(n)), a = zc(t.charCodeAt(n + 1));
    if (o === void 0 || a === void 0) {
      const c = t[n] + t[n + 1];
      throw new Error('hex string expected, got non-hex character "' + c + '" at index ' + n);
    }
    r[s] = o * 16 + a;
  }
  return r;
}
function Sv(t) {
  if (typeof t != "string")
    throw new Error("string expected");
  return new Uint8Array(new TextEncoder().encode(t));
}
function mt(t) {
  return typeof t == "string" && (t = Sv(t)), lt(t), t;
}
function vi(...t) {
  let e = 0;
  for (let r = 0; r < t.length; r++) {
    const s = t[r];
    lt(s), e += s.length;
  }
  const i = new Uint8Array(e);
  for (let r = 0, s = 0; r < t.length; r++) {
    const n = t[r];
    i.set(n, s), s += n.length;
  }
  return i;
}
class rn {
}
function es(t) {
  const e = (r) => t().update(mt(r)).digest(), i = t();
  return e.outputLen = i.outputLen, e.blockLen = i.blockLen, e.create = () => t(), e;
}
function Dv(t) {
  const e = (r, s) => t(s).update(mt(r)).digest(), i = t({});
  return e.outputLen = i.outputLen, e.blockLen = i.blockLen, e.create = (r) => t(r), e;
}
function sr(t = 32) {
  if (qi && typeof qi.getRandomValues == "function")
    return qi.getRandomValues(new Uint8Array(t));
  if (qi && typeof qi.randomBytes == "function")
    return Uint8Array.from(qi.randomBytes(t));
  throw new Error("crypto.getRandomValues must be defined");
}
const Av = BigInt(0), gr = BigInt(1), $v = BigInt(2), Ov = BigInt(7), Tv = BigInt(256), Cv = BigInt(113), tf = [], rf = [], sf = [];
for (let t = 0, e = gr, i = 1, r = 0; t < 24; t++) {
  [i, r] = [r, (2 * i + 3 * r) % 5], tf.push(2 * (5 * r + i)), rf.push((t + 1) * (t + 2) / 2 % 64);
  let s = Av;
  for (let n = 0; n < 7; n++)
    e = (e << gr ^ (e >> Ov) * Cv) % Tv, e & $v && (s ^= gr << (gr << BigInt(n)) - gr);
  sf.push(s);
}
const nf = Zl(sf, !0), Pv = nf[0], Rv = nf[1], Kc = (t, e, i) => i > 32 ? wv(t, e, i) : gv(t, e, i), Vc = (t, e, i) => i > 32 ? mv(t, e, i) : yv(t, e, i);
function Fv(t, e = 24) {
  const i = new Uint32Array(10);
  for (let r = 24 - e; r < 24; r++) {
    for (let o = 0; o < 10; o++)
      i[o] = t[o] ^ t[o + 10] ^ t[o + 20] ^ t[o + 30] ^ t[o + 40];
    for (let o = 0; o < 10; o += 2) {
      const a = (o + 8) % 10, c = (o + 2) % 10, u = i[c], h = i[c + 1], l = Kc(u, h, 1) ^ i[a], f = Vc(u, h, 1) ^ i[a + 1];
      for (let p = 0; p < 50; p += 10)
        t[o + p] ^= l, t[o + p + 1] ^= f;
    }
    let s = t[2], n = t[3];
    for (let o = 0; o < 24; o++) {
      const a = rf[o], c = Kc(s, n, a), u = Vc(s, n, a), h = tf[o];
      s = t[h], n = t[h + 1], t[h] = c, t[h + 1] = u;
    }
    for (let o = 0; o < 50; o += 10) {
      for (let a = 0; a < 10; a++)
        i[a] = t[o + a];
      for (let a = 0; a < 10; a++)
        t[o + a] ^= ~i[(a + 2) % 10] & i[(a + 4) % 10];
    }
    t[0] ^= Pv[r], t[1] ^= Rv[r];
  }
  ft(i);
}
let Uv = class of extends rn {
  constructor(e, i, r, s = !1, n = 24) {
    if (super(), this.pos = 0, this.posOut = 0, this.finished = !1, this.destroyed = !1, this.enableXOF = !1, this.blockLen = e, this.suffix = i, this.outputLen = r, this.enableXOF = s, this.rounds = n, qt(r), !(0 < e && e < 200))
      throw new Error("only keccak-f1600 function is supported");
    this.state = new Uint8Array(200), this.state32 = qr(this.state);
  }
  clone() {
    return this._cloneInto();
  }
  keccak() {
    ri(this.state32), Fv(this.state32, this.rounds), ri(this.state32), this.posOut = 0, this.pos = 0;
  }
  update(e) {
    ai(this), e = mt(e), lt(e);
    const { blockLen: i, state: r } = this, s = e.length;
    for (let n = 0; n < s; ) {
      const o = Math.min(i - this.pos, s - n);
      for (let a = 0; a < o; a++)
        r[this.pos++] ^= e[n++];
      this.pos === i && this.keccak();
    }
    return this;
  }
  finish() {
    if (this.finished)
      return;
    this.finished = !0;
    const { state: e, suffix: i, pos: r, blockLen: s } = this;
    e[r] ^= i, i & 128 && r === s - 1 && this.keccak(), e[s - 1] ^= 128, this.keccak();
  }
  writeInto(e) {
    ai(this, !1), lt(e), this.finish();
    const i = this.state, { blockLen: r } = this;
    for (let s = 0, n = e.length; s < n; ) {
      this.posOut >= r && this.keccak();
      const o = Math.min(r - this.posOut, n - s);
      e.set(i.subarray(this.posOut, this.posOut + o), s), this.posOut += o, s += o;
    }
    return e;
  }
  xofInto(e) {
    if (!this.enableXOF)
      throw new Error("XOF is not possible for this instance");
    return this.writeInto(e);
  }
  xof(e) {
    return qt(e), this.xofInto(new Uint8Array(e));
  }
  digestInto(e) {
    if (pa(e, this), this.finished)
      throw new Error("digest() was already called");
    return this.writeInto(e), this.destroy(), e;
  }
  digest() {
    return this.digestInto(new Uint8Array(this.outputLen));
  }
  destroy() {
    this.destroyed = !0, ft(this.state);
  }
  _cloneInto(e) {
    const { blockLen: i, suffix: r, outputLen: s, rounds: n, enableXOF: o } = this;
    return e || (e = new of(i, r, s, o, n)), e.state32.set(this.state32), e.pos = this.pos, e.posOut = this.posOut, e.finished = this.finished, e.rounds = n, e.suffix = r, e.outputLen = s, e.enableXOF = o, e.destroyed = this.destroyed, e;
  }
};
const Bv = (t, e, i) => es(() => new Uv(e, t, i)), Nv = Bv(1, 136, 256 / 8);
function kv(t, e, i, r) {
  if (typeof t.setBigUint64 == "function")
    return t.setBigUint64(e, i, r);
  const s = BigInt(32), n = BigInt(4294967295), o = Number(i >> s & n), a = Number(i & n), c = r ? 4 : 0, u = r ? 0 : 4;
  t.setUint32(e + c, o, r), t.setUint32(e + u, a, r);
}
function Lv(t, e, i) {
  return t & e ^ ~t & i;
}
function Mv(t, e, i) {
  return t & e ^ t & i ^ e & i;
}
let af = class extends rn {
  constructor(e, i, r, s) {
    super(), this.finished = !1, this.length = 0, this.pos = 0, this.destroyed = !1, this.blockLen = e, this.outputLen = i, this.padOffset = r, this.isLE = s, this.buffer = new Uint8Array(e), this.view = Nn(this.buffer);
  }
  update(e) {
    ai(this), e = mt(e), lt(e);
    const { view: i, buffer: r, blockLen: s } = this, n = e.length;
    for (let o = 0; o < n; ) {
      const a = Math.min(s - this.pos, n - o);
      if (a === s) {
        const c = Nn(e);
        for (; s <= n - o; o += s)
          this.process(c, o);
        continue;
      }
      r.set(e.subarray(o, o + a), this.pos), this.pos += a, o += a, this.pos === s && (this.process(i, 0), this.pos = 0);
    }
    return this.length += e.length, this.roundClean(), this;
  }
  digestInto(e) {
    ai(this), pa(e, this), this.finished = !0;
    const { buffer: i, view: r, blockLen: s, isLE: n } = this;
    let { pos: o } = this;
    i[o++] = 128, ft(this.buffer.subarray(o)), this.padOffset > s - o && (this.process(r, 0), o = 0);
    for (let l = o; l < s; l++)
      i[l] = 0;
    kv(r, s - 8, BigInt(this.length * 8), n), this.process(r, 0);
    const a = Nn(e), c = this.outputLen;
    if (c % 4)
      throw new Error("_sha2: outputLen should be aligned to 32bit");
    const u = c / 4, h = this.get();
    if (u > h.length)
      throw new Error("_sha2: outputLen bigger than state");
    for (let l = 0; l < u; l++)
      a.setUint32(4 * l, h[l], n);
  }
  digest() {
    const { buffer: e, outputLen: i } = this;
    this.digestInto(e);
    const r = e.slice(0, i);
    return this.destroy(), r;
  }
  _cloneInto(e) {
    e || (e = new this.constructor()), e.set(...this.get());
    const { blockLen: i, buffer: r, length: s, finished: n, destroyed: o, pos: a } = this;
    return e.destroyed = o, e.finished = n, e.length = s, e.pos = a, s % i && e.buffer.set(r), e;
  }
  clone() {
    return this._cloneInto();
  }
};
const Wt = Uint32Array.from([1779033703, 3144134277, 1013904242, 2773480762, 1359893119, 2600822924, 528734635, 1541459225]), Ue = Uint32Array.from([3418070365, 3238371032, 1654270250, 914150663, 2438529370, 812702999, 355462360, 4144912697, 1731405415, 4290775857, 2394180231, 1750603025, 3675008525, 1694076839, 1203062813, 3204075428]), Be = Uint32Array.from([1779033703, 4089235720, 3144134277, 2227873595, 1013904242, 4271175723, 2773480762, 1595750129, 1359893119, 2917565137, 2600822924, 725511199, 528734635, 4215389547, 1541459225, 327033209]), qv = Uint32Array.from([1116352408, 1899447441, 3049323471, 3921009573, 961987163, 1508970993, 2453635748, 2870763221, 3624381080, 310598401, 607225278, 1426881987, 1925078388, 2162078206, 2614888103, 3248222580, 3835390401, 4022224774, 264347078, 604807628, 770255983, 1249150122, 1555081692, 1996064986, 2554220882, 2821834349, 2952996808, 3210313671, 3336571891, 3584528711, 113926993, 338241895, 666307205, 773529912, 1294757372, 1396182291, 1695183700, 1986661051, 2177026350, 2456956037, 2730485921, 2820302411, 3259730800, 3345764771, 3516065817, 3600352804, 4094571909, 275423344, 430227734, 506948616, 659060556, 883997877, 958139571, 1322822218, 1537002063, 1747873779, 1955562222, 2024104815, 2227730452, 2361852424, 2428436474, 2756734187, 3204031479, 3329325298]), Gt = new Uint32Array(64);
let jv = class extends af {
  constructor(e = 32) {
    super(64, e, 8, !1), this.A = Wt[0] | 0, this.B = Wt[1] | 0, this.C = Wt[2] | 0, this.D = Wt[3] | 0, this.E = Wt[4] | 0, this.F = Wt[5] | 0, this.G = Wt[6] | 0, this.H = Wt[7] | 0;
  }
  get() {
    const { A: e, B: i, C: r, D: s, E: n, F: o, G: a, H: c } = this;
    return [e, i, r, s, n, o, a, c];
  }
  set(e, i, r, s, n, o, a, c) {
    this.A = e | 0, this.B = i | 0, this.C = r | 0, this.D = s | 0, this.E = n | 0, this.F = o | 0, this.G = a | 0, this.H = c | 0;
  }
  process(e, i) {
    for (let l = 0; l < 16; l++, i += 4)
      Gt[l] = e.getUint32(i, !1);
    for (let l = 16; l < 64; l++) {
      const f = Gt[l - 15], p = Gt[l - 2], d = vt(f, 7) ^ vt(f, 18) ^ f >>> 3, g = vt(p, 17) ^ vt(p, 19) ^ p >>> 10;
      Gt[l] = g + Gt[l - 7] + d + Gt[l - 16] | 0;
    }
    let { A: r, B: s, C: n, D: o, E: a, F: c, G: u, H: h } = this;
    for (let l = 0; l < 64; l++) {
      const f = vt(a, 6) ^ vt(a, 11) ^ vt(a, 25), p = h + f + Lv(a, c, u) + qv[l] + Gt[l] | 0, d = (vt(r, 2) ^ vt(r, 13) ^ vt(r, 22)) + Mv(r, s, n) | 0;
      h = u, u = c, c = a, a = o + p | 0, o = n, n = s, s = r, r = p + d | 0;
    }
    r = r + this.A | 0, s = s + this.B | 0, n = n + this.C | 0, o = o + this.D | 0, a = a + this.E | 0, c = c + this.F | 0, u = u + this.G | 0, h = h + this.H | 0, this.set(r, s, n, o, a, c, u, h);
  }
  roundClean() {
    ft(Gt);
  }
  destroy() {
    this.set(0, 0, 0, 0, 0, 0, 0, 0), ft(this.buffer);
  }
};
const cf = Zl(["0x428a2f98d728ae22", "0x7137449123ef65cd", "0xb5c0fbcfec4d3b2f", "0xe9b5dba58189dbbc", "0x3956c25bf348b538", "0x59f111f1b605d019", "0x923f82a4af194f9b", "0xab1c5ed5da6d8118", "0xd807aa98a3030242", "0x12835b0145706fbe", "0x243185be4ee4b28c", "0x550c7dc3d5ffb4e2", "0x72be5d74f27b896f", "0x80deb1fe3b1696b1", "0x9bdc06a725c71235", "0xc19bf174cf692694", "0xe49b69c19ef14ad2", "0xefbe4786384f25e3", "0x0fc19dc68b8cd5b5", "0x240ca1cc77ac9c65", "0x2de92c6f592b0275", "0x4a7484aa6ea6e483", "0x5cb0a9dcbd41fbd4", "0x76f988da831153b5", "0x983e5152ee66dfab", "0xa831c66d2db43210", "0xb00327c898fb213f", "0xbf597fc7beef0ee4", "0xc6e00bf33da88fc2", "0xd5a79147930aa725", "0x06ca6351e003826f", "0x142929670a0e6e70", "0x27b70a8546d22ffc", "0x2e1b21385c26c926", "0x4d2c6dfc5ac42aed", "0x53380d139d95b3df", "0x650a73548baf63de", "0x766a0abb3c77b2a8", "0x81c2c92e47edaee6", "0x92722c851482353b", "0xa2bfe8a14cf10364", "0xa81a664bbc423001", "0xc24b8b70d0f89791", "0xc76c51a30654be30", "0xd192e819d6ef5218", "0xd69906245565a910", "0xf40e35855771202a", "0x106aa07032bbd1b8", "0x19a4c116b8d2d0c8", "0x1e376c085141ab53", "0x2748774cdf8eeb99", "0x34b0bcb5e19b48a8", "0x391c0cb3c5c95a63", "0x4ed8aa4ae3418acb", "0x5b9cca4f7763e373", "0x682e6ff3d6b2b8a3", "0x748f82ee5defb2fc", "0x78a5636f43172f60", "0x84c87814a1f0ab72", "0x8cc702081a6439ec", "0x90befffa23631e28", "0xa4506cebde82bde9", "0xbef9a3f7b2c67915", "0xc67178f2e372532b", "0xca273eceea26619c", "0xd186b8c721c0c207", "0xeada7dd6cde0eb1e", "0xf57d4f7fee6ed178", "0x06f067aa72176fba", "0x0a637dc5a2c898a6", "0x113f9804bef90dae", "0x1b710b35131c471b", "0x28db77f523047d84", "0x32caab7b40c72493", "0x3c9ebe0a15c9bebc", "0x431d67c49c100d4c", "0x4cc5d4becb3e42b6", "0x597f299cfc657e2a", "0x5fcb6fab3ad6faec", "0x6c44198c4a475817"].map((t) => BigInt(t))), zv = cf[0], Kv = cf[1], Yt = new Uint32Array(80), Jt = new Uint32Array(80);
let ya = class extends af {
  constructor(e = 64) {
    super(128, e, 16, !1), this.Ah = Be[0] | 0, this.Al = Be[1] | 0, this.Bh = Be[2] | 0, this.Bl = Be[3] | 0, this.Ch = Be[4] | 0, this.Cl = Be[5] | 0, this.Dh = Be[6] | 0, this.Dl = Be[7] | 0, this.Eh = Be[8] | 0, this.El = Be[9] | 0, this.Fh = Be[10] | 0, this.Fl = Be[11] | 0, this.Gh = Be[12] | 0, this.Gl = Be[13] | 0, this.Hh = Be[14] | 0, this.Hl = Be[15] | 0;
  }
  get() {
    const { Ah: e, Al: i, Bh: r, Bl: s, Ch: n, Cl: o, Dh: a, Dl: c, Eh: u, El: h, Fh: l, Fl: f, Gh: p, Gl: d, Hh: g, Hl: y } = this;
    return [e, i, r, s, n, o, a, c, u, h, l, f, p, d, g, y];
  }
  set(e, i, r, s, n, o, a, c, u, h, l, f, p, d, g, y) {
    this.Ah = e | 0, this.Al = i | 0, this.Bh = r | 0, this.Bl = s | 0, this.Ch = n | 0, this.Cl = o | 0, this.Dh = a | 0, this.Dl = c | 0, this.Eh = u | 0, this.El = h | 0, this.Fh = l | 0, this.Fl = f | 0, this.Gh = p | 0, this.Gl = d | 0, this.Hh = g | 0, this.Hl = y | 0;
  }
  process(e, i) {
    for (let m = 0; m < 16; m++, i += 4)
      Yt[m] = e.getUint32(i), Jt[m] = e.getUint32(i += 4);
    for (let m = 16; m < 80; m++) {
      const D = Yt[m - 15] | 0, I = Jt[m - 15] | 0, R = ti(D, I, 1) ^ ti(D, I, 8) ^ qc(D, I, 7), B = ii(D, I, 1) ^ ii(D, I, 8) ^ jc(D, I, 7), C = Yt[m - 2] | 0, w = Jt[m - 2] | 0, O = ti(C, w, 19) ^ Ir(C, w, 61) ^ qc(C, w, 6), _ = ii(C, w, 19) ^ Sr(C, w, 61) ^ jc(C, w, 6), $ = bv(B, _, Jt[m - 7], Jt[m - 16]), P = vv($, R, O, Yt[m - 7], Yt[m - 16]);
      Yt[m] = P | 0, Jt[m] = $ | 0;
    }
    let { Ah: r, Al: s, Bh: n, Bl: o, Ch: a, Cl: c, Dh: u, Dl: h, Eh: l, El: f, Fh: p, Fl: d, Gh: g, Gl: y, Hh: E, Hl: v } = this;
    for (let m = 0; m < 80; m++) {
      const D = ti(l, f, 14) ^ ti(l, f, 18) ^ Ir(l, f, 41), I = ii(l, f, 14) ^ ii(l, f, 18) ^ Sr(l, f, 41), R = l & p ^ ~l & g, B = f & d ^ ~f & y, C = Ev(v, I, B, Kv[m], Jt[m]), w = _v(C, E, D, R, zv[m], Yt[m]), O = C | 0, _ = ti(r, s, 28) ^ Ir(r, s, 34) ^ Ir(r, s, 39), $ = ii(r, s, 28) ^ Sr(r, s, 34) ^ Sr(r, s, 39), P = r & n ^ r & a ^ n & a, k = s & o ^ s & c ^ o & c;
      E = g | 0, v = y | 0, g = p | 0, y = d | 0, p = l | 0, d = f | 0, { h: l, l: f } = yt(u | 0, h | 0, w | 0, O | 0), u = a | 0, h = c | 0, a = n | 0, c = o | 0, n = r | 0, o = s | 0;
      const x = ha(O, $, k);
      r = la(x, w, _, P), s = x | 0;
    }
    ({ h: r, l: s } = yt(this.Ah | 0, this.Al | 0, r | 0, s | 0)), { h: n, l: o } = yt(this.Bh | 0, this.Bl | 0, n | 0, o | 0), { h: a, l: c } = yt(this.Ch | 0, this.Cl | 0, a | 0, c | 0), { h: u, l: h } = yt(this.Dh | 0, this.Dl | 0, u | 0, h | 0), { h: l, l: f } = yt(this.Eh | 0, this.El | 0, l | 0, f | 0), { h: p, l: d } = yt(this.Fh | 0, this.Fl | 0, p | 0, d | 0), { h: g, l: y } = yt(this.Gh | 0, this.Gl | 0, g | 0, y | 0), { h: E, l: v } = yt(this.Hh | 0, this.Hl | 0, E | 0, v | 0), this.set(r, s, n, o, a, c, u, h, l, f, p, d, g, y, E, v);
  }
  roundClean() {
    ft(Yt, Jt);
  }
  destroy() {
    ft(this.buffer), this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  }
}, Vv = class extends ya {
  constructor() {
    super(48), this.Ah = Ue[0] | 0, this.Al = Ue[1] | 0, this.Bh = Ue[2] | 0, this.Bl = Ue[3] | 0, this.Ch = Ue[4] | 0, this.Cl = Ue[5] | 0, this.Dh = Ue[6] | 0, this.Dl = Ue[7] | 0, this.Eh = Ue[8] | 0, this.El = Ue[9] | 0, this.Fh = Ue[10] | 0, this.Fl = Ue[11] | 0, this.Gh = Ue[12] | 0, this.Gl = Ue[13] | 0, this.Hh = Ue[14] | 0, this.Hl = Ue[15] | 0;
  }
};
const Ne = Uint32Array.from([573645204, 4230739756, 2673172387, 3360449730, 596883563, 1867755857, 2520282905, 1497426621, 2519219938, 2827943907, 3193839141, 1401305490, 721525244, 746961066, 246885852, 2177182882]);
class Hv extends ya {
  constructor() {
    super(32), this.Ah = Ne[0] | 0, this.Al = Ne[1] | 0, this.Bh = Ne[2] | 0, this.Bl = Ne[3] | 0, this.Ch = Ne[4] | 0, this.Cl = Ne[5] | 0, this.Dh = Ne[6] | 0, this.Dl = Ne[7] | 0, this.Eh = Ne[8] | 0, this.El = Ne[9] | 0, this.Fh = Ne[10] | 0, this.Fl = Ne[11] | 0, this.Gh = Ne[12] | 0, this.Gl = Ne[13] | 0, this.Hh = Ne[14] | 0, this.Hl = Ne[15] | 0;
  }
}
const sn = es(() => new jv()), Wv = es(() => new ya()), Gv = es(() => new Vv()), Yv = es(() => new Hv()), Jv = Uint8Array.from([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3, 11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4, 7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8, 9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13, 2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9, 12, 5, 1, 15, 14, 13, 4, 10, 0, 7, 6, 3, 9, 2, 8, 11, 13, 11, 7, 14, 12, 1, 3, 9, 5, 0, 15, 4, 8, 6, 2, 10, 6, 15, 14, 9, 11, 3, 0, 8, 12, 2, 13, 7, 1, 4, 10, 5, 10, 2, 8, 4, 7, 6, 1, 5, 15, 11, 9, 14, 3, 12, 13, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3, 11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4, 7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8, 9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13, 2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9]), we = Uint32Array.from([4089235720, 1779033703, 2227873595, 3144134277, 4271175723, 1013904242, 1595750129, 2773480762, 2917565137, 1359893119, 725511199, 2600822924, 4215389547, 528734635, 327033209, 1541459225]), q = new Uint32Array(32);
function Zt(t, e, i, r, s, n) {
  const o = s[n], a = s[n + 1];
  let c = q[2 * t], u = q[2 * t + 1], h = q[2 * e], l = q[2 * e + 1], f = q[2 * i], p = q[2 * i + 1], d = q[2 * r], g = q[2 * r + 1], y = ha(c, h, o);
  u = la(y, u, l, a), c = y | 0, { Dh: g, Dl: d } = { Dh: g ^ u, Dl: d ^ c }, { Dh: g, Dl: d } = { Dh: dv(g, d), Dl: pv(g) }, { h: p, l: f } = yt(p, f, g, d), { Bh: l, Bl: h } = { Bh: l ^ p, Bl: h ^ f }, { Bh: l, Bl: h } = { Bh: ti(l, h, 24), Bl: ii(l, h, 24) }, q[2 * t] = c, q[2 * t + 1] = u, q[2 * e] = h, q[2 * e + 1] = l, q[2 * i] = f, q[2 * i + 1] = p, q[2 * r] = d, q[2 * r + 1] = g;
}
function Qt(t, e, i, r, s, n) {
  const o = s[n], a = s[n + 1];
  let c = q[2 * t], u = q[2 * t + 1], h = q[2 * e], l = q[2 * e + 1], f = q[2 * i], p = q[2 * i + 1], d = q[2 * r], g = q[2 * r + 1], y = ha(c, h, o);
  u = la(y, u, l, a), c = y | 0, { Dh: g, Dl: d } = { Dh: g ^ u, Dl: d ^ c }, { Dh: g, Dl: d } = { Dh: ti(g, d, 16), Dl: ii(g, d, 16) }, { h: p, l: f } = yt(p, f, g, d), { Bh: l, Bl: h } = { Bh: l ^ p, Bl: h ^ f }, { Bh: l, Bl: h } = { Bh: Ir(l, h, 63), Bl: Sr(l, h, 63) }, q[2 * t] = c, q[2 * t + 1] = u, q[2 * e] = h, q[2 * e + 1] = l, q[2 * i] = f, q[2 * i + 1] = p, q[2 * r] = d, q[2 * r + 1] = g;
}
function Zv(t, e = {}, i, r, s) {
  if (qt(i), t < 0 || t > i)
    throw new Error("outputLen bigger than keyLen");
  const { key: n, salt: o, personalization: a } = e;
  if (n !== void 0 && (n.length < 1 || n.length > i))
    throw new Error("key length must be undefined or 1.." + i);
  if (o !== void 0 && o.length !== r)
    throw new Error("salt must be undefined or " + r);
  if (a !== void 0 && a.length !== s)
    throw new Error("personalization must be undefined or " + s);
}
class Qv extends rn {
  constructor(e, i) {
    super(), this.finished = !1, this.destroyed = !1, this.length = 0, this.pos = 0, qt(e), qt(i), this.blockLen = e, this.outputLen = i, this.buffer = new Uint8Array(e), this.buffer32 = qr(this.buffer);
  }
  update(e) {
    ai(this), e = mt(e), lt(e);
    const { blockLen: i, buffer: r, buffer32: s } = this, n = e.length, o = e.byteOffset, a = e.buffer;
    for (let c = 0; c < n; ) {
      this.pos === i && (ri(s), this.compress(s, 0, !1), ri(s), this.pos = 0);
      const u = Math.min(i - this.pos, n - c), h = o + c;
      if (u === i && !(h % 4) && c + u < n) {
        const l = new Uint32Array(a, h, Math.floor((n - c) / 4));
        ri(l);
        for (let f = 0; c + i < n; f += s.length, c += i)
          this.length += i, this.compress(l, f, !1);
        ri(l);
        continue;
      }
      r.set(e.subarray(c, c + u), this.pos), this.pos += u, this.length += u, c += u;
    }
    return this;
  }
  digestInto(e) {
    ai(this), pa(e, this);
    const { pos: i, buffer32: r } = this;
    this.finished = !0, ft(this.buffer.subarray(i)), ri(r), this.compress(r, 0, !0), ri(r);
    const s = qr(e);
    this.get().forEach((n, o) => s[o] = Bt(n));
  }
  digest() {
    const { buffer: e, outputLen: i } = this;
    this.digestInto(e);
    const r = e.slice(0, i);
    return this.destroy(), r;
  }
  _cloneInto(e) {
    const { buffer: i, length: r, finished: s, destroyed: n, outputLen: o, pos: a } = this;
    return e || (e = new this.constructor({ dkLen: o })), e.set(...this.get()), e.buffer.set(i), e.destroyed = n, e.finished = s, e.length = r, e.pos = a, e.outputLen = o, e;
  }
  clone() {
    return this._cloneInto();
  }
}
class Xv extends Qv {
  constructor(e = {}) {
    const i = e.dkLen === void 0 ? 64 : e.dkLen;
    super(128, i), this.v0l = we[0] | 0, this.v0h = we[1] | 0, this.v1l = we[2] | 0, this.v1h = we[3] | 0, this.v2l = we[4] | 0, this.v2h = we[5] | 0, this.v3l = we[6] | 0, this.v3h = we[7] | 0, this.v4l = we[8] | 0, this.v4h = we[9] | 0, this.v5l = we[10] | 0, this.v5h = we[11] | 0, this.v6l = we[12] | 0, this.v6h = we[13] | 0, this.v7l = we[14] | 0, this.v7h = we[15] | 0, Zv(i, e, 64, 16, 16);
    let { key: r, personalization: s, salt: n } = e, o = 0;
    if (r !== void 0 && (r = mt(r), o = r.length), this.v0l ^= this.outputLen | o << 8 | 65536 | 1 << 24, n !== void 0) {
      n = mt(n);
      const a = qr(n);
      this.v4l ^= Bt(a[0]), this.v4h ^= Bt(a[1]), this.v5l ^= Bt(a[2]), this.v5h ^= Bt(a[3]);
    }
    if (s !== void 0) {
      s = mt(s);
      const a = qr(s);
      this.v6l ^= Bt(a[0]), this.v6h ^= Bt(a[1]), this.v7l ^= Bt(a[2]), this.v7h ^= Bt(a[3]);
    }
    if (r !== void 0) {
      const a = new Uint8Array(this.blockLen);
      a.set(r), this.update(a);
    }
  }
  get() {
    let { v0l: e, v0h: i, v1l: r, v1h: s, v2l: n, v2h: o, v3l: a, v3h: c, v4l: u, v4h: h, v5l: l, v5h: f, v6l: p, v6h: d, v7l: g, v7h: y } = this;
    return [e, i, r, s, n, o, a, c, u, h, l, f, p, d, g, y];
  }
  set(e, i, r, s, n, o, a, c, u, h, l, f, p, d, g, y) {
    this.v0l = e | 0, this.v0h = i | 0, this.v1l = r | 0, this.v1h = s | 0, this.v2l = n | 0, this.v2h = o | 0, this.v3l = a | 0, this.v3h = c | 0, this.v4l = u | 0, this.v4h = h | 0, this.v5l = l | 0, this.v5h = f | 0, this.v6l = p | 0, this.v6h = d | 0, this.v7l = g | 0, this.v7h = y | 0;
  }
  compress(e, i, r) {
    this.get().forEach((c, u) => q[u] = c), q.set(we, 16);
    let { h: s, l: n } = Jl(BigInt(this.length));
    q[24] = we[8] ^ n, q[25] = we[9] ^ s, r && (q[28] = ~q[28], q[29] = ~q[29]);
    let o = 0;
    const a = Jv;
    for (let c = 0; c < 12; c++)
      Zt(0, 4, 8, 12, e, i + 2 * a[o++]), Qt(0, 4, 8, 12, e, i + 2 * a[o++]), Zt(1, 5, 9, 13, e, i + 2 * a[o++]), Qt(1, 5, 9, 13, e, i + 2 * a[o++]), Zt(2, 6, 10, 14, e, i + 2 * a[o++]), Qt(2, 6, 10, 14, e, i + 2 * a[o++]), Zt(3, 7, 11, 15, e, i + 2 * a[o++]), Qt(3, 7, 11, 15, e, i + 2 * a[o++]), Zt(0, 5, 10, 15, e, i + 2 * a[o++]), Qt(0, 5, 10, 15, e, i + 2 * a[o++]), Zt(1, 6, 11, 12, e, i + 2 * a[o++]), Qt(1, 6, 11, 12, e, i + 2 * a[o++]), Zt(2, 7, 8, 13, e, i + 2 * a[o++]), Qt(2, 7, 8, 13, e, i + 2 * a[o++]), Zt(3, 4, 9, 14, e, i + 2 * a[o++]), Qt(3, 4, 9, 14, e, i + 2 * a[o++]);
    this.v0l ^= q[0] ^ q[16], this.v0h ^= q[1] ^ q[17], this.v1l ^= q[2] ^ q[18], this.v1h ^= q[3] ^ q[19], this.v2l ^= q[4] ^ q[20], this.v2h ^= q[5] ^ q[21], this.v3l ^= q[6] ^ q[22], this.v3h ^= q[7] ^ q[23], this.v4l ^= q[8] ^ q[24], this.v4h ^= q[9] ^ q[25], this.v5l ^= q[10] ^ q[26], this.v5h ^= q[11] ^ q[27], this.v6l ^= q[12] ^ q[28], this.v6h ^= q[13] ^ q[29], this.v7l ^= q[14] ^ q[30], this.v7h ^= q[15] ^ q[31], ft(q);
  }
  destroy() {
    this.destroyed = !0, ft(this.buffer32), this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  }
}
const e2 = Dv((t) => new Xv(t)), t2 = "https://rpc.walletconnect.org/v1";
function uf(t) {
  const e = `Ethereum Signed Message:
${t.length}`, i = new TextEncoder().encode(e + t);
  return "0x" + Buffer.from(Nv(i)).toString("hex");
}
async function i2(t, e, i, r, s, n) {
  switch (i.t) {
    case "eip191":
      return await r2(t, e, i.s);
    case "eip1271":
      return await s2(t, e, i.s, r, s, n);
    default:
      throw new Error(`verifySignature failed: Attempted to verify CacaoSignature with unknown type: ${i.t}`);
  }
}
async function r2(t, e, i) {
  return (await Rw({ hash: uf(e), signature: i })).toLowerCase() === t.toLowerCase();
}
async function s2(t, e, i, r, s, n) {
  const o = As(r);
  if (!o.namespace || !o.reference)
    throw new Error(`isValidEip1271Signature failed: chainId must be in CAIP-2 format, received: ${r}`);
  try {
    const a = "0x1626ba7e", c = "0000000000000000000000000000000000000000000000000000000000000040", u = i.substring(2), h = (u.length / 2).toString(16).padStart(64, "0"), l = (e.startsWith("0x") ? e : uf(e)).substring(2), f = a + l + c + h + u, p = await fetch(`${n || t2}/?chainId=${r}&projectId=${s}`, { headers: { "Content-Type": "application/json" }, method: "POST", body: JSON.stringify({ id: n2(), jsonrpc: "2.0", method: "eth_call", params: [{ to: t, data: f }, "latest"] }) }), { result: d } = await p.json();
    return d ? d.slice(0, a.length).toLowerCase() === a.toLowerCase() : !1;
  } catch (a) {
    return console.error("isValidEip1271Signature: ", a), !1;
  }
}
function n2() {
  return Date.now() + Math.floor(Math.random() * 1e3);
}
function o2(t) {
  const e = atob(t), i = new Uint8Array(e.length);
  for (let o = 0; o < e.length; o++)
    i[o] = e.charCodeAt(o);
  const r = i[0];
  if (r === 0)
    throw new Error("No signatures found");
  const s = 1 + r * 64;
  if (i.length < s)
    throw new Error("Transaction data too short for claimed signature count");
  if (i.length < 100)
    throw new Error("Transaction too short");
  const n = Buffer.from(t, "base64").slice(1, 65);
  return Zr.encode(n);
}
function a2(t) {
  const e = new Uint8Array(Buffer.from(t, "base64")), i = Array.from("TransactionData::").map((n) => n.charCodeAt(0)), r = new Uint8Array(i.length + e.length);
  r.set(i), r.set(e, i.length);
  const s = e2(r, { dkLen: 32 });
  return Zr.encode(s);
}
function Hc(t) {
  const e = new Uint8Array(sn(c2(t)));
  return Zr.encode(e);
}
function c2(t) {
  if (t instanceof Uint8Array)
    return t;
  if (Array.isArray(t))
    return new Uint8Array(t);
  if (typeof t == "object" && t != null && t.data)
    return new Uint8Array(Object.values(t.data));
  if (typeof t == "object" && t)
    return new Uint8Array(Object.values(t));
  throw new Error("getNearUint8ArrayFromBytes: Unexpected result type from bytes array");
}
function Wc(t) {
  const e = Buffer.from(t, "base64"), i = wm(e).txn;
  if (!i)
    throw new Error("Invalid signed transaction: missing 'txn' field");
  const r = cm(i), s = Buffer.from("TX"), n = Buffer.concat([s, Buffer.from(r)]), o = Yv(n);
  return Sm.encode(o).replace(/=+$/, "");
}
function kn(t) {
  const e = [];
  let i = BigInt(t);
  for (; i >= BigInt(128); )
    e.push(Number(i & BigInt(127) | BigInt(128))), i >>= BigInt(7);
  return e.push(Number(i)), Buffer.from(e);
}
function u2(t) {
  const e = Buffer.from(t.signed.bodyBytes, "base64"), i = Buffer.from(t.signed.authInfoBytes, "base64"), r = Buffer.from(t.signature.signature, "base64"), s = [];
  s.push(Buffer.from([10])), s.push(kn(e.length)), s.push(e), s.push(Buffer.from([18])), s.push(kn(i.length)), s.push(i), s.push(Buffer.from([26])), s.push(kn(r.length)), s.push(r);
  const n = Buffer.concat(s), o = sn(n);
  return Buffer.from(o).toString("hex").toUpperCase();
}
var h2 = Object.defineProperty, l2 = Object.defineProperties, f2 = Object.getOwnPropertyDescriptors, Gc = Object.getOwnPropertySymbols, d2 = Object.prototype.hasOwnProperty, p2 = Object.prototype.propertyIsEnumerable, Yc = (t, e, i) => e in t ? h2(t, e, { enumerable: !0, configurable: !0, writable: !0, value: i }) : t[e] = i, g2 = (t, e) => {
  for (var i in e || (e = {}))
    d2.call(e, i) && Yc(t, i, e[i]);
  if (Gc)
    for (var i of Gc(e))
      p2.call(e, i) && Yc(t, i, e[i]);
  return t;
}, y2 = (t, e) => l2(t, f2(e));
const w2 = "did:pkh:", wa = (t) => t?.split(":"), m2 = (t) => {
  const e = t && wa(t);
  if (e)
    return t.includes(w2) ? e[3] : e[1];
}, Eo = (t) => {
  const e = t && wa(t);
  if (e)
    return e[2] + ":" + e[3];
}, js = (t) => {
  const e = t && wa(t);
  if (e)
    return e.pop();
};
async function Jc(t) {
  const { cacao: e, projectId: i } = t, { s: r, p: s } = e, n = hf(s, s.iss), o = js(s.iss);
  return await i2(o, n, r, Eo(s.iss), i);
}
const hf = (t, e) => {
  const i = `${t.domain} wants you to sign in with your Ethereum account:`, r = js(e);
  if (!t.aud && !t.uri)
    throw new Error("Either `aud` or `uri` is required to construct the message");
  let s = t.statement || void 0;
  const n = `URI: ${t.aud || t.uri}`, o = `Version: ${t.version}`, a = `Chain ID: ${m2(e)}`, c = `Nonce: ${t.nonce}`, u = `Issued At: ${t.iat}`, h = t.exp ? `Expiration Time: ${t.exp}` : void 0, l = t.nbf ? `Not Before: ${t.nbf}` : void 0, f = t.requestId ? `Request ID: ${t.requestId}` : void 0, p = t.resources ? `Resources:${t.resources.map((g) => `
- ${g}`).join("")}` : void 0, d = $s(t.resources);
  if (d) {
    const g = zr(d);
    s = A2(s, g);
  }
  return [i, r, "", s, "", n, o, a, c, u, h, l, f, p].filter((g) => g != null).join(`
`);
};
function b2(t) {
  return Buffer.from(JSON.stringify(t)).toString("base64");
}
function v2(t) {
  return JSON.parse(Buffer.from(t, "base64").toString("utf-8"));
}
function Ai(t) {
  if (!t)
    throw new Error("No recap provided, value is undefined");
  if (!t.att)
    throw new Error("No `att` property found");
  const e = Object.keys(t.att);
  if (!(e != null && e.length))
    throw new Error("No resources found in `att` property");
  e.forEach((i) => {
    const r = t.att[i];
    if (Array.isArray(r))
      throw new Error(`Resource must be an object: ${i}`);
    if (typeof r != "object")
      throw new Error(`Resource must be an object: ${i}`);
    if (!Object.keys(r).length)
      throw new Error(`Resource object is empty: ${i}`);
    Object.keys(r).forEach((s) => {
      const n = r[s];
      if (!Array.isArray(n))
        throw new Error(`Ability limits ${s} must be an array of objects, found: ${n}`);
      if (!n.length)
        throw new Error(`Value of ${s} is empty array, must be an array with objects`);
      n.forEach((o) => {
        if (typeof o != "object")
          throw new Error(`Ability limits (${s}) must be an array of objects, found: ${o}`);
      });
    });
  });
}
function E2(t, e, i, r = {}) {
  return i?.sort((s, n) => s.localeCompare(n)), { att: { [t]: _2(e, i, r) } };
}
function _2(t, e, i = {}) {
  e = e?.sort((s, n) => s.localeCompare(n));
  const r = e.map((s) => ({ [`${t}/${s}`]: [i] }));
  return Object.assign({}, ...r);
}
function lf(t) {
  return Ai(t), `urn:recap:${b2(t).replace(/=/g, "")}`;
}
function zr(t) {
  const e = v2(t.replace("urn:recap:", ""));
  return Ai(e), e;
}
function x2(t, e, i) {
  const r = E2(t, e, i);
  return lf(r);
}
function I2(t) {
  return t && t.includes("urn:recap:");
}
function S2(t, e) {
  const i = zr(t), r = zr(e), s = D2(i, r);
  return lf(s);
}
function D2(t, e) {
  Ai(t), Ai(e);
  const i = Object.keys(t.att).concat(Object.keys(e.att)).sort((s, n) => s.localeCompare(n)), r = { att: {} };
  return i.forEach((s) => {
    var n, o;
    Object.keys(((n = t.att) == null ? void 0 : n[s]) || {}).concat(Object.keys(((o = e.att) == null ? void 0 : o[s]) || {})).sort((a, c) => a.localeCompare(c)).forEach((a) => {
      var c, u;
      r.att[s] = y2(g2({}, r.att[s]), { [a]: ((c = t.att[s]) == null ? void 0 : c[a]) || ((u = e.att[s]) == null ? void 0 : u[a]) });
    });
  }), r;
}
function A2(t = "", e) {
  Ai(e);
  const i = "I further authorize the stated URI to perform the following actions on my behalf: ";
  if (t.includes(i))
    return t;
  const r = [];
  let s = 0;
  Object.keys(e.att).forEach((a) => {
    const c = Object.keys(e.att[a]).map((l) => ({ ability: l.split("/")[0], action: l.split("/")[1] }));
    c.sort((l, f) => l.action.localeCompare(f.action));
    const u = {};
    c.forEach((l) => {
      u[l.ability] || (u[l.ability] = []), u[l.ability].push(l.action);
    });
    const h = Object.keys(u).map((l) => (s++, `(${s}) '${l}': '${u[l].join("', '")}' for '${a}'.`));
    r.push(h.join(", ").replace(".,", "."));
  });
  const n = r.join(" "), o = `${i}${n}`;
  return `${t ? t + " " : ""}${o}`;
}
function Zc(t) {
  var e;
  const i = zr(t);
  Ai(i);
  const r = (e = i.att) == null ? void 0 : e.eip155;
  return r ? Object.keys(r).map((s) => s.split("/")[1]) : [];
}
function Qc(t) {
  const e = zr(t);
  Ai(e);
  const i = [];
  return Object.values(e.att).forEach((r) => {
    Object.values(r).forEach((s) => {
      var n;
      (n = s?.[0]) != null && n.chains && i.push(s[0].chains);
    });
  }), [...new Set(i.flat())];
}
function $s(t) {
  if (!t)
    return;
  const e = t?.[t.length - 1];
  return I2(e) ? e : void 0;
}
/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */
function ff(t) {
  return t instanceof Uint8Array || ArrayBuffer.isView(t) && t.constructor.name === "Uint8Array";
}
function _o(t) {
  if (typeof t != "boolean")
    throw new Error(`boolean expected, not ${t}`);
}
function Ln(t) {
  if (!Number.isSafeInteger(t) || t < 0)
    throw new Error("positive integer expected, got " + t);
}
function Ge(t, ...e) {
  if (!ff(t))
    throw new Error("Uint8Array expected");
  if (e.length > 0 && !e.includes(t.length))
    throw new Error("Uint8Array expected of length " + e + ", got length=" + t.length);
}
function Xc(t, e = !0) {
  if (t.destroyed)
    throw new Error("Hash instance has been destroyed");
  if (e && t.finished)
    throw new Error("Hash#digest() has already been called");
}
function $2(t, e) {
  Ge(t);
  const i = e.outputLen;
  if (t.length < i)
    throw new Error("digestInto() expects output buffer of length at least " + i);
}
function oi(t) {
  return new Uint32Array(t.buffer, t.byteOffset, Math.floor(t.byteLength / 4));
}
function Ji(...t) {
  for (let e = 0; e < t.length; e++)
    t[e].fill(0);
}
function O2(t) {
  return new DataView(t.buffer, t.byteOffset, t.byteLength);
}
const T2 = new Uint8Array(new Uint32Array([287454020]).buffer)[0] === 68;
function C2(t) {
  if (typeof t != "string")
    throw new Error("string expected");
  return new Uint8Array(new TextEncoder().encode(t));
}
function xo(t) {
  if (typeof t == "string")
    t = C2(t);
  else if (ff(t))
    t = Io(t);
  else
    throw new Error("Uint8Array expected, got " + typeof t);
  return t;
}
function P2(t, e) {
  if (e == null || typeof e != "object")
    throw new Error("options must be defined");
  return Object.assign(t, e);
}
function R2(t, e) {
  if (t.length !== e.length)
    return !1;
  let i = 0;
  for (let r = 0; r < t.length; r++)
    i |= t[r] ^ e[r];
  return i === 0;
}
const F2 = (t, e) => {
  function i(r, ...s) {
    if (Ge(r), !T2)
      throw new Error("Non little-endian hardware is not yet supported");
    if (t.nonceLength !== void 0) {
      const u = s[0];
      if (!u)
        throw new Error("nonce / iv required");
      t.varSizeNonce ? Ge(u) : Ge(u, t.nonceLength);
    }
    const n = t.tagLength;
    n && s[1] !== void 0 && Ge(s[1]);
    const o = e(r, ...s), a = (u, h) => {
      if (h !== void 0) {
        if (u !== 2)
          throw new Error("cipher output not supported");
        Ge(h);
      }
    };
    let c = !1;
    return { encrypt(u, h) {
      if (c)
        throw new Error("cannot encrypt() twice with same key + nonce");
      return c = !0, Ge(u), a(o.encrypt.length, h), o.encrypt(u, h);
    }, decrypt(u, h) {
      if (Ge(u), n && u.length < n)
        throw new Error("invalid ciphertext length: smaller than tagLength=" + n);
      return a(o.decrypt.length, h), o.decrypt(u, h);
    } };
  }
  return Object.assign(i, t), i;
};
function eu(t, e, i = !0) {
  if (e === void 0)
    return new Uint8Array(t);
  if (e.length !== t)
    throw new Error("invalid output length, expected " + t + ", got: " + e.length);
  if (i && !B2(e))
    throw new Error("invalid output, must be aligned");
  return e;
}
function tu(t, e, i, r) {
  if (typeof t.setBigUint64 == "function")
    return t.setBigUint64(e, i, r);
  const s = BigInt(32), n = BigInt(4294967295), o = Number(i >> s & n), a = Number(i & n), c = r ? 4 : 0, u = r ? 0 : 4;
  t.setUint32(e + c, o, r), t.setUint32(e + u, a, r);
}
function U2(t, e, i) {
  _o(i);
  const r = new Uint8Array(16), s = O2(r);
  return tu(s, 0, BigInt(e), i), tu(s, 8, BigInt(t), i), r;
}
function B2(t) {
  return t.byteOffset % 4 === 0;
}
function Io(t) {
  return Uint8Array.from(t);
}
const df = (t) => Uint8Array.from(t.split("").map((e) => e.charCodeAt(0))), N2 = df("expand 16-byte k"), k2 = df("expand 32-byte k"), L2 = oi(N2), M2 = oi(k2);
function X(t, e) {
  return t << e | t >>> 32 - e;
}
function So(t) {
  return t.byteOffset % 4 === 0;
}
const ws = 64, q2 = 16, pf = 2 ** 32 - 1, iu = new Uint32Array();
function j2(t, e, i, r, s, n, o, a) {
  const c = s.length, u = new Uint8Array(ws), h = oi(u), l = So(s) && So(n), f = l ? oi(s) : iu, p = l ? oi(n) : iu;
  for (let d = 0; d < c; o++) {
    if (t(e, i, r, h, o, a), o >= pf)
      throw new Error("arx: counter overflow");
    const g = Math.min(ws, c - d);
    if (l && g === ws) {
      const y = d / 4;
      if (d % 4 !== 0)
        throw new Error("arx: invalid block position");
      for (let E = 0, v; E < q2; E++)
        v = y + E, p[v] = f[v] ^ h[E];
      d += ws;
      continue;
    }
    for (let y = 0, E; y < g; y++)
      E = d + y, n[E] = s[E] ^ u[y];
    d += g;
  }
}
function z2(t, e) {
  const { allowShortKeys: i, extendNonceFn: r, counterLength: s, counterRight: n, rounds: o } = P2({ allowShortKeys: !1, counterLength: 8, counterRight: !1, rounds: 20 }, e);
  if (typeof t != "function")
    throw new Error("core must be a function");
  return Ln(s), Ln(o), _o(n), _o(i), (a, c, u, h, l = 0) => {
    Ge(a), Ge(c), Ge(u);
    const f = u.length;
    if (h === void 0 && (h = new Uint8Array(f)), Ge(h), Ln(l), l < 0 || l >= pf)
      throw new Error("arx: counter overflow");
    if (h.length < f)
      throw new Error(`arx: output (${h.length}) is shorter than data (${f})`);
    const p = [];
    let d = a.length, g, y;
    if (d === 32)
      p.push(g = Io(a)), y = M2;
    else if (d === 16 && i)
      g = new Uint8Array(32), g.set(a), g.set(a, 16), y = L2, p.push(g);
    else
      throw new Error(`arx: invalid 32-byte key, got length=${d}`);
    So(c) || p.push(c = Io(c));
    const E = oi(g);
    if (r) {
      if (c.length !== 24)
        throw new Error("arx: extended nonce must be 24 bytes");
      r(y, E, oi(c.subarray(0, 16)), E), c = c.subarray(16);
    }
    const v = 16 - s;
    if (v !== c.length)
      throw new Error(`arx: nonce must be ${v} or 16 bytes`);
    if (v !== 12) {
      const D = new Uint8Array(12);
      D.set(c, n ? 0 : 12 - c.length), c = D, p.push(c);
    }
    const m = oi(c);
    return j2(t, y, E, m, u, h, l, o), Ji(...p), h;
  };
}
const De = (t, e) => t[e++] & 255 | (t[e++] & 255) << 8;
class K2 {
  constructor(e) {
    this.blockLen = 16, this.outputLen = 16, this.buffer = new Uint8Array(16), this.r = new Uint16Array(10), this.h = new Uint16Array(10), this.pad = new Uint16Array(8), this.pos = 0, this.finished = !1, e = xo(e), Ge(e, 32);
    const i = De(e, 0), r = De(e, 2), s = De(e, 4), n = De(e, 6), o = De(e, 8), a = De(e, 10), c = De(e, 12), u = De(e, 14);
    this.r[0] = i & 8191, this.r[1] = (i >>> 13 | r << 3) & 8191, this.r[2] = (r >>> 10 | s << 6) & 7939, this.r[3] = (s >>> 7 | n << 9) & 8191, this.r[4] = (n >>> 4 | o << 12) & 255, this.r[5] = o >>> 1 & 8190, this.r[6] = (o >>> 14 | a << 2) & 8191, this.r[7] = (a >>> 11 | c << 5) & 8065, this.r[8] = (c >>> 8 | u << 8) & 8191, this.r[9] = u >>> 5 & 127;
    for (let h = 0; h < 8; h++)
      this.pad[h] = De(e, 16 + 2 * h);
  }
  process(e, i, r = !1) {
    const s = r ? 0 : 2048, { h: n, r: o } = this, a = o[0], c = o[1], u = o[2], h = o[3], l = o[4], f = o[5], p = o[6], d = o[7], g = o[8], y = o[9], E = De(e, i + 0), v = De(e, i + 2), m = De(e, i + 4), D = De(e, i + 6), I = De(e, i + 8), R = De(e, i + 10), B = De(e, i + 12), C = De(e, i + 14);
    let w = n[0] + (E & 8191), O = n[1] + ((E >>> 13 | v << 3) & 8191), _ = n[2] + ((v >>> 10 | m << 6) & 8191), $ = n[3] + ((m >>> 7 | D << 9) & 8191), P = n[4] + ((D >>> 4 | I << 12) & 8191), k = n[5] + (I >>> 1 & 8191), x = n[6] + ((I >>> 14 | R << 2) & 8191), b = n[7] + ((R >>> 11 | B << 5) & 8191), S = n[8] + ((B >>> 8 | C << 8) & 8191), T = n[9] + (C >>> 5 | s), A = 0, U = A + w * a + O * (5 * y) + _ * (5 * g) + $ * (5 * d) + P * (5 * p);
    A = U >>> 13, U &= 8191, U += k * (5 * f) + x * (5 * l) + b * (5 * h) + S * (5 * u) + T * (5 * c), A += U >>> 13, U &= 8191;
    let N = A + w * c + O * a + _ * (5 * y) + $ * (5 * g) + P * (5 * d);
    A = N >>> 13, N &= 8191, N += k * (5 * p) + x * (5 * f) + b * (5 * l) + S * (5 * h) + T * (5 * u), A += N >>> 13, N &= 8191;
    let j = A + w * u + O * c + _ * a + $ * (5 * y) + P * (5 * g);
    A = j >>> 13, j &= 8191, j += k * (5 * d) + x * (5 * p) + b * (5 * f) + S * (5 * l) + T * (5 * h), A += j >>> 13, j &= 8191;
    let z = A + w * h + O * u + _ * c + $ * a + P * (5 * y);
    A = z >>> 13, z &= 8191, z += k * (5 * g) + x * (5 * d) + b * (5 * p) + S * (5 * f) + T * (5 * l), A += z >>> 13, z &= 8191;
    let K = A + w * l + O * h + _ * u + $ * c + P * a;
    A = K >>> 13, K &= 8191, K += k * (5 * y) + x * (5 * g) + b * (5 * d) + S * (5 * p) + T * (5 * f), A += K >>> 13, K &= 8191;
    let V = A + w * f + O * l + _ * h + $ * u + P * c;
    A = V >>> 13, V &= 8191, V += k * a + x * (5 * y) + b * (5 * g) + S * (5 * d) + T * (5 * p), A += V >>> 13, V &= 8191;
    let H = A + w * p + O * f + _ * l + $ * h + P * u;
    A = H >>> 13, H &= 8191, H += k * c + x * a + b * (5 * y) + S * (5 * g) + T * (5 * d), A += H >>> 13, H &= 8191;
    let re = A + w * d + O * p + _ * f + $ * l + P * h;
    A = re >>> 13, re &= 8191, re += k * u + x * c + b * a + S * (5 * y) + T * (5 * g), A += re >>> 13, re &= 8191;
    let ie = A + w * g + O * d + _ * p + $ * f + P * l;
    A = ie >>> 13, ie &= 8191, ie += k * h + x * u + b * c + S * a + T * (5 * y), A += ie >>> 13, ie &= 8191;
    let J = A + w * y + O * g + _ * d + $ * p + P * f;
    A = J >>> 13, J &= 8191, J += k * l + x * h + b * u + S * c + T * a, A += J >>> 13, J &= 8191, A = (A << 2) + A | 0, A = A + U | 0, U = A & 8191, A = A >>> 13, N += A, n[0] = U, n[1] = N, n[2] = j, n[3] = z, n[4] = K, n[5] = V, n[6] = H, n[7] = re, n[8] = ie, n[9] = J;
  }
  finalize() {
    const { h: e, pad: i } = this, r = new Uint16Array(10);
    let s = e[1] >>> 13;
    e[1] &= 8191;
    for (let a = 2; a < 10; a++)
      e[a] += s, s = e[a] >>> 13, e[a] &= 8191;
    e[0] += s * 5, s = e[0] >>> 13, e[0] &= 8191, e[1] += s, s = e[1] >>> 13, e[1] &= 8191, e[2] += s, r[0] = e[0] + 5, s = r[0] >>> 13, r[0] &= 8191;
    for (let a = 1; a < 10; a++)
      r[a] = e[a] + s, s = r[a] >>> 13, r[a] &= 8191;
    r[9] -= 8192;
    let n = (s ^ 1) - 1;
    for (let a = 0; a < 10; a++)
      r[a] &= n;
    n = ~n;
    for (let a = 0; a < 10; a++)
      e[a] = e[a] & n | r[a];
    e[0] = (e[0] | e[1] << 13) & 65535, e[1] = (e[1] >>> 3 | e[2] << 10) & 65535, e[2] = (e[2] >>> 6 | e[3] << 7) & 65535, e[3] = (e[3] >>> 9 | e[4] << 4) & 65535, e[4] = (e[4] >>> 12 | e[5] << 1 | e[6] << 14) & 65535, e[5] = (e[6] >>> 2 | e[7] << 11) & 65535, e[6] = (e[7] >>> 5 | e[8] << 8) & 65535, e[7] = (e[8] >>> 8 | e[9] << 5) & 65535;
    let o = e[0] + i[0];
    e[0] = o & 65535;
    for (let a = 1; a < 8; a++)
      o = (e[a] + i[a] | 0) + (o >>> 16) | 0, e[a] = o & 65535;
    Ji(r);
  }
  update(e) {
    Xc(this), e = xo(e), Ge(e);
    const { buffer: i, blockLen: r } = this, s = e.length;
    for (let n = 0; n < s; ) {
      const o = Math.min(r - this.pos, s - n);
      if (o === r) {
        for (; r <= s - n; n += r)
          this.process(e, n);
        continue;
      }
      i.set(e.subarray(n, n + o), this.pos), this.pos += o, n += o, this.pos === r && (this.process(i, 0, !1), this.pos = 0);
    }
    return this;
  }
  destroy() {
    Ji(this.h, this.r, this.buffer, this.pad);
  }
  digestInto(e) {
    Xc(this), $2(e, this), this.finished = !0;
    const { buffer: i, h: r } = this;
    let { pos: s } = this;
    if (s) {
      for (i[s++] = 1; s < 16; s++)
        i[s] = 0;
      this.process(i, 0, !0);
    }
    this.finalize();
    let n = 0;
    for (let o = 0; o < 8; o++)
      e[n++] = r[o] >>> 0, e[n++] = r[o] >>> 8;
    return e;
  }
  digest() {
    const { buffer: e, outputLen: i } = this;
    this.digestInto(e);
    const r = e.slice(0, i);
    return this.destroy(), r;
  }
}
function V2(t) {
  const e = (r, s) => t(s).update(xo(r)).digest(), i = t(new Uint8Array(32));
  return e.outputLen = i.outputLen, e.blockLen = i.blockLen, e.create = (r) => t(r), e;
}
const H2 = V2((t) => new K2(t));
function W2(t, e, i, r, s, n = 20) {
  let o = t[0], a = t[1], c = t[2], u = t[3], h = e[0], l = e[1], f = e[2], p = e[3], d = e[4], g = e[5], y = e[6], E = e[7], v = s, m = i[0], D = i[1], I = i[2], R = o, B = a, C = c, w = u, O = h, _ = l, $ = f, P = p, k = d, x = g, b = y, S = E, T = v, A = m, U = D, N = I;
  for (let z = 0; z < n; z += 2)
    R = R + O | 0, T = X(T ^ R, 16), k = k + T | 0, O = X(O ^ k, 12), R = R + O | 0, T = X(T ^ R, 8), k = k + T | 0, O = X(O ^ k, 7), B = B + _ | 0, A = X(A ^ B, 16), x = x + A | 0, _ = X(_ ^ x, 12), B = B + _ | 0, A = X(A ^ B, 8), x = x + A | 0, _ = X(_ ^ x, 7), C = C + $ | 0, U = X(U ^ C, 16), b = b + U | 0, $ = X($ ^ b, 12), C = C + $ | 0, U = X(U ^ C, 8), b = b + U | 0, $ = X($ ^ b, 7), w = w + P | 0, N = X(N ^ w, 16), S = S + N | 0, P = X(P ^ S, 12), w = w + P | 0, N = X(N ^ w, 8), S = S + N | 0, P = X(P ^ S, 7), R = R + _ | 0, N = X(N ^ R, 16), b = b + N | 0, _ = X(_ ^ b, 12), R = R + _ | 0, N = X(N ^ R, 8), b = b + N | 0, _ = X(_ ^ b, 7), B = B + $ | 0, T = X(T ^ B, 16), S = S + T | 0, $ = X($ ^ S, 12), B = B + $ | 0, T = X(T ^ B, 8), S = S + T | 0, $ = X($ ^ S, 7), C = C + P | 0, A = X(A ^ C, 16), k = k + A | 0, P = X(P ^ k, 12), C = C + P | 0, A = X(A ^ C, 8), k = k + A | 0, P = X(P ^ k, 7), w = w + O | 0, U = X(U ^ w, 16), x = x + U | 0, O = X(O ^ x, 12), w = w + O | 0, U = X(U ^ w, 8), x = x + U | 0, O = X(O ^ x, 7);
  let j = 0;
  r[j++] = o + R | 0, r[j++] = a + B | 0, r[j++] = c + C | 0, r[j++] = u + w | 0, r[j++] = h + O | 0, r[j++] = l + _ | 0, r[j++] = f + $ | 0, r[j++] = p + P | 0, r[j++] = d + k | 0, r[j++] = g + x | 0, r[j++] = y + b | 0, r[j++] = E + S | 0, r[j++] = v + T | 0, r[j++] = m + A | 0, r[j++] = D + U | 0, r[j++] = I + N | 0;
}
const G2 = z2(W2, { counterRight: !1, counterLength: 4, allowShortKeys: !1 }), Y2 = new Uint8Array(16), ru = (t, e) => {
  t.update(e);
  const i = e.length % 16;
  i && t.update(Y2.subarray(i));
}, J2 = new Uint8Array(32);
function su(t, e, i, r, s) {
  const n = t(e, i, J2), o = H2.create(n);
  s && ru(o, s), ru(o, r);
  const a = U2(r.length, s ? s.length : 0, !0);
  o.update(a);
  const c = o.digest();
  return Ji(n, a), c;
}
const Z2 = (t) => (e, i, r) => ({ encrypt(s, n) {
  const o = s.length;
  n = eu(o + 16, n, !1), n.set(s);
  const a = n.subarray(0, -16);
  t(e, i, a, a, 1);
  const c = su(t, e, i, a, r);
  return n.set(c, o), Ji(c), n;
}, decrypt(s, n) {
  n = eu(s.length - 16, n, !1);
  const o = s.subarray(0, -16), a = s.subarray(-16), c = su(t, e, i, o, r);
  if (!R2(a, c))
    throw new Error("invalid tag");
  return n.set(s.subarray(0, -16)), t(e, i, n, n, 1), Ji(c), n;
} }), gf = F2({ blockSize: 64, nonceLength: 12, tagLength: 16 }, Z2(G2));
let yf = class extends rn {
  constructor(e, i) {
    super(), this.finished = !1, this.destroyed = !1, da(e);
    const r = mt(i);
    if (this.iHash = e.create(), typeof this.iHash.update != "function")
      throw new Error("Expected instance of class which extends utils.Hash");
    this.blockLen = this.iHash.blockLen, this.outputLen = this.iHash.outputLen;
    const s = this.blockLen, n = new Uint8Array(s);
    n.set(r.length > s ? e.create().update(r).digest() : r);
    for (let o = 0; o < n.length; o++)
      n[o] ^= 54;
    this.iHash.update(n), this.oHash = e.create();
    for (let o = 0; o < n.length; o++)
      n[o] ^= 106;
    this.oHash.update(n), ft(n);
  }
  update(e) {
    return ai(this), this.iHash.update(e), this;
  }
  digestInto(e) {
    ai(this), lt(e, this.outputLen), this.finished = !0, this.iHash.digestInto(e), this.oHash.update(e), this.oHash.digestInto(e), this.destroy();
  }
  digest() {
    const e = new Uint8Array(this.oHash.outputLen);
    return this.digestInto(e), e;
  }
  _cloneInto(e) {
    e || (e = Object.create(Object.getPrototypeOf(this), {}));
    const { oHash: i, iHash: r, finished: s, destroyed: n, blockLen: o, outputLen: a } = this;
    return e = e, e.finished = s, e.destroyed = n, e.blockLen = o, e.outputLen = a, e.oHash = i._cloneInto(e.oHash), e.iHash = r._cloneInto(e.iHash), e;
  }
  clone() {
    return this._cloneInto();
  }
  destroy() {
    this.destroyed = !0, this.oHash.destroy(), this.iHash.destroy();
  }
};
const nn = (t, e, i) => new yf(t, e).update(i).digest();
nn.create = (t, e) => new yf(t, e);
function Q2(t, e, i) {
  return da(t), i === void 0 && (i = new Uint8Array(t.outputLen)), nn(t, mt(i), mt(e));
}
const Mn = Uint8Array.from([0]), nu = Uint8Array.of();
function X2(t, e, i, r = 32) {
  da(t), qt(r);
  const s = t.outputLen;
  if (r > 255 * s)
    throw new Error("Length should be <= 255*HashLen");
  const n = Math.ceil(r / s);
  i === void 0 && (i = nu);
  const o = new Uint8Array(n * s), a = nn.create(t, e), c = a._cloneInto(), u = new Uint8Array(a.outputLen);
  for (let h = 0; h < n; h++)
    Mn[0] = h + 1, c.update(h === 0 ? nu : u).update(i).update(Mn).digestInto(u), o.set(u, s * h), a._cloneInto(c);
  return a.destroy(), c.destroy(), ft(u, Mn), o.slice(0, r);
}
const eE = (t, e, i, r, s) => X2(t, Q2(t, e, i), r, s), on = sn, ma = BigInt(0), Do = BigInt(1);
function zs(t, e) {
  if (typeof e != "boolean")
    throw new Error(t + " boolean expected, got " + e);
}
function ms(t) {
  const e = t.toString(16);
  return e.length & 1 ? "0" + e : e;
}
function wf(t) {
  if (typeof t != "string")
    throw new Error("hex string expected, got " + typeof t);
  return t === "" ? ma : BigInt("0x" + t);
}
function an(t) {
  return wf(jr(t));
}
function Ks(t) {
  return lt(t), wf(jr(Uint8Array.from(t).reverse()));
}
function ba(t, e) {
  return ga(t.toString(16).padStart(e * 2, "0"));
}
function va(t, e) {
  return ba(t, e).reverse();
}
function We(t, e, i) {
  let r;
  if (typeof e == "string")
    try {
      r = ga(e);
    } catch (n) {
      throw new Error(t + " must be hex string or Uint8Array, cause: " + n);
    }
  else if (fa(e))
    r = Uint8Array.from(e);
  else
    throw new Error(t + " must be hex string or Uint8Array");
  const s = r.length;
  if (typeof i == "number" && s !== i)
    throw new Error(t + " of length " + i + " expected, got " + s);
  return r;
}
const qn = (t) => typeof t == "bigint" && ma <= t;
function tE(t, e, i) {
  return qn(t) && qn(e) && qn(i) && e <= t && t < i;
}
function Ao(t, e, i, r) {
  if (!tE(e, i, r))
    throw new Error("expected valid " + t + ": " + i + " <= n < " + r + ", got " + e);
}
function iE(t) {
  let e;
  for (e = 0; t > ma; t >>= Do, e += 1)
    ;
  return e;
}
const cn = (t) => (Do << BigInt(t)) - Do;
function rE(t, e, i) {
  if (typeof t != "number" || t < 2)
    throw new Error("hashLen must be a number");
  if (typeof e != "number" || e < 2)
    throw new Error("qByteLen must be a number");
  if (typeof i != "function")
    throw new Error("hmacFn must be a function");
  const r = (f) => new Uint8Array(f), s = (f) => Uint8Array.of(f);
  let n = r(t), o = r(t), a = 0;
  const c = () => {
    n.fill(1), o.fill(0), a = 0;
  }, u = (...f) => i(o, n, ...f), h = (f = r(0)) => {
    o = u(s(0), f), n = u(), f.length !== 0 && (o = u(s(1), f), n = u());
  }, l = () => {
    if (a++ >= 1e3)
      throw new Error("drbg: tried 1000 values");
    let f = 0;
    const p = [];
    for (; f < e; ) {
      n = u();
      const d = n.slice();
      p.push(d), f += n.length;
    }
    return vi(...p);
  };
  return (f, p) => {
    c(), h(f);
    let d;
    for (; !(d = p(l())); )
      h();
    return c(), d;
  };
}
function un(t, e, i = {}) {
  if (!t || typeof t != "object")
    throw new Error("expected valid options object");
  function r(s, n, o) {
    const a = t[s];
    if (o && a === void 0)
      return;
    const c = typeof a;
    if (c !== n || a === null)
      throw new Error(`param "${s}" is invalid: expected ${n}, got ${c}`);
  }
  Object.entries(e).forEach(([s, n]) => r(s, n, !1)), Object.entries(i).forEach(([s, n]) => r(s, n, !0));
}
function ou(t) {
  const e = /* @__PURE__ */ new WeakMap();
  return (i, ...r) => {
    const s = e.get(i);
    if (s !== void 0)
      return s;
    const n = t(i, ...r);
    return e.set(i, n), n;
  };
}
const Je = BigInt(0), Me = BigInt(1), Ei = BigInt(2), sE = BigInt(3), mf = BigInt(4), bf = BigInt(5), vf = BigInt(8);
function ut(t, e) {
  const i = t % e;
  return i >= Je ? i : e + i;
}
function gt(t, e, i) {
  let r = t;
  for (; e-- > Je; )
    r *= r, r %= i;
  return r;
}
function au(t, e) {
  if (t === Je)
    throw new Error("invert: expected non-zero number");
  if (e <= Je)
    throw new Error("invert: expected positive modulus, got " + e);
  let i = ut(t, e), r = e, s = Je, n = Me;
  for (; i !== Je; ) {
    const o = r / i, a = r % i, c = s - n * o;
    r = i, i = a, s = n, n = c;
  }
  if (r !== Me)
    throw new Error("invert: does not exist");
  return ut(s, e);
}
function Ef(t, e) {
  const i = (t.ORDER + Me) / mf, r = t.pow(e, i);
  if (!t.eql(t.sqr(r), e))
    throw new Error("Cannot find square root");
  return r;
}
function nE(t, e) {
  const i = (t.ORDER - bf) / vf, r = t.mul(e, Ei), s = t.pow(r, i), n = t.mul(e, s), o = t.mul(t.mul(n, Ei), s), a = t.mul(n, t.sub(o, t.ONE));
  if (!t.eql(t.sqr(a), e))
    throw new Error("Cannot find square root");
  return a;
}
function oE(t) {
  if (t < BigInt(3))
    throw new Error("sqrt is not defined for small field");
  let e = t - Me, i = 0;
  for (; e % Ei === Je; )
    e /= Ei, i++;
  let r = Ei;
  const s = nr(t);
  for (; cu(s, r) === 1; )
    if (r++ > 1e3)
      throw new Error("Cannot find square root: probably non-prime P");
  if (i === 1)
    return Ef;
  let n = s.pow(r, e);
  const o = (e + Me) / Ei;
  return function(a, c) {
    if (a.is0(c))
      return c;
    if (cu(a, c) !== 1)
      throw new Error("Cannot find square root");
    let u = i, h = a.mul(a.ONE, n), l = a.pow(c, e), f = a.pow(c, o);
    for (; !a.eql(l, a.ONE); ) {
      if (a.is0(l))
        return a.ZERO;
      let p = 1, d = a.sqr(l);
      for (; !a.eql(d, a.ONE); )
        if (p++, d = a.sqr(d), p === u)
          throw new Error("Cannot find square root");
      const g = Me << BigInt(u - p - 1), y = a.pow(h, g);
      u = p, h = a.sqr(y), l = a.mul(l, h), f = a.mul(f, y);
    }
    return f;
  };
}
function aE(t) {
  return t % mf === sE ? Ef : t % vf === bf ? nE : oE(t);
}
const cE = ["create", "isValid", "is0", "neg", "inv", "sqrt", "sqr", "eql", "add", "sub", "mul", "pow", "div", "addN", "subN", "mulN", "sqrN"];
function uE(t) {
  const e = { ORDER: "bigint", MASK: "bigint", BYTES: "number", BITS: "number" }, i = cE.reduce((r, s) => (r[s] = "function", r), e);
  return un(t, i), t;
}
function hE(t, e, i) {
  if (i < Je)
    throw new Error("invalid exponent, negatives unsupported");
  if (i === Je)
    return t.ONE;
  if (i === Me)
    return e;
  let r = t.ONE, s = e;
  for (; i > Je; )
    i & Me && (r = t.mul(r, s)), s = t.sqr(s), i >>= Me;
  return r;
}
function _f(t, e, i = !1) {
  const r = new Array(e.length).fill(i ? t.ZERO : void 0), s = e.reduce((o, a, c) => t.is0(a) ? o : (r[c] = o, t.mul(o, a)), t.ONE), n = t.inv(s);
  return e.reduceRight((o, a, c) => t.is0(a) ? o : (r[c] = t.mul(o, r[c]), t.mul(o, a)), n), r;
}
function cu(t, e) {
  const i = (t.ORDER - Me) / Ei, r = t.pow(e, i), s = t.eql(r, t.ONE), n = t.eql(r, t.ZERO), o = t.eql(r, t.neg(t.ONE));
  if (!s && !n && !o)
    throw new Error("invalid Legendre symbol result");
  return s ? 1 : n ? 0 : -1;
}
function lE(t, e) {
  e !== void 0 && qt(e);
  const i = e !== void 0 ? e : t.toString(2).length, r = Math.ceil(i / 8);
  return { nBitLength: i, nByteLength: r };
}
function nr(t, e, i = !1, r = {}) {
  if (t <= Je)
    throw new Error("invalid field: expected ORDER > 0, got " + t);
  let s, n;
  if (typeof e == "object" && e != null) {
    if (r.sqrt || i)
      throw new Error("cannot specify opts in two arguments");
    const h = e;
    h.BITS && (s = h.BITS), h.sqrt && (n = h.sqrt), typeof h.isLE == "boolean" && (i = h.isLE);
  } else
    typeof e == "number" && (s = e), r.sqrt && (n = r.sqrt);
  const { nBitLength: o, nByteLength: a } = lE(t, s);
  if (a > 2048)
    throw new Error("invalid field: expected ORDER of <= 2048 bytes");
  let c;
  const u = Object.freeze({ ORDER: t, isLE: i, BITS: o, BYTES: a, MASK: cn(o), ZERO: Je, ONE: Me, create: (h) => ut(h, t), isValid: (h) => {
    if (typeof h != "bigint")
      throw new Error("invalid field element: expected bigint, got " + typeof h);
    return Je <= h && h < t;
  }, is0: (h) => h === Je, isValidNot0: (h) => !u.is0(h) && u.isValid(h), isOdd: (h) => (h & Me) === Me, neg: (h) => ut(-h, t), eql: (h, l) => h === l, sqr: (h) => ut(h * h, t), add: (h, l) => ut(h + l, t), sub: (h, l) => ut(h - l, t), mul: (h, l) => ut(h * l, t), pow: (h, l) => hE(u, h, l), div: (h, l) => ut(h * au(l, t), t), sqrN: (h) => h * h, addN: (h, l) => h + l, subN: (h, l) => h - l, mulN: (h, l) => h * l, inv: (h) => au(h, t), sqrt: n || ((h) => (c || (c = aE(t)), c(u, h))), toBytes: (h) => i ? va(h, a) : ba(h, a), fromBytes: (h) => {
    if (h.length !== a)
      throw new Error("Field.fromBytes: expected " + a + " bytes, got " + h.length);
    return i ? Ks(h) : an(h);
  }, invertBatch: (h) => _f(u, h), cmov: (h, l, f) => f ? l : h });
  return Object.freeze(u);
}
function xf(t) {
  if (typeof t != "bigint")
    throw new Error("field order must be bigint");
  const e = t.toString(2).length;
  return Math.ceil(e / 8);
}
function If(t) {
  const e = xf(t);
  return e + Math.ceil(e / 2);
}
function fE(t, e, i = !1) {
  const r = t.length, s = xf(e), n = If(e);
  if (r < 16 || r < n || r > 1024)
    throw new Error("expected " + n + "-1024 bytes of input, got " + r);
  const o = i ? Ks(t) : an(t), a = ut(o, e - Me) + Me;
  return i ? va(a, s) : ba(a, s);
}
const Zi = BigInt(0), _i = BigInt(1);
function Or(t, e) {
  const i = e.negate();
  return t ? i : e;
}
function dE(t, e, i) {
  const r = e === "pz" ? (n) => n.pz : (n) => n.ez, s = _f(t.Fp, i.map(r));
  return i.map((n, o) => n.toAffine(s[o])).map(t.fromAffine);
}
function Sf(t, e) {
  if (!Number.isSafeInteger(t) || t <= 0 || t > e)
    throw new Error("invalid window size, expected [1.." + e + "], got W=" + t);
}
function jn(t, e) {
  Sf(t, e);
  const i = Math.ceil(e / t) + 1, r = 2 ** (t - 1), s = 2 ** t, n = cn(t), o = BigInt(t);
  return { windows: i, windowSize: r, mask: n, maxNumber: s, shiftBy: o };
}
function uu(t, e, i) {
  const { windowSize: r, mask: s, maxNumber: n, shiftBy: o } = i;
  let a = Number(t & s), c = t >> o;
  a > r && (a -= n, c += _i);
  const u = e * r, h = u + Math.abs(a) - 1, l = a === 0, f = a < 0, p = e % 2 !== 0;
  return { nextN: c, offset: h, isZero: l, isNeg: f, isNegF: p, offsetF: u };
}
function pE(t, e) {
  if (!Array.isArray(t))
    throw new Error("array expected");
  t.forEach((i, r) => {
    if (!(i instanceof e))
      throw new Error("invalid point at index " + r);
  });
}
function gE(t, e) {
  if (!Array.isArray(t))
    throw new Error("array of scalars expected");
  t.forEach((i, r) => {
    if (!e.isValid(i))
      throw new Error("invalid scalar at index " + r);
  });
}
const zn = /* @__PURE__ */ new WeakMap(), Df = /* @__PURE__ */ new WeakMap();
function Kn(t) {
  return Df.get(t) || 1;
}
function hu(t) {
  if (t !== Zi)
    throw new Error("invalid wNAF");
}
function yE(t, e) {
  return { constTimeNegate: Or, hasPrecomputes(i) {
    return Kn(i) !== 1;
  }, unsafeLadder(i, r, s = t.ZERO) {
    let n = i;
    for (; r > Zi; )
      r & _i && (s = s.add(n)), n = n.double(), r >>= _i;
    return s;
  }, precomputeWindow(i, r) {
    const { windows: s, windowSize: n } = jn(r, e), o = [];
    let a = i, c = a;
    for (let u = 0; u < s; u++) {
      c = a, o.push(c);
      for (let h = 1; h < n; h++)
        c = c.add(a), o.push(c);
      a = c.double();
    }
    return o;
  }, wNAF(i, r, s) {
    let n = t.ZERO, o = t.BASE;
    const a = jn(i, e);
    for (let c = 0; c < a.windows; c++) {
      const { nextN: u, offset: h, isZero: l, isNeg: f, isNegF: p, offsetF: d } = uu(s, c, a);
      s = u, l ? o = o.add(Or(p, r[d])) : n = n.add(Or(f, r[h]));
    }
    return hu(s), { p: n, f: o };
  }, wNAFUnsafe(i, r, s, n = t.ZERO) {
    const o = jn(i, e);
    for (let a = 0; a < o.windows && s !== Zi; a++) {
      const { nextN: c, offset: u, isZero: h, isNeg: l } = uu(s, a, o);
      if (s = c, !h) {
        const f = r[u];
        n = n.add(l ? f.negate() : f);
      }
    }
    return hu(s), n;
  }, getPrecomputes(i, r, s) {
    let n = zn.get(r);
    return n || (n = this.precomputeWindow(r, i), i !== 1 && (typeof s == "function" && (n = s(n)), zn.set(r, n))), n;
  }, wNAFCached(i, r, s) {
    const n = Kn(i);
    return this.wNAF(n, this.getPrecomputes(n, i, s), r);
  }, wNAFCachedUnsafe(i, r, s, n) {
    const o = Kn(i);
    return o === 1 ? this.unsafeLadder(i, r, n) : this.wNAFUnsafe(o, this.getPrecomputes(o, i, s), r, n);
  }, setWindowSize(i, r) {
    Sf(r, e), Df.set(i, r), zn.delete(i);
  } };
}
function wE(t, e, i, r) {
  let s = e, n = t.ZERO, o = t.ZERO;
  for (; i > Zi || r > Zi; )
    i & _i && (n = n.add(s)), r & _i && (o = o.add(s)), s = s.double(), i >>= _i, r >>= _i;
  return { p1: n, p2: o };
}
function mE(t, e, i, r) {
  pE(i, t), gE(r, e);
  const s = i.length, n = r.length;
  if (s !== n)
    throw new Error("arrays of points and scalars must have equal length");
  const o = t.ZERO, a = iE(BigInt(s));
  let c = 1;
  a > 12 ? c = a - 3 : a > 4 ? c = a - 2 : a > 0 && (c = 2);
  const u = cn(c), h = new Array(Number(u) + 1).fill(o), l = Math.floor((e.BITS - 1) / c) * c;
  let f = o;
  for (let p = l; p >= 0; p -= c) {
    h.fill(o);
    for (let g = 0; g < n; g++) {
      const y = r[g], E = Number(y >> BigInt(p) & u);
      h[E] = h[E].add(i[g]);
    }
    let d = o;
    for (let g = h.length - 1, y = o; g > 0; g--)
      y = y.add(h[g]), d = d.add(y);
    if (f = f.add(d), p !== 0)
      for (let g = 0; g < c; g++)
        f = f.double();
  }
  return f;
}
function lu(t, e) {
  if (e) {
    if (e.ORDER !== t)
      throw new Error("Field.ORDER must match order: Fp == p, Fn == n");
    return uE(e), e;
  } else
    return nr(t);
}
function bE(t, e, i = {}) {
  if (!e || typeof e != "object")
    throw new Error(`expected valid ${t} CURVE object`);
  for (const o of ["p", "n", "h"]) {
    const a = e[o];
    if (!(typeof a == "bigint" && a > Zi))
      throw new Error(`CURVE.${o} must be positive bigint`);
  }
  const r = lu(e.p, i.Fp), s = lu(e.n, i.Fn), n = ["Gx", "Gy", "a", t === "weierstrass" ? "b" : "d"];
  for (const o of n)
    if (!r.isValid(e[o]))
      throw new Error(`CURVE.${o} must be valid field element of CURVE.Fp`);
  return { Fp: r, Fn: s };
}
BigInt(0), BigInt(1), BigInt(2), BigInt(8);
const yr = BigInt(0), ji = BigInt(1), bs = BigInt(2);
function vE(t) {
  return un(t, { adjustScalarBytes: "function", powPminus2: "function" }), Object.freeze({ ...t });
}
function EE(t) {
  const e = vE(t), { P: i, type: r, adjustScalarBytes: s, powPminus2: n, randomBytes: o } = e, a = r === "x25519";
  if (!a && r !== "x448")
    throw new Error("invalid type");
  const c = o || sr, u = a ? 255 : 448, h = a ? 32 : 56, l = BigInt(a ? 9 : 5), f = BigInt(a ? 121665 : 39081), p = a ? bs ** BigInt(254) : bs ** BigInt(447), d = a ? BigInt(8) * bs ** BigInt(251) - ji : BigInt(4) * bs ** BigInt(445) - ji, g = p + d + ji, y = (w) => ut(w, i), E = v(l);
  function v(w) {
    return va(y(w), h);
  }
  function m(w) {
    const O = We("u coordinate", w, h);
    return a && (O[31] &= 127), y(Ks(O));
  }
  function D(w) {
    return Ks(s(We("scalar", w, h)));
  }
  function I(w, O) {
    const _ = C(m(O), D(w));
    if (_ === yr)
      throw new Error("invalid private or public key received");
    return v(_);
  }
  function R(w) {
    return I(w, E);
  }
  function B(w, O, _) {
    const $ = y(w * (O - _));
    return O = y(O - $), _ = y(_ + $), { x_2: O, x_3: _ };
  }
  function C(w, O) {
    Ao("u", w, yr, i), Ao("scalar", O, p, g);
    const _ = O, $ = w;
    let P = ji, k = yr, x = w, b = ji, S = yr;
    for (let A = BigInt(u - 1); A >= yr; A--) {
      const U = _ >> A & ji;
      S ^= U, { x_2: P, x_3: x } = B(S, P, x), { x_2: k, x_3: b } = B(S, k, b), S = U;
      const N = P + k, j = y(N * N), z = P - k, K = y(z * z), V = j - K, H = x + b, re = x - b, ie = y(re * N), J = y(H * z), fe = ie + J, Ie = ie - J;
      x = y(fe * fe), b = y($ * y(Ie * Ie)), P = y(j * K), k = y(V * (j + y(f * V)));
    }
    ({ x_2: P, x_3: x } = B(S, P, x)), { x_2: k, x_3: b } = B(S, k, b);
    const T = n(k);
    return y(P * T);
  }
  return { scalarMult: I, scalarMultBase: R, getSharedSecret: (w, O) => I(w, O), getPublicKey: (w) => R(w), utils: { randomPrivateKey: () => c(h) }, GuBytes: E.slice() };
}
BigInt(0);
const _E = BigInt(1), fu = BigInt(2), xE = BigInt(3), IE = BigInt(5), SE = BigInt(8), Af = { p: BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"), n: BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"), h: SE, a: BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"), d: BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"), Gx: BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"), Gy: BigInt("0x6666666666666666666666666666666666666666666666666666666666666658") };
function DE(t) {
  const e = BigInt(10), i = BigInt(20), r = BigInt(40), s = BigInt(80), n = Af.p, o = t * t % n * t % n, a = gt(o, fu, n) * o % n, c = gt(a, _E, n) * t % n, u = gt(c, IE, n) * c % n, h = gt(u, e, n) * u % n, l = gt(h, i, n) * h % n, f = gt(l, r, n) * l % n, p = gt(f, s, n) * f % n, d = gt(p, s, n) * f % n, g = gt(d, e, n) * u % n;
  return { pow_p_5_8: gt(g, fu, n) * t % n, b2: o };
}
function AE(t) {
  return t[0] &= 248, t[31] &= 127, t[31] |= 64, t;
}
const $o = (() => {
  const t = Af.p;
  return EE({ P: t, type: "x25519", powPminus2: (e) => {
    const { pow_p_5_8: i, b2: r } = DE(e);
    return ut(gt(i, xE, t) * r, t);
  }, adjustScalarBytes: AE });
})();
function du(t) {
  t.lowS !== void 0 && zs("lowS", t.lowS), t.prehash !== void 0 && zs("prehash", t.prehash);
}
class $E extends Error {
  constructor(e = "") {
    super(e);
  }
}
const kt = { Err: $E, _tlv: { encode: (t, e) => {
  const { Err: i } = kt;
  if (t < 0 || t > 256)
    throw new i("tlv.encode: wrong tag");
  if (e.length & 1)
    throw new i("tlv.encode: unpadded data");
  const r = e.length / 2, s = ms(r);
  if (s.length / 2 & 128)
    throw new i("tlv.encode: long form length too big");
  const n = r > 127 ? ms(s.length / 2 | 128) : "";
  return ms(t) + n + s + e;
}, decode(t, e) {
  const { Err: i } = kt;
  let r = 0;
  if (t < 0 || t > 256)
    throw new i("tlv.encode: wrong tag");
  if (e.length < 2 || e[r++] !== t)
    throw new i("tlv.decode: wrong tlv");
  const s = e[r++], n = !!(s & 128);
  let o = 0;
  if (!n)
    o = s;
  else {
    const c = s & 127;
    if (!c)
      throw new i("tlv.decode(long): indefinite length not supported");
    if (c > 4)
      throw new i("tlv.decode(long): byte length is too big");
    const u = e.subarray(r, r + c);
    if (u.length !== c)
      throw new i("tlv.decode: length bytes not complete");
    if (u[0] === 0)
      throw new i("tlv.decode(long): zero leftmost byte");
    for (const h of u)
      o = o << 8 | h;
    if (r += c, o < 128)
      throw new i("tlv.decode(long): not minimal encoding");
  }
  const a = e.subarray(r, r + o);
  if (a.length !== o)
    throw new i("tlv.decode: wrong value length");
  return { v: a, l: e.subarray(r + o) };
} }, _int: { encode(t) {
  const { Err: e } = kt;
  if (t < Tr)
    throw new e("integer: negative integers are not allowed");
  let i = ms(t);
  if (Number.parseInt(i[0], 16) & 8 && (i = "00" + i), i.length & 1)
    throw new e("unexpected DER parsing assertion: unpadded hex");
  return i;
}, decode(t) {
  const { Err: e } = kt;
  if (t[0] & 128)
    throw new e("invalid signature integer: negative");
  if (t[0] === 0 && !(t[1] & 128))
    throw new e("invalid signature integer: unnecessary leading zero");
  return an(t);
} }, toSig(t) {
  const { Err: e, _int: i, _tlv: r } = kt, s = We("signature", t), { v: n, l: o } = r.decode(48, s);
  if (o.length)
    throw new e("invalid signature: left bytes after parsing");
  const { v: a, l: c } = r.decode(2, n), { v: u, l: h } = r.decode(2, c);
  if (h.length)
    throw new e("invalid signature: left bytes after parsing");
  return { r: i.decode(a), s: i.decode(u) };
}, hexFromSig(t) {
  const { _tlv: e, _int: i } = kt, r = e.encode(2, i.encode(t.r)), s = e.encode(2, i.encode(t.s)), n = r + s;
  return e.encode(48, n);
} }, Tr = BigInt(0), Cr = BigInt(1), OE = BigInt(2), vs = BigInt(3), TE = BigInt(4);
function CE(t, e, i) {
  function r(s) {
    const n = t.sqr(s), o = t.mul(n, s);
    return t.add(t.add(o, t.mul(s, e)), i);
  }
  return r;
}
function $f(t, e, i) {
  const { BYTES: r } = t;
  function s(n) {
    let o;
    if (typeof n == "bigint")
      o = n;
    else {
      let a = We("private key", n);
      if (e) {
        if (!e.includes(a.length * 2))
          throw new Error("invalid private key");
        const c = new Uint8Array(r);
        c.set(a, c.length - a.length), a = c;
      }
      try {
        o = t.fromBytes(a);
      } catch {
        throw new Error(`invalid private key: expected ui8a of size ${r}, got ${typeof n}`);
      }
    }
    if (i && (o = t.create(o)), !t.isValidNot0(o))
      throw new Error("invalid private key: out of range [1..N-1]");
    return o;
  }
  return s;
}
function PE(t, e = {}) {
  const { Fp: i, Fn: r } = bE("weierstrass", t, e), { h: s, n } = t;
  un(e, {}, { allowInfinityPoint: "boolean", clearCofactor: "function", isTorsionFree: "function", fromBytes: "function", toBytes: "function", endo: "object", wrapPrivateKey: "boolean" });
  const { endo: o } = e;
  if (o && (!i.is0(t.a) || typeof o.beta != "bigint" || typeof o.splitScalar != "function"))
    throw new Error('invalid endo: expected "beta": bigint and "splitScalar": function');
  function a() {
    if (!i.isOdd)
      throw new Error("compression is not supported: Field does not have .isOdd()");
  }
  function c(C, w, O) {
    const { x: _, y: $ } = w.toAffine(), P = i.toBytes(_);
    if (zs("isCompressed", O), O) {
      a();
      const k = !i.isOdd($);
      return vi(Of(k), P);
    } else
      return vi(Uint8Array.of(4), P, i.toBytes($));
  }
  function u(C) {
    lt(C);
    const w = i.BYTES, O = w + 1, _ = 2 * w + 1, $ = C.length, P = C[0], k = C.subarray(1);
    if ($ === O && (P === 2 || P === 3)) {
      const x = i.fromBytes(k);
      if (!i.isValid(x))
        throw new Error("bad point: is not on curve, wrong x");
      const b = f(x);
      let S;
      try {
        S = i.sqrt(b);
      } catch (A) {
        const U = A instanceof Error ? ": " + A.message : "";
        throw new Error("bad point: is not on curve, sqrt error" + U);
      }
      a();
      const T = i.isOdd(S);
      return (P & 1) === 1 !== T && (S = i.neg(S)), { x, y: S };
    } else if ($ === _ && P === 4) {
      const x = i.fromBytes(k.subarray(w * 0, w * 1)), b = i.fromBytes(k.subarray(w * 1, w * 2));
      if (!p(x, b))
        throw new Error("bad point: is not on curve");
      return { x, y: b };
    } else
      throw new Error(`bad point: got length ${$}, expected compressed=${O} or uncompressed=${_}`);
  }
  const h = e.toBytes || c, l = e.fromBytes || u, f = CE(i, t.a, t.b);
  function p(C, w) {
    const O = i.sqr(w), _ = f(C);
    return i.eql(O, _);
  }
  if (!p(t.Gx, t.Gy))
    throw new Error("bad curve params: generator point");
  const d = i.mul(i.pow(t.a, vs), TE), g = i.mul(i.sqr(t.b), BigInt(27));
  if (i.is0(i.add(d, g)))
    throw new Error("bad curve params: a or b");
  function y(C, w, O = !1) {
    if (!i.isValid(w) || O && i.is0(w))
      throw new Error(`bad point coordinate ${C}`);
    return w;
  }
  function E(C) {
    if (!(C instanceof I))
      throw new Error("ProjectivePoint expected");
  }
  const v = ou((C, w) => {
    const { px: O, py: _, pz: $ } = C;
    if (i.eql($, i.ONE))
      return { x: O, y: _ };
    const P = C.is0();
    w == null && (w = P ? i.ONE : i.inv($));
    const k = i.mul(O, w), x = i.mul(_, w), b = i.mul($, w);
    if (P)
      return { x: i.ZERO, y: i.ZERO };
    if (!i.eql(b, i.ONE))
      throw new Error("invZ was invalid");
    return { x: k, y: x };
  }), m = ou((C) => {
    if (C.is0()) {
      if (e.allowInfinityPoint && !i.is0(C.py))
        return;
      throw new Error("bad point: ZERO");
    }
    const { x: w, y: O } = C.toAffine();
    if (!i.isValid(w) || !i.isValid(O))
      throw new Error("bad point: x or y not field elements");
    if (!p(w, O))
      throw new Error("bad point: equation left != right");
    if (!C.isTorsionFree())
      throw new Error("bad point: not in prime-order subgroup");
    return !0;
  });
  function D(C, w, O, _, $) {
    return O = new I(i.mul(O.px, C), O.py, O.pz), w = Or(_, w), O = Or($, O), w.add(O);
  }
  class I {
    constructor(w, O, _) {
      this.px = y("x", w), this.py = y("y", O, !0), this.pz = y("z", _), Object.freeze(this);
    }
    static fromAffine(w) {
      const { x: O, y: _ } = w || {};
      if (!w || !i.isValid(O) || !i.isValid(_))
        throw new Error("invalid affine point");
      if (w instanceof I)
        throw new Error("projective point not allowed");
      return i.is0(O) && i.is0(_) ? I.ZERO : new I(O, _, i.ONE);
    }
    get x() {
      return this.toAffine().x;
    }
    get y() {
      return this.toAffine().y;
    }
    static normalizeZ(w) {
      return dE(I, "pz", w);
    }
    static fromBytes(w) {
      return lt(w), I.fromHex(w);
    }
    static fromHex(w) {
      const O = I.fromAffine(l(We("pointHex", w)));
      return O.assertValidity(), O;
    }
    static fromPrivateKey(w) {
      const O = $f(r, e.allowedPrivateKeyLengths, e.wrapPrivateKey);
      return I.BASE.multiply(O(w));
    }
    static msm(w, O) {
      return mE(I, r, w, O);
    }
    precompute(w = 8, O = !0) {
      return B.setWindowSize(this, w), O || this.multiply(vs), this;
    }
    _setWindowSize(w) {
      this.precompute(w);
    }
    assertValidity() {
      m(this);
    }
    hasEvenY() {
      const { y: w } = this.toAffine();
      if (!i.isOdd)
        throw new Error("Field doesn't support isOdd");
      return !i.isOdd(w);
    }
    equals(w) {
      E(w);
      const { px: O, py: _, pz: $ } = this, { px: P, py: k, pz: x } = w, b = i.eql(i.mul(O, x), i.mul(P, $)), S = i.eql(i.mul(_, x), i.mul(k, $));
      return b && S;
    }
    negate() {
      return new I(this.px, i.neg(this.py), this.pz);
    }
    double() {
      const { a: w, b: O } = t, _ = i.mul(O, vs), { px: $, py: P, pz: k } = this;
      let x = i.ZERO, b = i.ZERO, S = i.ZERO, T = i.mul($, $), A = i.mul(P, P), U = i.mul(k, k), N = i.mul($, P);
      return N = i.add(N, N), S = i.mul($, k), S = i.add(S, S), x = i.mul(w, S), b = i.mul(_, U), b = i.add(x, b), x = i.sub(A, b), b = i.add(A, b), b = i.mul(x, b), x = i.mul(N, x), S = i.mul(_, S), U = i.mul(w, U), N = i.sub(T, U), N = i.mul(w, N), N = i.add(N, S), S = i.add(T, T), T = i.add(S, T), T = i.add(T, U), T = i.mul(T, N), b = i.add(b, T), U = i.mul(P, k), U = i.add(U, U), T = i.mul(U, N), x = i.sub(x, T), S = i.mul(U, A), S = i.add(S, S), S = i.add(S, S), new I(x, b, S);
    }
    add(w) {
      E(w);
      const { px: O, py: _, pz: $ } = this, { px: P, py: k, pz: x } = w;
      let b = i.ZERO, S = i.ZERO, T = i.ZERO;
      const A = t.a, U = i.mul(t.b, vs);
      let N = i.mul(O, P), j = i.mul(_, k), z = i.mul($, x), K = i.add(O, _), V = i.add(P, k);
      K = i.mul(K, V), V = i.add(N, j), K = i.sub(K, V), V = i.add(O, $);
      let H = i.add(P, x);
      return V = i.mul(V, H), H = i.add(N, z), V = i.sub(V, H), H = i.add(_, $), b = i.add(k, x), H = i.mul(H, b), b = i.add(j, z), H = i.sub(H, b), T = i.mul(A, V), b = i.mul(U, z), T = i.add(b, T), b = i.sub(j, T), T = i.add(j, T), S = i.mul(b, T), j = i.add(N, N), j = i.add(j, N), z = i.mul(A, z), V = i.mul(U, V), j = i.add(j, z), z = i.sub(N, z), z = i.mul(A, z), V = i.add(V, z), N = i.mul(j, V), S = i.add(S, N), N = i.mul(H, V), b = i.mul(K, b), b = i.sub(b, N), N = i.mul(K, j), T = i.mul(H, T), T = i.add(T, N), new I(b, S, T);
    }
    subtract(w) {
      return this.add(w.negate());
    }
    is0() {
      return this.equals(I.ZERO);
    }
    multiply(w) {
      const { endo: O } = e;
      if (!r.isValidNot0(w))
        throw new Error("invalid scalar: out of range");
      let _, $;
      const P = (k) => B.wNAFCached(this, k, I.normalizeZ);
      if (O) {
        const { k1neg: k, k1: x, k2neg: b, k2: S } = O.splitScalar(w), { p: T, f: A } = P(x), { p: U, f: N } = P(S);
        $ = A.add(N), _ = D(O.beta, T, U, k, b);
      } else {
        const { p: k, f: x } = P(w);
        _ = k, $ = x;
      }
      return I.normalizeZ([_, $])[0];
    }
    multiplyUnsafe(w) {
      const { endo: O } = e, _ = this;
      if (!r.isValid(w))
        throw new Error("invalid scalar: out of range");
      if (w === Tr || _.is0())
        return I.ZERO;
      if (w === Cr)
        return _;
      if (B.hasPrecomputes(this))
        return this.multiply(w);
      if (O) {
        const { k1neg: $, k1: P, k2neg: k, k2: x } = O.splitScalar(w), { p1: b, p2: S } = wE(I, _, P, x);
        return D(O.beta, b, S, $, k);
      } else
        return B.wNAFCachedUnsafe(_, w);
    }
    multiplyAndAddUnsafe(w, O, _) {
      const $ = this.multiplyUnsafe(O).add(w.multiplyUnsafe(_));
      return $.is0() ? void 0 : $;
    }
    toAffine(w) {
      return v(this, w);
    }
    isTorsionFree() {
      const { isTorsionFree: w } = e;
      return s === Cr ? !0 : w ? w(I, this) : B.wNAFCachedUnsafe(this, n).is0();
    }
    clearCofactor() {
      const { clearCofactor: w } = e;
      return s === Cr ? this : w ? w(I, this) : this.multiplyUnsafe(s);
    }
    toBytes(w = !0) {
      return zs("isCompressed", w), this.assertValidity(), h(I, this, w);
    }
    toRawBytes(w = !0) {
      return this.toBytes(w);
    }
    toHex(w = !0) {
      return jr(this.toBytes(w));
    }
    toString() {
      return `<Point ${this.is0() ? "ZERO" : this.toHex()}>`;
    }
  }
  I.BASE = new I(t.Gx, t.Gy, i.ONE), I.ZERO = new I(i.ZERO, i.ONE, i.ZERO), I.Fp = i, I.Fn = r;
  const R = r.BITS, B = yE(I, e.endo ? Math.ceil(R / 2) : R);
  return I;
}
function Of(t) {
  return Uint8Array.of(t ? 2 : 3);
}
function RE(t, e, i = {}) {
  un(e, { hash: "function" }, { hmac: "function", lowS: "boolean", randomBytes: "function", bits2int: "function", bits2int_modN: "function" });
  const r = e.randomBytes || sr, s = e.hmac || ((_, ...$) => nn(e.hash, _, vi(...$))), { Fp: n, Fn: o } = t, { ORDER: a, BITS: c } = o;
  function u(_) {
    const $ = a >> Cr;
    return _ > $;
  }
  function h(_) {
    return u(_) ? o.neg(_) : _;
  }
  function l(_, $) {
    if (!o.isValidNot0($))
      throw new Error(`invalid signature ${_}: out of range 1..CURVE.n`);
  }
  class f {
    constructor($, P, k) {
      l("r", $), l("s", P), this.r = $, this.s = P, k != null && (this.recovery = k), Object.freeze(this);
    }
    static fromCompact($) {
      const P = o.BYTES, k = We("compactSignature", $, P * 2);
      return new f(o.fromBytes(k.subarray(0, P)), o.fromBytes(k.subarray(P, P * 2)));
    }
    static fromDER($) {
      const { r: P, s: k } = kt.toSig(We("DER", $));
      return new f(P, k);
    }
    assertValidity() {
    }
    addRecoveryBit($) {
      return new f(this.r, this.s, $);
    }
    recoverPublicKey($) {
      const P = n.ORDER, { r: k, s: x, recovery: b } = this;
      if (b == null || ![0, 1, 2, 3].includes(b))
        throw new Error("recovery id invalid");
      if (a * OE < P && b > 1)
        throw new Error("recovery id is ambiguous for h>1 curve");
      const S = b === 2 || b === 3 ? k + a : k;
      if (!n.isValid(S))
        throw new Error("recovery id 2 or 3 invalid");
      const T = n.toBytes(S), A = t.fromHex(vi(Of((b & 1) === 0), T)), U = o.inv(S), N = m(We("msgHash", $)), j = o.create(-N * U), z = o.create(x * U), K = t.BASE.multiplyUnsafe(j).add(A.multiplyUnsafe(z));
      if (K.is0())
        throw new Error("point at infinify");
      return K.assertValidity(), K;
    }
    hasHighS() {
      return u(this.s);
    }
    normalizeS() {
      return this.hasHighS() ? new f(this.r, o.neg(this.s), this.recovery) : this;
    }
    toBytes($) {
      if ($ === "compact")
        return vi(o.toBytes(this.r), o.toBytes(this.s));
      if ($ === "der")
        return ga(kt.hexFromSig(this));
      throw new Error("invalid format");
    }
    toDERRawBytes() {
      return this.toBytes("der");
    }
    toDERHex() {
      return jr(this.toBytes("der"));
    }
    toCompactRawBytes() {
      return this.toBytes("compact");
    }
    toCompactHex() {
      return jr(this.toBytes("compact"));
    }
  }
  const p = $f(o, i.allowedPrivateKeyLengths, i.wrapPrivateKey), d = { isValidPrivateKey(_) {
    try {
      return p(_), !0;
    } catch {
      return !1;
    }
  }, normPrivateKeyToScalar: p, randomPrivateKey: () => {
    const _ = a;
    return fE(r(If(_)), _);
  }, precompute(_ = 8, $ = t.BASE) {
    return $.precompute(_, !1);
  } };
  function g(_, $ = !0) {
    return t.fromPrivateKey(_).toBytes($);
  }
  function y(_) {
    if (typeof _ == "bigint")
      return !1;
    if (_ instanceof t)
      return !0;
    const $ = We("key", _).length, P = n.BYTES, k = P + 1, x = 2 * P + 1;
    if (!(i.allowedPrivateKeyLengths || o.BYTES === k))
      return $ === k || $ === x;
  }
  function E(_, $, P = !0) {
    if (y(_) === !0)
      throw new Error("first arg must be private key");
    if (y($) === !1)
      throw new Error("second arg must be public key");
    return t.fromHex($).multiply(p(_)).toBytes(P);
  }
  const v = e.bits2int || function(_) {
    if (_.length > 8192)
      throw new Error("input is too large");
    const $ = an(_), P = _.length * 8 - c;
    return P > 0 ? $ >> BigInt(P) : $;
  }, m = e.bits2int_modN || function(_) {
    return o.create(v(_));
  }, D = cn(c);
  function I(_) {
    return Ao("num < 2^" + c, _, Tr, D), o.toBytes(_);
  }
  function R(_, $, P = B) {
    if (["recovered", "canonical"].some((K) => K in P))
      throw new Error("sign() legacy options not supported");
    const { hash: k } = e;
    let { lowS: x, prehash: b, extraEntropy: S } = P;
    x == null && (x = !0), _ = We("msgHash", _), du(P), b && (_ = We("prehashed msgHash", k(_)));
    const T = m(_), A = p($), U = [I(A), I(T)];
    if (S != null && S !== !1) {
      const K = S === !0 ? r(n.BYTES) : S;
      U.push(We("extraEntropy", K));
    }
    const N = vi(...U), j = T;
    function z(K) {
      const V = v(K);
      if (!o.isValidNot0(V))
        return;
      const H = o.inv(V), re = t.BASE.multiply(V).toAffine(), ie = o.create(re.x);
      if (ie === Tr)
        return;
      const J = o.create(H * o.create(j + ie * A));
      if (J === Tr)
        return;
      let fe = (re.x === ie ? 0 : 2) | Number(re.y & Cr), Ie = J;
      return x && u(J) && (Ie = h(J), fe ^= 1), new f(ie, Ie, fe);
    }
    return { seed: N, k2sig: z };
  }
  const B = { lowS: e.lowS, prehash: !1 }, C = { lowS: e.lowS, prehash: !1 };
  function w(_, $, P = B) {
    const { seed: k, k2sig: x } = R(_, $, P);
    return rE(e.hash.outputLen, o.BYTES, s)(k, x);
  }
  t.BASE.precompute(8);
  function O(_, $, P, k = C) {
    const x = _;
    $ = We("msgHash", $), P = We("publicKey", P), du(k);
    const { lowS: b, prehash: S, format: T } = k;
    if ("strict" in k)
      throw new Error("options.strict was renamed to lowS");
    if (T !== void 0 && !["compact", "der", "js"].includes(T))
      throw new Error('format must be "compact", "der" or "js"');
    const A = typeof x == "string" || fa(x), U = !A && !T && typeof x == "object" && x !== null && typeof x.r == "bigint" && typeof x.s == "bigint";
    if (!A && !U)
      throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");
    let N, j;
    try {
      if (U)
        if (T === void 0 || T === "js")
          N = new f(x.r, x.s);
        else
          throw new Error("invalid format");
      if (A) {
        try {
          T !== "compact" && (N = f.fromDER(x));
        } catch (fe) {
          if (!(fe instanceof kt.Err))
            throw fe;
        }
        !N && T !== "der" && (N = f.fromCompact(x));
      }
      j = t.fromHex(P);
    } catch {
      return !1;
    }
    if (!N || b && N.hasHighS())
      return !1;
    S && ($ = e.hash($));
    const { r: z, s: K } = N, V = m($), H = o.inv(K), re = o.create(V * H), ie = o.create(z * H), J = t.BASE.multiplyUnsafe(re).add(j.multiplyUnsafe(ie));
    return J.is0() ? !1 : o.create(J.x) === z;
  }
  return Object.freeze({ getPublicKey: g, getSharedSecret: E, sign: w, verify: O, utils: d, Point: t, Signature: f });
}
function FE(t) {
  const e = { a: t.a, b: t.b, p: t.Fp.ORDER, n: t.n, h: t.h, Gx: t.Gx, Gy: t.Gy }, i = t.Fp, r = nr(e.n, t.nBitLength), s = { Fp: i, Fn: r, allowedPrivateKeyLengths: t.allowedPrivateKeyLengths, allowInfinityPoint: t.allowInfinityPoint, endo: t.endo, wrapPrivateKey: t.wrapPrivateKey, isTorsionFree: t.isTorsionFree, clearCofactor: t.clearCofactor, fromBytes: t.fromBytes, toBytes: t.toBytes };
  return { CURVE: e, curveOpts: s };
}
function UE(t) {
  const { CURVE: e, curveOpts: i } = FE(t), r = { hash: t.hash, hmac: t.hmac, randomBytes: t.randomBytes, lowS: t.lowS, bits2int: t.bits2int, bits2int_modN: t.bits2int_modN };
  return { CURVE: e, curveOpts: i, ecdsaOpts: r };
}
function BE(t, e) {
  return Object.assign({}, e, { ProjectivePoint: e.Point, CURVE: t });
}
function NE(t) {
  const { CURVE: e, curveOpts: i, ecdsaOpts: r } = UE(t), s = PE(e, i), n = RE(s, r, i);
  return BE(t, n);
}
function Oo(t, e) {
  const i = (r) => NE({ ...t, hash: r });
  return { ...i(e), create: i };
}
const Tf = { p: BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff"), n: BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"), h: BigInt(1), a: BigInt("0xffffffff00000001000000000000000000000000fffffffffffffffffffffffc"), b: BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"), Gx: BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"), Gy: BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5") }, Cf = { p: BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffff"), n: BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf581a0db248b0a77aecec196accc52973"), h: BigInt(1), a: BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000fffffffc"), b: BigInt("0xb3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aef"), Gx: BigInt("0xaa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7"), Gy: BigInt("0x3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f") }, Pf = { p: BigInt("0x1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"), n: BigInt("0x01fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa51868783bf2f966b7fcc0148f709a5d03bb5c9b8899c47aebb6fb71e91386409"), h: BigInt(1), a: BigInt("0x1fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc"), b: BigInt("0x0051953eb9618e1c9a1f929a21a0b68540eea2da725b99b315f3b8b489918ef109e156193951ec7e937b1652c0bd3bb1bf073573df883d2c34f1ef451fd46b503f00"), Gx: BigInt("0x00c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66"), Gy: BigInt("0x011839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650") }, kE = nr(Tf.p), LE = nr(Cf.p), ME = nr(Pf.p), qE = Oo({ ...Tf, Fp: kE, lowS: !1 }, sn);
Oo({ ...Cf, Fp: LE, lowS: !1 }, Gv), Oo({ ...Pf, Fp: ME, lowS: !1, allowedPrivateKeyLengths: [130, 131, 132] }, Wv);
const jE = qE, Rf = "base10", qe = "base16", Ye = "base64pad", si = "base64url", ts = "utf8", Ff = 0, Mt = 1, is = 2, zE = 0, pu = 1, Pr = 12, Ea = 32;
function KE() {
  const t = $o.utils.randomPrivateKey(), e = $o.getPublicKey(t);
  return { privateKey: Ze(t, qe), publicKey: Ze(e, qe) };
}
function To() {
  const t = sr(Ea);
  return Ze(t, qe);
}
function VE(t, e) {
  const i = $o.getSharedSecret(ht(t, qe), ht(e, qe)), r = eE(on, i, void 0, void 0, Ea);
  return Ze(r, qe);
}
function Os(t) {
  const e = on(ht(t, qe));
  return Ze(e, qe);
}
function at(t) {
  const e = on(ht(t, ts));
  return Ze(e, qe);
}
function Uf(t) {
  return ht(`${t}`, Rf);
}
function $i(t) {
  return Number(Ze(t, Rf));
}
function Bf(t) {
  return t.replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
}
function Nf(t) {
  const e = t.replace(/-/g, "+").replace(/_/g, "/"), i = (4 - e.length % 4) % 4;
  return e + "=".repeat(i);
}
function HE(t) {
  const e = Uf(typeof t.type < "u" ? t.type : Ff);
  if ($i(e) === Mt && typeof t.senderPublicKey > "u")
    throw new Error("Missing sender public key for type 1 envelope");
  const i = typeof t.senderPublicKey < "u" ? ht(t.senderPublicKey, qe) : void 0, r = typeof t.iv < "u" ? ht(t.iv, qe) : sr(Pr), s = ht(t.symKey, qe), n = gf(s, r).encrypt(ht(t.message, ts)), o = kf({ type: e, sealed: n, iv: r, senderPublicKey: i });
  return t.encoding === si ? Bf(o) : o;
}
function WE(t) {
  const e = ht(t.symKey, qe), { sealed: i, iv: r } = Kr({ encoded: t.encoded, encoding: t.encoding }), s = gf(e, r).decrypt(i);
  if (s === null)
    throw new Error("Failed to decrypt");
  return Ze(s, ts);
}
function GE(t, e) {
  const i = Uf(is), r = sr(Pr), s = ht(t, ts), n = kf({ type: i, sealed: s, iv: r });
  return e === si ? Bf(n) : n;
}
function YE(t, e) {
  const { sealed: i } = Kr({ encoded: t, encoding: e });
  return Ze(i, ts);
}
function kf(t) {
  if ($i(t.type) === is)
    return Ze($r([t.type, t.sealed]), Ye);
  if ($i(t.type) === Mt) {
    if (typeof t.senderPublicKey > "u")
      throw new Error("Missing sender public key for type 1 envelope");
    return Ze($r([t.type, t.senderPublicKey, t.iv, t.sealed]), Ye);
  }
  return Ze($r([t.type, t.iv, t.sealed]), Ye);
}
function Kr(t) {
  const e = (t.encoding || Ye) === si ? Nf(t.encoded) : t.encoded, i = ht(e, Ye), r = i.slice(zE, pu), s = pu;
  if ($i(r) === Mt) {
    const c = s + Ea, u = c + Pr, h = i.slice(s, c), l = i.slice(c, u), f = i.slice(u);
    return { type: r, sealed: f, iv: l, senderPublicKey: h };
  }
  if ($i(r) === is) {
    const c = i.slice(s), u = sr(Pr);
    return { type: r, sealed: c, iv: u };
  }
  const n = s + Pr, o = i.slice(s, n), a = i.slice(n);
  return { type: r, sealed: a, iv: o };
}
function JE(t, e) {
  const i = Kr({ encoded: t, encoding: e?.encoding });
  return Lf({ type: $i(i.type), senderPublicKey: typeof i.senderPublicKey < "u" ? Ze(i.senderPublicKey, qe) : void 0, receiverPublicKey: e?.receiverPublicKey });
}
function Lf(t) {
  const e = t?.type || Ff;
  if (e === Mt) {
    if (typeof t?.senderPublicKey > "u")
      throw new Error("missing sender public key");
    if (typeof t?.receiverPublicKey > "u")
      throw new Error("missing receiver public key");
  }
  return { type: e, senderPublicKey: t?.senderPublicKey, receiverPublicKey: t?.receiverPublicKey };
}
function gu(t) {
  return t.type === Mt && typeof t.senderPublicKey == "string" && typeof t.receiverPublicKey == "string";
}
function yu(t) {
  return t.type === is;
}
function ZE(t) {
  const e = Buffer.from(t.x, "base64"), i = Buffer.from(t.y, "base64");
  return $r([new Uint8Array([4]), e, i]);
}
function QE(t, e) {
  const [i, r, s] = t.split("."), n = Buffer.from(Nf(s), "base64");
  if (n.length !== 64)
    throw new Error("Invalid signature length");
  const o = n.slice(0, 32), a = n.slice(32, 64), c = `${i}.${r}`, u = on(c), h = ZE(e);
  if (!jE.verify($r([o, a]), u, h))
    throw new Error("Invalid signature");
  return ho(t).payload;
}
const XE = "irn";
function Vs(t) {
  return t?.relay || { protocol: XE };
}
function Wi(t) {
  const e = _b[t];
  if (typeof e > "u")
    throw new Error(`Relay Protocol not supported: ${t}`);
  return e;
}
function e3(t, e = "-") {
  const i = {}, r = "relay" + e;
  return Object.keys(t).forEach((s) => {
    if (s.startsWith(r)) {
      const n = s.replace(r, ""), o = t[s];
      i[n] = o;
    }
  }), i;
}
function wu(t) {
  if (!t.includes("wc:")) {
    const u = Yl(t);
    u != null && u.includes("wc:") && (t = u);
  }
  t = t.includes("wc://") ? t.replace("wc://", "") : t, t = t.includes("wc:") ? t.replace("wc:", "") : t;
  const e = t.indexOf(":"), i = t.indexOf("?") !== -1 ? t.indexOf("?") : void 0, r = t.substring(0, e), s = t.substring(e + 1, i).split("@"), n = typeof i < "u" ? t.substring(i) : "", o = new URLSearchParams(n), a = {};
  o.forEach((u, h) => {
    a[h] = u;
  });
  const c = typeof a.methods == "string" ? a.methods.split(",") : void 0;
  return { protocol: r, topic: t3(s[0]), version: parseInt(s[1], 10), symKey: a.symKey, relay: e3(a), methods: c, expiryTimestamp: a.expiryTimestamp ? parseInt(a.expiryTimestamp, 10) : void 0 };
}
function t3(t) {
  return t.startsWith("//") ? t.substring(2) : t;
}
function i3(t, e = "-") {
  const i = "relay", r = {};
  return Object.keys(t).forEach((s) => {
    const n = s, o = i + e + n;
    t[n] && (r[o] = t[n]);
  }), r;
}
function mu(t) {
  const e = new URLSearchParams(), i = i3(t.relay);
  Object.keys(i).sort().forEach((s) => {
    e.set(s, i[s]);
  }), e.set("symKey", t.symKey), t.expiryTimestamp && e.set("expiryTimestamp", t.expiryTimestamp.toString()), t.methods && e.set("methods", t.methods.join(","));
  const r = e.toString();
  return `${t.protocol}:${t.topic}@${t.version}?${r}`;
}
function Es(t, e, i) {
  return `${t}?wc_ev=${i}&topic=${e}`;
}
var r3 = Object.defineProperty, s3 = Object.defineProperties, n3 = Object.getOwnPropertyDescriptors, bu = Object.getOwnPropertySymbols, o3 = Object.prototype.hasOwnProperty, a3 = Object.prototype.propertyIsEnumerable, vu = (t, e, i) => e in t ? r3(t, e, { enumerable: !0, configurable: !0, writable: !0, value: i }) : t[e] = i, c3 = (t, e) => {
  for (var i in e || (e = {}))
    o3.call(e, i) && vu(t, i, e[i]);
  if (bu)
    for (var i of bu(e))
      a3.call(e, i) && vu(t, i, e[i]);
  return t;
}, u3 = (t, e) => s3(t, n3(e));
function or(t) {
  const e = [];
  return t.forEach((i) => {
    const [r, s] = i.split(":");
    e.push(`${r}:${s}`);
  }), e;
}
function h3(t) {
  const e = [];
  return Object.values(t).forEach((i) => {
    e.push(...or(i.accounts));
  }), e;
}
function l3(t, e) {
  const i = [];
  return Object.values(t).forEach((r) => {
    or(r.accounts).includes(e) && i.push(...r.methods);
  }), i;
}
function f3(t, e) {
  const i = [];
  return Object.values(t).forEach((r) => {
    or(r.accounts).includes(e) && i.push(...r.events);
  }), i;
}
function Mf(t) {
  return t.includes(":");
}
function d3(t) {
  return Mf(t) ? t.split(":")[0] : t;
}
function Eu(t) {
  var e, i, r;
  const s = {};
  if (!Vr(t))
    return s;
  for (const [n, o] of Object.entries(t)) {
    const a = Mf(n) ? [n] : o.chains, c = o.methods || [], u = o.events || [], h = d3(n);
    s[h] = u3(c3({}, s[h]), { chains: xi(a, (e = s[h]) == null ? void 0 : e.chains), methods: xi(c, (i = s[h]) == null ? void 0 : i.methods), events: xi(u, (r = s[h]) == null ? void 0 : r.events) });
  }
  return s;
}
function p3(t) {
  const e = {};
  return t?.forEach((i) => {
    var r;
    const [s, n] = i.split(":");
    e[s] || (e[s] = { accounts: [], chains: [], events: [], methods: [] }), e[s].accounts.push(i), (r = e[s].chains) == null || r.push(`${s}:${n}`);
  }), e;
}
function _u(t, e) {
  e = e.map((r) => r.replace("did:pkh:", ""));
  const i = p3(e);
  for (const [r, s] of Object.entries(i))
    s.methods ? s.methods = xi(s.methods, t) : s.methods = t, s.events = ["chainChanged", "accountsChanged"];
  return i;
}
function g3(t, e) {
  var i, r, s, n, o, a;
  const c = Eu(t), u = Eu(e), h = {}, l = Object.keys(c).concat(Object.keys(u));
  for (const f of l)
    h[f] = { chains: xi((i = c[f]) == null ? void 0 : i.chains, (r = u[f]) == null ? void 0 : r.chains), methods: xi((s = c[f]) == null ? void 0 : s.methods, (n = u[f]) == null ? void 0 : n.methods), events: xi((o = c[f]) == null ? void 0 : o.events, (a = u[f]) == null ? void 0 : a.events) };
  return h;
}
const y3 = { INVALID_METHOD: { message: "Invalid method.", code: 1001 }, INVALID_EVENT: { message: "Invalid event.", code: 1002 }, INVALID_UPDATE_REQUEST: { message: "Invalid update request.", code: 1003 }, INVALID_EXTEND_REQUEST: { message: "Invalid extend request.", code: 1004 }, INVALID_SESSION_SETTLE_REQUEST: { message: "Invalid session settle request.", code: 1005 }, UNAUTHORIZED_METHOD: { message: "Unauthorized method.", code: 3001 }, UNAUTHORIZED_EVENT: { message: "Unauthorized event.", code: 3002 }, UNAUTHORIZED_UPDATE_REQUEST: { message: "Unauthorized update request.", code: 3003 }, UNAUTHORIZED_EXTEND_REQUEST: { message: "Unauthorized extend request.", code: 3004 }, USER_REJECTED: { message: "User rejected.", code: 5e3 }, USER_REJECTED_CHAINS: { message: "User rejected chains.", code: 5001 }, USER_REJECTED_METHODS: { message: "User rejected methods.", code: 5002 }, USER_REJECTED_EVENTS: { message: "User rejected events.", code: 5003 }, UNSUPPORTED_CHAINS: { message: "Unsupported chains.", code: 5100 }, UNSUPPORTED_METHODS: { message: "Unsupported methods.", code: 5101 }, UNSUPPORTED_EVENTS: { message: "Unsupported events.", code: 5102 }, UNSUPPORTED_ACCOUNTS: { message: "Unsupported accounts.", code: 5103 }, UNSUPPORTED_NAMESPACE_KEY: { message: "Unsupported namespace key.", code: 5104 }, USER_DISCONNECTED: { message: "User disconnected.", code: 6e3 }, SESSION_SETTLEMENT_FAILED: { message: "Session settlement failed.", code: 7e3 }, WC_METHOD_UNSUPPORTED: { message: "Unsupported wc_ method.", code: 10001 } }, w3 = { NOT_INITIALIZED: { message: "Not initialized.", code: 1 }, NO_MATCHING_KEY: { message: "No matching key.", code: 2 }, RESTORE_WILL_OVERRIDE: { message: "Restore will override.", code: 3 }, RESUBSCRIBED: { message: "Resubscribed.", code: 4 }, MISSING_OR_INVALID: { message: "Missing or invalid.", code: 5 }, EXPIRED: { message: "Expired.", code: 6 }, UNKNOWN_TYPE: { message: "Unknown type.", code: 7 }, MISMATCHED_TOPIC: { message: "Mismatched topic.", code: 8 }, NON_CONFORMING_NAMESPACES: { message: "Non conforming namespaces.", code: 9 } };
function M(t, e) {
  const { message: i, code: r } = w3[t];
  return { message: e ? `${i} ${e}` : i, code: r };
}
function le(t, e) {
  const { message: i, code: r } = y3[t];
  return { message: e ? `${i} ${e}` : i, code: r };
}
function Qi(t, e) {
  return Array.isArray(t) ? typeof e < "u" && t.length ? t.every(e) : !0 : !1;
}
function Vr(t) {
  return Object.getPrototypeOf(t) === Object.prototype && Object.keys(t).length;
}
function ve(t) {
  return typeof t > "u";
}
function ye(t, e) {
  return e && ve(t) ? !0 : typeof t == "string" && !!t.trim().length;
}
function _a(t, e) {
  return e && ve(t) ? !0 : typeof t == "number" && !isNaN(t);
}
function m3(t, e) {
  const { requiredNamespaces: i } = e, r = Object.keys(t.namespaces), s = Object.keys(i);
  let n = !0;
  return bi(s, r) ? (r.forEach((o) => {
    const { accounts: a, methods: c, events: u } = t.namespaces[o], h = or(a), l = i[o];
    (!bi(ca(o, l), h) || !bi(l.methods, c) || !bi(l.events, u)) && (n = !1);
  }), n) : !1;
}
function Hs(t) {
  return ye(t, !1) && t.includes(":") ? t.split(":").length === 2 : !1;
}
function b3(t) {
  if (ye(t, !1) && t.includes(":")) {
    const e = t.split(":");
    if (e.length === 3) {
      const i = e[0] + ":" + e[1];
      return !!e[2] && Hs(i);
    }
  }
  return !1;
}
function v3(t) {
  function e(i) {
    try {
      return typeof new URL(i) < "u";
    } catch {
      return !1;
    }
  }
  try {
    if (ye(t, !1)) {
      if (e(t))
        return !0;
      const i = Yl(t);
      return e(i);
    }
  } catch {
  }
  return !1;
}
function E3(t) {
  var e;
  return (e = t?.proposer) == null ? void 0 : e.publicKey;
}
function _3(t) {
  return t?.topic;
}
function x3(t, e) {
  let i = null;
  return ye(t?.publicKey, !1) || (i = M("MISSING_OR_INVALID", `${e} controller public key should be a string`)), i;
}
function xu(t) {
  let e = !0;
  return Qi(t) ? t.length && (e = t.every((i) => ye(i, !1))) : e = !1, e;
}
function I3(t, e, i) {
  let r = null;
  return Qi(e) && e.length ? e.forEach((s) => {
    r || Hs(s) || (r = le("UNSUPPORTED_CHAINS", `${i}, chain ${s} should be a string and conform to "namespace:chainId" format`));
  }) : Hs(t) || (r = le("UNSUPPORTED_CHAINS", `${i}, chains must be defined as "namespace:chainId" e.g. "eip155:1": {...} in the namespace key OR as an array of CAIP-2 chainIds e.g. eip155: { chains: ["eip155:1", "eip155:5"] }`)), r;
}
function S3(t, e, i) {
  let r = null;
  return Object.entries(t).forEach(([s, n]) => {
    if (r)
      return;
    const o = I3(s, ca(s, n), `${e} ${i}`);
    o && (r = o);
  }), r;
}
function D3(t, e) {
  let i = null;
  return Qi(t) ? t.forEach((r) => {
    i || b3(r) || (i = le("UNSUPPORTED_ACCOUNTS", `${e}, account ${r} should be a string and conform to "namespace:chainId:address" format`));
  }) : i = le("UNSUPPORTED_ACCOUNTS", `${e}, accounts should be an array of strings conforming to "namespace:chainId:address" format`), i;
}
function A3(t, e) {
  let i = null;
  return Object.values(t).forEach((r) => {
    if (i)
      return;
    const s = D3(r?.accounts, `${e} namespace`);
    s && (i = s);
  }), i;
}
function $3(t, e) {
  let i = null;
  return xu(t?.methods) ? xu(t?.events) || (i = le("UNSUPPORTED_EVENTS", `${e}, events should be an array of strings or empty array for no events`)) : i = le("UNSUPPORTED_METHODS", `${e}, methods should be an array of strings or empty array for no methods`), i;
}
function qf(t, e) {
  let i = null;
  return Object.values(t).forEach((r) => {
    if (i)
      return;
    const s = $3(r, `${e}, namespace`);
    s && (i = s);
  }), i;
}
function O3(t, e, i) {
  let r = null;
  if (t && Vr(t)) {
    const s = qf(t, e);
    s && (r = s);
    const n = S3(t, e, i);
    n && (r = n);
  } else
    r = M("MISSING_OR_INVALID", `${e}, ${i} should be an object with data`);
  return r;
}
function Vn(t, e) {
  let i = null;
  if (t && Vr(t)) {
    const r = qf(t, e);
    r && (i = r);
    const s = A3(t, e);
    s && (i = s);
  } else
    i = M("MISSING_OR_INVALID", `${e}, namespaces should be an object with data`);
  return i;
}
function jf(t) {
  return ye(t.protocol, !0);
}
function T3(t, e) {
  let i = !1;
  return e && !t ? i = !0 : t && Qi(t) && t.length && t.forEach((r) => {
    i = jf(r);
  }), i;
}
function C3(t) {
  return typeof t == "number";
}
function He(t) {
  return typeof t < "u" && typeof t !== null;
}
function P3(t) {
  return !(!t || typeof t != "object" || !t.code || !_a(t.code, !1) || !t.message || !ye(t.message, !1));
}
function R3(t) {
  return !(ve(t) || !ye(t.method, !1));
}
function F3(t) {
  return !(ve(t) || ve(t.result) && ve(t.error) || !_a(t.id, !1) || !ye(t.jsonrpc, !1));
}
function U3(t) {
  return !(ve(t) || !ye(t.name, !1));
}
function Iu(t, e) {
  return !(!Hs(e) || !h3(t).includes(e));
}
function B3(t, e, i) {
  return ye(i, !1) ? l3(t, e).includes(i) : !1;
}
function N3(t, e, i) {
  return ye(i, !1) ? f3(t, e).includes(i) : !1;
}
function Su(t, e, i) {
  let r = null;
  const s = k3(t), n = L3(e), o = Object.keys(s), a = Object.keys(n), c = Du(Object.keys(t)), u = Du(Object.keys(e)), h = c.filter((l) => !u.includes(l));
  return h.length && (r = M("NON_CONFORMING_NAMESPACES", `${i} namespaces keys don't satisfy requiredNamespaces.
      Required: ${h.toString()}
      Received: ${Object.keys(e).toString()}`)), bi(o, a) || (r = M("NON_CONFORMING_NAMESPACES", `${i} namespaces chains don't satisfy required namespaces.
      Required: ${o.toString()}
      Approved: ${a.toString()}`)), Object.keys(e).forEach((l) => {
    if (!l.includes(":") || r)
      return;
    const f = or(e[l].accounts);
    f.includes(l) || (r = M("NON_CONFORMING_NAMESPACES", `${i} namespaces accounts don't satisfy namespace accounts for ${l}
        Required: ${l}
        Approved: ${f.toString()}`));
  }), o.forEach((l) => {
    r || (bi(s[l].methods, n[l].methods) ? bi(s[l].events, n[l].events) || (r = M("NON_CONFORMING_NAMESPACES", `${i} namespaces events don't satisfy namespace events for ${l}`)) : r = M("NON_CONFORMING_NAMESPACES", `${i} namespaces methods don't satisfy namespace methods for ${l}`));
  }), r;
}
function k3(t) {
  const e = {};
  return Object.keys(t).forEach((i) => {
    var r;
    i.includes(":") ? e[i] = t[i] : (r = t[i].chains) == null || r.forEach((s) => {
      e[s] = { methods: t[i].methods, events: t[i].events };
    });
  }), e;
}
function Du(t) {
  return [...new Set(t.map((e) => e.includes(":") ? e.split(":")[0] : e))];
}
function L3(t) {
  const e = {};
  return Object.keys(t).forEach((i) => {
    i.includes(":") ? e[i] = t[i] : or(t[i].accounts)?.forEach((s) => {
      e[s] = { accounts: t[i].accounts.filter((n) => n.includes(`${s}:`)), methods: t[i].methods, events: t[i].events };
    });
  }), e;
}
function M3(t, e) {
  return _a(t, !1) && t <= e.max && t >= e.min;
}
function Au() {
  const t = Xr();
  return new Promise((e) => {
    switch (t) {
      case it.browser:
        e(q3());
        break;
      case it.reactNative:
        e(j3());
        break;
      case it.node:
        e(z3());
        break;
      default:
        e(!0);
    }
  });
}
function q3() {
  return rr() && navigator?.onLine;
}
async function j3() {
  return ci() && typeof global < "u" && global != null && global.NetInfo ? (await (global == null ? void 0 : global.NetInfo.fetch()))?.isConnected : !0;
}
function z3() {
  return !0;
}
function K3(t) {
  switch (Xr()) {
    case it.browser:
      V3(t);
      break;
    case it.reactNative:
      H3(t);
      break;
  }
}
function V3(t) {
  !ci() && rr() && (window.addEventListener("online", () => t(!0)), window.addEventListener("offline", () => t(!1)));
}
function H3(t) {
  ci() && typeof global < "u" && global != null && global.NetInfo && global?.NetInfo.addEventListener((e) => t(e?.isConnected));
}
function W3() {
  var t;
  return rr() && Si() ? ((t = Si()) == null ? void 0 : t.visibilityState) === "visible" : !0;
}
const Hn = {};
class wr {
  static get(e) {
    return Hn[e];
  }
  static set(e, i) {
    Hn[e] = i;
  }
  static delete(e) {
    delete Hn[e];
  }
}
function G3(t) {
  const e = Zr.decode(t);
  if (e.length < 33)
    throw new Error("Too short to contain a public key");
  return e.slice(1, 33);
}
function Y3({ publicKey: t, signature: e, payload: i }) {
  var r;
  const s = Co(i.method), n = 128 | parseInt(((r = i.version) == null ? void 0 : r.toString()) || "4"), o = Q3(i.address), a = i.era === "00" ? new Uint8Array([0]) : Co(i.era);
  if (a.length !== 1 && a.length !== 2)
    throw new Error("Invalid era length");
  const c = parseInt(i.nonce, 16), u = new Uint8Array([c & 255, c >> 8 & 255]), h = BigInt(`0x${Z3(i.tip)}`), l = e_(h), f = new Uint8Array([0, ...t, o, ...e, ...a, ...u, ...l, ...s]), p = X3(f.length + 1);
  return new Uint8Array([...p, n, ...f]);
}
function J3(t) {
  const e = Co(t), i = Fb.blake2b(e, void 0, 32);
  return "0x" + Buffer.from(i).toString("hex");
}
function Co(t) {
  return new Uint8Array(t.replace(/^0x/, "").match(/.{1,2}/g).map((e) => parseInt(e, 16)));
}
function Z3(t) {
  return t.startsWith("0x") ? t.slice(2) : t;
}
function Q3(t) {
  const e = Zr.decode(t)[0];
  return e === 42 ? 0 : e === 60 ? 2 : 1;
}
function X3(t) {
  if (t < 64)
    return new Uint8Array([t << 2]);
  if (t < 16384) {
    const e = t << 2 | 1;
    return new Uint8Array([e & 255, e >> 8 & 255]);
  } else if (t < 1 << 30) {
    const e = t << 2 | 2;
    return new Uint8Array([e & 255, e >> 8 & 255, e >> 16 & 255, e >> 24 & 255]);
  } else
    throw new Error("Compact encoding > 2^30 not supported");
}
function e_(t) {
  if (t < BigInt(1) << BigInt(6))
    return new Uint8Array([Number(t << BigInt(2))]);
  if (t < BigInt(1) << BigInt(14)) {
    const e = t << BigInt(2) | BigInt(1);
    return new Uint8Array([Number(e & BigInt(255)), Number(e >> BigInt(8) & BigInt(255))]);
  } else if (t < BigInt(1) << BigInt(30)) {
    const e = t << BigInt(2) | BigInt(2);
    return new Uint8Array([Number(e & BigInt(255)), Number(e >> BigInt(8) & BigInt(255)), Number(e >> BigInt(16) & BigInt(255)), Number(e >> BigInt(24) & BigInt(255))]);
  } else
    throw new Error("BigInt compact encoding not supported > 2^30");
}
function t_(t) {
  const e = Uint8Array.from(Buffer.from(t.signature, "hex")), i = G3(t.transaction.address), r = Y3({ publicKey: i, signature: e, payload: t.transaction }), s = Buffer.from(r).toString("hex");
  return J3(s);
}
const i_ = "PARSE_ERROR", r_ = "INVALID_REQUEST", s_ = "METHOD_NOT_FOUND", n_ = "INVALID_PARAMS", zf = "INTERNAL_ERROR", xa = "SERVER_ERROR", o_ = [-32700, -32600, -32601, -32602, -32603], Rr = {
  [i_]: { code: -32700, message: "Parse error" },
  [r_]: { code: -32600, message: "Invalid Request" },
  [s_]: { code: -32601, message: "Method not found" },
  [n_]: { code: -32602, message: "Invalid params" },
  [zf]: { code: -32603, message: "Internal error" },
  [xa]: { code: -32e3, message: "Server error" }
}, Kf = xa;
function a_(t) {
  return o_.includes(t);
}
function $u(t) {
  return Object.keys(Rr).includes(t) ? Rr[t] : Rr[Kf];
}
function c_(t) {
  const e = Object.values(Rr).find((i) => i.code === t);
  return e || Rr[Kf];
}
function u_(t, e, i) {
  return t.message.includes("getaddrinfo ENOTFOUND") || t.message.includes("connect ECONNREFUSED") ? new Error(`Unavailable ${i} RPC url at ${e}`) : t;
}
var Vf = {}, Ft = {}, Ou;
function h_() {
  if (Ou)
    return Ft;
  Ou = 1, Object.defineProperty(Ft, "__esModule", { value: !0 }), Ft.isBrowserCryptoAvailable = Ft.getSubtleCrypto = Ft.getBrowerCrypto = void 0;
  function t() {
    return (Ui === null || Ui === void 0 ? void 0 : Ui.crypto) || (Ui === null || Ui === void 0 ? void 0 : Ui.msCrypto) || {};
  }
  Ft.getBrowerCrypto = t;
  function e() {
    const r = t();
    return r.subtle || r.webkitSubtle;
  }
  Ft.getSubtleCrypto = e;
  function i() {
    return !!t() && !!e();
  }
  return Ft.isBrowserCryptoAvailable = i, Ft;
}
var Ut = {}, Tu;
function l_() {
  if (Tu)
    return Ut;
  Tu = 1, Object.defineProperty(Ut, "__esModule", { value: !0 }), Ut.isBrowser = Ut.isNode = Ut.isReactNative = void 0;
  function t() {
    return typeof document > "u" && typeof navigator < "u" && navigator.product === "ReactNative";
  }
  Ut.isReactNative = t;
  function e() {
    return typeof process < "u" && typeof process.versions < "u" && typeof process.versions.node < "u";
  }
  Ut.isNode = e;
  function i() {
    return !t() && !e();
  }
  return Ut.isBrowser = i, Ut;
}
(function(t) {
  Object.defineProperty(t, "__esModule", { value: !0 });
  const e = Wr;
  e.__exportStar(h_(), t), e.__exportStar(l_(), t);
})(Vf);
function It(t = 3) {
  const e = Date.now() * Math.pow(10, t), i = Math.floor(Math.random() * Math.pow(10, t));
  return e + i;
}
function ni(t = 6) {
  return BigInt(It(t));
}
function Lt(t, e, i) {
  return {
    id: i || It(),
    jsonrpc: "2.0",
    method: t,
    params: e
  };
}
function Hr(t, e) {
  return {
    id: t,
    jsonrpc: "2.0",
    result: e
  };
}
function hn(t, e, i) {
  return {
    id: t,
    jsonrpc: "2.0",
    error: f_(e, i)
  };
}
function f_(t, e) {
  return typeof t > "u" ? $u(zf) : (typeof t == "string" && (t = Object.assign(Object.assign({}, $u(xa)), { message: t })), typeof e < "u" && (t.data = e), a_(t.code) && (t = c_(t.code)), t);
}
class Hf {
}
let d_ = class extends Hf {
  constructor(e) {
    super();
  }
}, p_ = class extends Hf {
  constructor() {
    super();
  }
};
class g_ extends p_ {
  constructor(e) {
    super();
  }
}
const y_ = "^wss?:";
function w_(t) {
  const e = t.match(new RegExp(/^\w+:/, "gi"));
  if (!(!e || !e.length))
    return e[0];
}
function m_(t, e) {
  const i = w_(t);
  return typeof i > "u" ? !1 : new RegExp(e).test(i);
}
function Cu(t) {
  return m_(t, y_);
}
function b_(t) {
  return new RegExp("wss?://localhost(:d{2,5})?").test(t);
}
function Wf(t) {
  return typeof t == "object" && "id" in t && "jsonrpc" in t && t.jsonrpc === "2.0";
}
function Ia(t) {
  return Wf(t) && "method" in t;
}
function ln(t) {
  return Wf(t) && (St(t) || ct(t));
}
function St(t) {
  return "result" in t;
}
function ct(t) {
  return "error" in t;
}
let Gf = class extends g_ {
  constructor(e) {
    super(e), this.events = new rt.EventEmitter(), this.hasRegisteredEventListeners = !1, this.connection = this.setConnection(e), this.connection.connected && this.registerEventListeners();
  }
  async connect(e = this.connection) {
    await this.open(e);
  }
  async disconnect() {
    await this.close();
  }
  on(e, i) {
    this.events.on(e, i);
  }
  once(e, i) {
    this.events.once(e, i);
  }
  off(e, i) {
    this.events.off(e, i);
  }
  removeListener(e, i) {
    this.events.removeListener(e, i);
  }
  async request(e, i) {
    return this.requestStrict(Lt(e.method, e.params || [], e.id || ni().toString()), i);
  }
  async requestStrict(e, i) {
    return new Promise(async (r, s) => {
      if (!this.connection.connected)
        try {
          await this.open();
        } catch (n) {
          s(n);
        }
      this.events.on(`${e.id}`, (n) => {
        ct(n) ? s(n.error) : r(n.result);
      });
      try {
        await this.connection.send(e, i);
      } catch (n) {
        s(n);
      }
    });
  }
  setConnection(e = this.connection) {
    return e;
  }
  onPayload(e) {
    this.events.emit("payload", e), ln(e) ? this.events.emit(`${e.id}`, e) : this.events.emit("message", { type: e.method, data: e.params });
  }
  onClose(e) {
    e && e.code === 3e3 && this.events.emit("error", new Error(`WebSocket connection closed abnormally with code: ${e.code} ${e.reason ? `(${e.reason})` : ""}`)), this.events.emit("disconnect");
  }
  async open(e = this.connection) {
    this.connection === e && this.connection.connected || (this.connection.connected && this.close(), typeof e == "string" && (await this.connection.open(e), e = this.connection), this.connection = this.setConnection(e), await this.connection.open(), this.registerEventListeners(), this.events.emit("connect"));
  }
  async close() {
    await this.connection.close();
  }
  registerEventListeners() {
    this.hasRegisteredEventListeners || (this.connection.on("payload", (e) => this.onPayload(e)), this.connection.on("close", (e) => this.onClose(e)), this.connection.on("error", (e) => this.events.emit("error", e)), this.connection.on("register_error", (e) => this.onClose()), this.hasRegisteredEventListeners = !0);
  }
};
const v_ = () => typeof WebSocket < "u" ? WebSocket : typeof global < "u" && typeof global.WebSocket < "u" ? global.WebSocket : typeof window < "u" && typeof window.WebSocket < "u" ? window.WebSocket : typeof self < "u" && typeof self.WebSocket < "u" ? self.WebSocket : require("ws"), E_ = () => typeof WebSocket < "u" || typeof global < "u" && typeof global.WebSocket < "u" || typeof window < "u" && typeof window.WebSocket < "u" || typeof self < "u" && typeof self.WebSocket < "u", Pu = (t) => t.split("?")[0], Ru = 10, __ = v_();
let x_ = class {
  constructor(e) {
    if (this.url = e, this.events = new rt.EventEmitter(), this.registering = !1, !Cu(e))
      throw new Error(`Provided URL is not compatible with WebSocket connection: ${e}`);
    this.url = e;
  }
  get connected() {
    return typeof this.socket < "u";
  }
  get connecting() {
    return this.registering;
  }
  on(e, i) {
    this.events.on(e, i);
  }
  once(e, i) {
    this.events.once(e, i);
  }
  off(e, i) {
    this.events.off(e, i);
  }
  removeListener(e, i) {
    this.events.removeListener(e, i);
  }
  async open(e = this.url) {
    await this.register(e);
  }
  async close() {
    return new Promise((e, i) => {
      if (typeof this.socket > "u") {
        i(new Error("Connection already closed"));
        return;
      }
      this.socket.onclose = (r) => {
        this.onClose(r), e();
      }, this.socket.close();
    });
  }
  async send(e) {
    typeof this.socket > "u" && (this.socket = await this.register());
    try {
      this.socket.send(Ii(e));
    } catch (i) {
      this.onError(e.id, i);
    }
  }
  register(e = this.url) {
    if (!Cu(e))
      throw new Error(`Provided URL is not compatible with WebSocket connection: ${e}`);
    if (this.registering) {
      const i = this.events.getMaxListeners();
      return (this.events.listenerCount("register_error") >= i || this.events.listenerCount("open") >= i) && this.events.setMaxListeners(i + 1), new Promise((r, s) => {
        this.events.once("register_error", (n) => {
          this.resetMaxListeners(), s(n);
        }), this.events.once("open", () => {
          if (this.resetMaxListeners(), typeof this.socket > "u")
            return s(new Error("WebSocket connection is missing or invalid"));
          r(this.socket);
        });
      });
    }
    return this.url = e, this.registering = !0, new Promise((i, r) => {
      const s = Vf.isReactNative() ? void 0 : { rejectUnauthorized: !b_(e) }, n = new __(e, [], s);
      E_() ? n.onerror = (o) => {
        const a = o;
        r(this.emitError(a.error));
      } : n.on("error", (o) => {
        r(this.emitError(o));
      }), n.onopen = () => {
        this.onOpen(n), i(n);
      };
    });
  }
  onOpen(e) {
    e.onmessage = (i) => this.onPayload(i), e.onclose = (i) => this.onClose(i), this.socket = e, this.registering = !1, this.events.emit("open");
  }
  onClose(e) {
    this.socket = void 0, this.registering = !1, this.events.emit("close", e);
  }
  onPayload(e) {
    if (typeof e.data > "u")
      return;
    const i = typeof e.data == "string" ? Yi(e.data) : e.data;
    this.events.emit("payload", i);
  }
  onError(e, i) {
    const r = this.parseError(i), s = r.message || r.toString(), n = hn(e, s);
    this.events.emit("payload", n);
  }
  parseError(e, i = this.url) {
    return u_(e, Pu(i), "WS");
  }
  resetMaxListeners() {
    this.events.getMaxListeners() > Ru && this.events.setMaxListeners(Ru);
  }
  emitError(e) {
    const i = this.parseError(new Error(e?.message || `WebSocket connection failed for host: ${Pu(this.url)}`));
    return this.events.emit("register_error", i), i;
  }
};
const Yf = "wc", Jf = 2, Ws = "core", Ot = `${Yf}@2:${Ws}:`, I_ = { name: Ws, logger: "error" }, S_ = { database: ":memory:" }, D_ = "crypto", Fu = "client_ed25519_seed", A_ = L.ONE_DAY, $_ = "keychain", O_ = "0.3", T_ = "messages", C_ = "0.3", P_ = L.SIX_HOURS, R_ = "publisher", Zf = "irn", F_ = "error", Qf = "wss://relay.walletconnect.org", U_ = "relayer", de = { message: "relayer_message", message_ack: "relayer_message_ack", connect: "relayer_connect", disconnect: "relayer_disconnect", error: "relayer_error", connection_stalled: "relayer_connection_stalled", transport_closed: "relayer_transport_closed", publish: "relayer_publish" }, B_ = "_subscription", st = { payload: "payload", connect: "connect", disconnect: "disconnect", error: "error" }, N_ = 0.1, Po = "2.21.8", he = { link_mode: "link_mode", relay: "relay" }, Ts = { inbound: "inbound", outbound: "outbound" }, k_ = "0.3", L_ = "WALLETCONNECT_CLIENT_ID", Uu = "WALLETCONNECT_LINK_MODE_APPS", et = { created: "subscription_created", deleted: "subscription_deleted", expired: "subscription_expired", disabled: "subscription_disabled", sync: "subscription_sync", resubscribed: "subscription_resubscribed" }, M_ = "subscription", q_ = "0.3", j_ = "pairing", z_ = "0.3", mr = { wc_pairingDelete: { req: { ttl: L.ONE_DAY, prompt: !1, tag: 1e3 }, res: { ttl: L.ONE_DAY, prompt: !1, tag: 1001 } }, wc_pairingPing: { req: { ttl: L.THIRTY_SECONDS, prompt: !1, tag: 1002 }, res: { ttl: L.THIRTY_SECONDS, prompt: !1, tag: 1003 } }, unregistered_method: { req: { ttl: L.ONE_DAY, prompt: !1, tag: 0 }, res: { ttl: L.ONE_DAY, prompt: !1, tag: 0 } } }, mi = { create: "pairing_create", expire: "pairing_expire", delete: "pairing_delete", ping: "pairing_ping" }, pt = { created: "history_created", updated: "history_updated", deleted: "history_deleted", sync: "history_sync" }, K_ = "history", V_ = "0.3", H_ = "expirer", ot = { created: "expirer_created", deleted: "expirer_deleted", expired: "expirer_expired", sync: "expirer_sync" }, W_ = "0.3", G_ = "verify-api", Y_ = "https://verify.walletconnect.com", Xf = "https://verify.walletconnect.org", Fr = Xf, J_ = `${Fr}/v3`, Z_ = [Y_, Xf], Q_ = "echo", X_ = "https://echo.walletconnect.com", xt = { pairing_started: "pairing_started", pairing_uri_validation_success: "pairing_uri_validation_success", pairing_uri_not_expired: "pairing_uri_not_expired", store_new_pairing: "store_new_pairing", subscribing_pairing_topic: "subscribing_pairing_topic", subscribe_pairing_topic_success: "subscribe_pairing_topic_success", existing_pairing: "existing_pairing", pairing_not_expired: "pairing_not_expired", emit_inactive_pairing: "emit_inactive_pairing", emit_session_proposal: "emit_session_proposal", subscribing_to_pairing_topic: "subscribing_to_pairing_topic" }, Nt = { no_wss_connection: "no_wss_connection", no_internet_connection: "no_internet_connection", malformed_pairing_uri: "malformed_pairing_uri", active_pairing_already_exists: "active_pairing_already_exists", subscribe_pairing_topic_failure: "subscribe_pairing_topic_failure", pairing_expired: "pairing_expired", proposal_expired: "proposal_expired", proposal_listener_not_found: "proposal_listener_not_found" }, Xt = { session_approve_started: "session_approve_started", proposal_not_expired: "proposal_not_expired", session_namespaces_validation_success: "session_namespaces_validation_success", create_session_topic: "create_session_topic", subscribing_session_topic: "subscribing_session_topic", subscribe_session_topic_success: "subscribe_session_topic_success", publishing_session_approve: "publishing_session_approve", session_approve_publish_success: "session_approve_publish_success", store_session: "store_session", publishing_session_settle: "publishing_session_settle", session_settle_publish_success: "session_settle_publish_success" }, br = { no_internet_connection: "no_internet_connection", no_wss_connection: "no_wss_connection", proposal_expired: "proposal_expired", subscribe_session_topic_failure: "subscribe_session_topic_failure", session_approve_publish_failure: "session_approve_publish_failure", session_settle_publish_failure: "session_settle_publish_failure", session_approve_namespace_validation_failure: "session_approve_namespace_validation_failure", proposal_not_found: "proposal_not_found" }, di = { authenticated_session_approve_started: "authenticated_session_approve_started", authenticated_session_not_expired: "authenticated_session_not_expired", chains_caip2_compliant: "chains_caip2_compliant", chains_evm_compliant: "chains_evm_compliant", create_authenticated_session_topic: "create_authenticated_session_topic", cacaos_verified: "cacaos_verified", store_authenticated_session: "store_authenticated_session", subscribing_authenticated_session_topic: "subscribing_authenticated_session_topic", subscribe_authenticated_session_topic_success: "subscribe_authenticated_session_topic_success", publishing_authenticated_session_approve: "publishing_authenticated_session_approve", authenticated_session_approve_publish_success: "authenticated_session_approve_publish_success" }, vr = { no_internet_connection: "no_internet_connection", no_wss_connection: "no_wss_connection", missing_session_authenticate_request: "missing_session_authenticate_request", session_authenticate_request_expired: "session_authenticate_request_expired", chains_caip2_compliant_failure: "chains_caip2_compliant_failure", chains_evm_compliant_failure: "chains_evm_compliant_failure", invalid_cacao: "invalid_cacao", subscribe_authenticated_session_topic_failure: "subscribe_authenticated_session_topic_failure", authenticated_session_approve_publish_failure: "authenticated_session_approve_publish_failure", authenticated_session_pending_request_not_found: "authenticated_session_pending_request_not_found" }, ex = 0.1, tx = "event-client", ix = 86400, rx = "https://pulse.walletconnect.org/batch";
function sx(t, e) {
  if (t.length >= 255)
    throw new TypeError("Alphabet too long");
  for (var i = new Uint8Array(256), r = 0; r < i.length; r++)
    i[r] = 255;
  for (var s = 0; s < t.length; s++) {
    var n = t.charAt(s), o = n.charCodeAt(0);
    if (i[o] !== 255)
      throw new TypeError(n + " is ambiguous");
    i[o] = s;
  }
  var a = t.length, c = t.charAt(0), u = Math.log(a) / Math.log(256), h = Math.log(256) / Math.log(a);
  function l(d) {
    if (d instanceof Uint8Array || (ArrayBuffer.isView(d) ? d = new Uint8Array(d.buffer, d.byteOffset, d.byteLength) : Array.isArray(d) && (d = Uint8Array.from(d))), !(d instanceof Uint8Array))
      throw new TypeError("Expected Uint8Array");
    if (d.length === 0)
      return "";
    for (var g = 0, y = 0, E = 0, v = d.length; E !== v && d[E] === 0; )
      E++, g++;
    for (var m = (v - E) * h + 1 >>> 0, D = new Uint8Array(m); E !== v; ) {
      for (var I = d[E], R = 0, B = m - 1; (I !== 0 || R < y) && B !== -1; B--, R++)
        I += 256 * D[B] >>> 0, D[B] = I % a >>> 0, I = I / a >>> 0;
      if (I !== 0)
        throw new Error("Non-zero carry");
      y = R, E++;
    }
    for (var C = m - y; C !== m && D[C] === 0; )
      C++;
    for (var w = c.repeat(g); C < m; ++C)
      w += t.charAt(D[C]);
    return w;
  }
  function f(d) {
    if (typeof d != "string")
      throw new TypeError("Expected String");
    if (d.length === 0)
      return new Uint8Array();
    var g = 0;
    if (d[g] !== " ") {
      for (var y = 0, E = 0; d[g] === c; )
        y++, g++;
      for (var v = (d.length - g) * u + 1 >>> 0, m = new Uint8Array(v); d[g]; ) {
        var D = i[d.charCodeAt(g)];
        if (D === 255)
          return;
        for (var I = 0, R = v - 1; (D !== 0 || I < E) && R !== -1; R--, I++)
          D += a * m[R] >>> 0, m[R] = D % 256 >>> 0, D = D / 256 >>> 0;
        if (D !== 0)
          throw new Error("Non-zero carry");
        E = I, g++;
      }
      if (d[g] !== " ") {
        for (var B = v - E; B !== v && m[B] === 0; )
          B++;
        for (var C = new Uint8Array(y + (v - B)), w = y; B !== v; )
          C[w++] = m[B++];
        return C;
      }
    }
  }
  function p(d) {
    var g = f(d);
    if (g)
      return g;
    throw new Error(`Non-${e} character`);
  }
  return { encode: l, decodeUnsafe: f, decode: p };
}
var nx = sx, ox = nx;
const ed = (t) => {
  if (t instanceof Uint8Array && t.constructor.name === "Uint8Array")
    return t;
  if (t instanceof ArrayBuffer)
    return new Uint8Array(t);
  if (ArrayBuffer.isView(t))
    return new Uint8Array(t.buffer, t.byteOffset, t.byteLength);
  throw new Error("Unknown type, must be binary type");
}, ax = (t) => new TextEncoder().encode(t), cx = (t) => new TextDecoder().decode(t);
class ux {
  constructor(e, i, r) {
    this.name = e, this.prefix = i, this.baseEncode = r;
  }
  encode(e) {
    if (e instanceof Uint8Array)
      return `${this.prefix}${this.baseEncode(e)}`;
    throw Error("Unknown type, must be binary type");
  }
}
class hx {
  constructor(e, i, r) {
    if (this.name = e, this.prefix = i, i.codePointAt(0) === void 0)
      throw new Error("Invalid prefix character");
    this.prefixCodePoint = i.codePointAt(0), this.baseDecode = r;
  }
  decode(e) {
    if (typeof e == "string") {
      if (e.codePointAt(0) !== this.prefixCodePoint)
        throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);
      return this.baseDecode(e.slice(this.prefix.length));
    } else
      throw Error("Can only multibase decode strings");
  }
  or(e) {
    return td(this, e);
  }
}
class lx {
  constructor(e) {
    this.decoders = e;
  }
  or(e) {
    return td(this, e);
  }
  decode(e) {
    const i = e[0], r = this.decoders[i];
    if (r)
      return r.decode(e);
    throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`);
  }
}
const td = (t, e) => new lx({ ...t.decoders || { [t.prefix]: t }, ...e.decoders || { [e.prefix]: e } });
class fx {
  constructor(e, i, r, s) {
    this.name = e, this.prefix = i, this.baseEncode = r, this.baseDecode = s, this.encoder = new ux(e, i, r), this.decoder = new hx(e, i, s);
  }
  encode(e) {
    return this.encoder.encode(e);
  }
  decode(e) {
    return this.decoder.decode(e);
  }
}
const fn = ({ name: t, prefix: e, encode: i, decode: r }) => new fx(t, e, i, r), rs = ({ prefix: t, name: e, alphabet: i }) => {
  const { encode: r, decode: s } = ox(i, e);
  return fn({ prefix: t, name: e, encode: r, decode: (n) => ed(s(n)) });
}, dx = (t, e, i, r) => {
  const s = {};
  for (let h = 0; h < e.length; ++h)
    s[e[h]] = h;
  let n = t.length;
  for (; t[n - 1] === "="; )
    --n;
  const o = new Uint8Array(n * i / 8 | 0);
  let a = 0, c = 0, u = 0;
  for (let h = 0; h < n; ++h) {
    const l = s[t[h]];
    if (l === void 0)
      throw new SyntaxError(`Non-${r} character`);
    c = c << i | l, a += i, a >= 8 && (a -= 8, o[u++] = 255 & c >> a);
  }
  if (a >= i || 255 & c << 8 - a)
    throw new SyntaxError("Unexpected end of data");
  return o;
}, px = (t, e, i) => {
  const r = e[e.length - 1] === "=", s = (1 << i) - 1;
  let n = "", o = 0, a = 0;
  for (let c = 0; c < t.length; ++c)
    for (a = a << 8 | t[c], o += 8; o > i; )
      o -= i, n += e[s & a >> o];
  if (o && (n += e[s & a << i - o]), r)
    for (; n.length * i & 7; )
      n += "=";
  return n;
}, Pe = ({ name: t, prefix: e, bitsPerChar: i, alphabet: r }) => fn({ prefix: e, name: t, encode(s) {
  return px(s, r, i);
}, decode(s) {
  return dx(s, r, i, t);
} }), gx = fn({ prefix: "\0", name: "identity", encode: (t) => cx(t), decode: (t) => ax(t) });
var yx = Object.freeze({ __proto__: null, identity: gx });
const wx = Pe({ prefix: "0", name: "base2", alphabet: "01", bitsPerChar: 1 });
var mx = Object.freeze({ __proto__: null, base2: wx });
const bx = Pe({ prefix: "7", name: "base8", alphabet: "01234567", bitsPerChar: 3 });
var vx = Object.freeze({ __proto__: null, base8: bx });
const Ex = rs({ prefix: "9", name: "base10", alphabet: "0123456789" });
var _x = Object.freeze({ __proto__: null, base10: Ex });
const xx = Pe({ prefix: "f", name: "base16", alphabet: "0123456789abcdef", bitsPerChar: 4 }), Ix = Pe({ prefix: "F", name: "base16upper", alphabet: "0123456789ABCDEF", bitsPerChar: 4 });
var Sx = Object.freeze({ __proto__: null, base16: xx, base16upper: Ix });
const Dx = Pe({ prefix: "b", name: "base32", alphabet: "abcdefghijklmnopqrstuvwxyz234567", bitsPerChar: 5 }), Ax = Pe({ prefix: "B", name: "base32upper", alphabet: "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567", bitsPerChar: 5 }), $x = Pe({ prefix: "c", name: "base32pad", alphabet: "abcdefghijklmnopqrstuvwxyz234567=", bitsPerChar: 5 }), Ox = Pe({ prefix: "C", name: "base32padupper", alphabet: "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=", bitsPerChar: 5 }), Tx = Pe({ prefix: "v", name: "base32hex", alphabet: "0123456789abcdefghijklmnopqrstuv", bitsPerChar: 5 }), Cx = Pe({ prefix: "V", name: "base32hexupper", alphabet: "0123456789ABCDEFGHIJKLMNOPQRSTUV", bitsPerChar: 5 }), Px = Pe({ prefix: "t", name: "base32hexpad", alphabet: "0123456789abcdefghijklmnopqrstuv=", bitsPerChar: 5 }), Rx = Pe({ prefix: "T", name: "base32hexpadupper", alphabet: "0123456789ABCDEFGHIJKLMNOPQRSTUV=", bitsPerChar: 5 }), Fx = Pe({ prefix: "h", name: "base32z", alphabet: "ybndrfg8ejkmcpqxot1uwisza345h769", bitsPerChar: 5 });
var Ux = Object.freeze({ __proto__: null, base32: Dx, base32upper: Ax, base32pad: $x, base32padupper: Ox, base32hex: Tx, base32hexupper: Cx, base32hexpad: Px, base32hexpadupper: Rx, base32z: Fx });
const Bx = rs({ prefix: "k", name: "base36", alphabet: "0123456789abcdefghijklmnopqrstuvwxyz" }), Nx = rs({ prefix: "K", name: "base36upper", alphabet: "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ" });
var kx = Object.freeze({ __proto__: null, base36: Bx, base36upper: Nx });
const Lx = rs({ name: "base58btc", prefix: "z", alphabet: "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" }), Mx = rs({ name: "base58flickr", prefix: "Z", alphabet: "123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ" });
var qx = Object.freeze({ __proto__: null, base58btc: Lx, base58flickr: Mx });
const jx = Pe({ prefix: "m", name: "base64", alphabet: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/", bitsPerChar: 6 }), zx = Pe({ prefix: "M", name: "base64pad", alphabet: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=", bitsPerChar: 6 }), Kx = Pe({ prefix: "u", name: "base64url", alphabet: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_", bitsPerChar: 6 }), Vx = Pe({ prefix: "U", name: "base64urlpad", alphabet: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=", bitsPerChar: 6 });
var Hx = Object.freeze({ __proto__: null, base64: jx, base64pad: zx, base64url: Kx, base64urlpad: Vx });
const id = Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"), Wx = id.reduce((t, e, i) => (t[i] = e, t), []), Gx = id.reduce((t, e, i) => (t[e.codePointAt(0)] = i, t), []);
function Yx(t) {
  return t.reduce((e, i) => (e += Wx[i], e), "");
}
function Jx(t) {
  const e = [];
  for (const i of t) {
    const r = Gx[i.codePointAt(0)];
    if (r === void 0)
      throw new Error(`Non-base256emoji character: ${i}`);
    e.push(r);
  }
  return new Uint8Array(e);
}
const Zx = fn({ prefix: "🚀", name: "base256emoji", encode: Yx, decode: Jx });
var Qx = Object.freeze({ __proto__: null, base256emoji: Zx }), Xx = rd, Bu = 128, e8 = 127, t8 = ~e8, i8 = Math.pow(2, 31);
function rd(t, e, i) {
  e = e || [], i = i || 0;
  for (var r = i; t >= i8; )
    e[i++] = t & 255 | Bu, t /= 128;
  for (; t & t8; )
    e[i++] = t & 255 | Bu, t >>>= 7;
  return e[i] = t | 0, rd.bytes = i - r + 1, e;
}
var r8 = Ro, s8 = 128, Nu = 127;
function Ro(t, r) {
  var i = 0, r = r || 0, s = 0, n = r, o, a = t.length;
  do {
    if (n >= a)
      throw Ro.bytes = 0, new RangeError("Could not decode varint");
    o = t[n++], i += s < 28 ? (o & Nu) << s : (o & Nu) * Math.pow(2, s), s += 7;
  } while (o >= s8);
  return Ro.bytes = n - r, i;
}
var n8 = Math.pow(2, 7), o8 = Math.pow(2, 14), a8 = Math.pow(2, 21), c8 = Math.pow(2, 28), u8 = Math.pow(2, 35), h8 = Math.pow(2, 42), l8 = Math.pow(2, 49), f8 = Math.pow(2, 56), d8 = Math.pow(2, 63), p8 = function(t) {
  return t < n8 ? 1 : t < o8 ? 2 : t < a8 ? 3 : t < c8 ? 4 : t < u8 ? 5 : t < h8 ? 6 : t < l8 ? 7 : t < f8 ? 8 : t < d8 ? 9 : 10;
}, g8 = { encode: Xx, decode: r8, encodingLength: p8 }, sd = g8;
const ku = (t, e, i = 0) => (sd.encode(t, e, i), e), Lu = (t) => sd.encodingLength(t), Fo = (t, e) => {
  const i = e.byteLength, r = Lu(t), s = r + Lu(i), n = new Uint8Array(s + i);
  return ku(t, n, 0), ku(i, n, r), n.set(e, s), new y8(t, i, e, n);
};
class y8 {
  constructor(e, i, r, s) {
    this.code = e, this.size = i, this.digest = r, this.bytes = s;
  }
}
const nd = ({ name: t, code: e, encode: i }) => new w8(t, e, i);
class w8 {
  constructor(e, i, r) {
    this.name = e, this.code = i, this.encode = r;
  }
  digest(e) {
    if (e instanceof Uint8Array) {
      const i = this.encode(e);
      return i instanceof Uint8Array ? Fo(this.code, i) : i.then((r) => Fo(this.code, r));
    } else
      throw Error("Unknown type, must be binary type");
  }
}
const od = (t) => async (e) => new Uint8Array(await crypto.subtle.digest(t, e)), m8 = nd({ name: "sha2-256", code: 18, encode: od("SHA-256") }), b8 = nd({ name: "sha2-512", code: 19, encode: od("SHA-512") });
var v8 = Object.freeze({ __proto__: null, sha256: m8, sha512: b8 });
const ad = 0, E8 = "identity", cd = ed, _8 = (t) => Fo(ad, cd(t)), x8 = { code: ad, name: E8, encode: cd, digest: _8 };
var I8 = Object.freeze({ __proto__: null, identity: x8 });
new TextEncoder(), new TextDecoder();
const Mu = { ...yx, ...mx, ...vx, ..._x, ...Sx, ...Ux, ...kx, ...qx, ...Hx, ...Qx };
({ ...v8, ...I8 });
function ud(t) {
  return globalThis.Buffer != null ? new Uint8Array(t.buffer, t.byteOffset, t.byteLength) : t;
}
function S8(t = 0) {
  return globalThis.Buffer != null && globalThis.Buffer.allocUnsafe != null ? ud(globalThis.Buffer.allocUnsafe(t)) : new Uint8Array(t);
}
function hd(t, e, i, r) {
  return { name: t, prefix: e, encoder: { name: t, prefix: e, encode: i }, decoder: { decode: r } };
}
const qu = hd("utf8", "u", (t) => "u" + new TextDecoder("utf8").decode(t), (t) => new TextEncoder().encode(t.substring(1))), Wn = hd("ascii", "a", (t) => {
  let e = "a";
  for (let i = 0; i < t.length; i++)
    e += String.fromCharCode(t[i]);
  return e;
}, (t) => {
  t = t.substring(1);
  const e = S8(t.length);
  for (let i = 0; i < t.length; i++)
    e[i] = t.charCodeAt(i);
  return e;
}), D8 = { utf8: qu, "utf-8": qu, hex: Mu.base16, latin1: Wn, ascii: Wn, binary: Wn, ...Mu };
function A8(t, e = "utf8") {
  const i = D8[e];
  if (!i)
    throw new Error(`Unsupported encoding "${e}"`);
  return (e === "utf8" || e === "utf-8") && globalThis.Buffer != null && globalThis.Buffer.from != null ? ud(globalThis.Buffer.from(t, "utf-8")) : i.decoder.decode(`${i.prefix}${t}`);
}
var $8 = Object.defineProperty, O8 = (t, e, i) => e in t ? $8(t, e, { enumerable: !0, configurable: !0, writable: !0, value: i }) : t[e] = i, Et = (t, e, i) => O8(t, typeof e != "symbol" ? e + "" : e, i);
class T8 {
  constructor(e, i) {
    this.core = e, this.logger = i, Et(this, "keychain", /* @__PURE__ */ new Map()), Et(this, "name", $_), Et(this, "version", O_), Et(this, "initialized", !1), Et(this, "storagePrefix", Ot), Et(this, "init", async () => {
      if (!this.initialized) {
        const r = await this.getKeyChain();
        typeof r < "u" && (this.keychain = r), this.initialized = !0;
      }
    }), Et(this, "has", (r) => (this.isInitialized(), this.keychain.has(r))), Et(this, "set", async (r, s) => {
      this.isInitialized(), this.keychain.set(r, s), await this.persist();
    }), Et(this, "get", (r) => {
      this.isInitialized();
      const s = this.keychain.get(r);
      if (typeof s > "u") {
        const { message: n } = M("NO_MATCHING_KEY", `${this.name}: ${r}`);
        throw new Error(n);
      }
      return s;
    }), Et(this, "del", async (r) => {
      this.isInitialized(), this.keychain.delete(r), await this.persist();
    }), this.core = e, this.logger = je(i, this.name);
  }
  get context() {
    return Qe(this.logger);
  }
  get storageKey() {
    return this.storagePrefix + this.version + this.core.customStoragePrefix + "//" + this.name;
  }
  async setKeyChain(e) {
    await this.core.storage.setItem(this.storageKey, bo(e));
  }
  async getKeyChain() {
    const e = await this.core.storage.getItem(this.storageKey);
    return typeof e < "u" ? vo(e) : void 0;
  }
  async persist() {
    await this.setKeyChain(this.keychain);
  }
  isInitialized() {
    if (!this.initialized) {
      const { message: e } = M("NOT_INITIALIZED", this.name);
      throw new Error(e);
    }
  }
}
var C8 = Object.defineProperty, P8 = (t, e, i) => e in t ? C8(t, e, { enumerable: !0, configurable: !0, writable: !0, value: i }) : t[e] = i, Ae = (t, e, i) => P8(t, typeof e != "symbol" ? e + "" : e, i);
class R8 {
  constructor(e, i, r) {
    this.core = e, this.logger = i, Ae(this, "name", D_), Ae(this, "keychain"), Ae(this, "randomSessionIdentifier", To()), Ae(this, "initialized", !1), Ae(this, "init", async () => {
      this.initialized || (await this.keychain.init(), this.initialized = !0);
    }), Ae(this, "hasKeys", (s) => (this.isInitialized(), this.keychain.has(s))), Ae(this, "getClientId", async () => {
      this.isInitialized();
      const s = await this.getClientSeed(), n = vc(s);
      return el(n.publicKey);
    }), Ae(this, "generateKeyPair", () => {
      this.isInitialized();
      const s = KE();
      return this.setPrivateKey(s.publicKey, s.privateKey);
    }), Ae(this, "signJWT", async (s) => {
      this.isInitialized();
      const n = await this.getClientSeed(), o = vc(n), a = this.randomSessionIdentifier;
      return await R1(a, s, A_, o);
    }), Ae(this, "generateSharedKey", (s, n, o) => {
      this.isInitialized();
      const a = this.getPrivateKey(s), c = VE(a, n);
      return this.setSymKey(c, o);
    }), Ae(this, "setSymKey", async (s, n) => {
      this.isInitialized();
      const o = n || Os(s);
      return await this.keychain.set(o, s), o;
    }), Ae(this, "deleteKeyPair", async (s) => {
      this.isInitialized(), await this.keychain.del(s);
    }), Ae(this, "deleteSymKey", async (s) => {
      this.isInitialized(), await this.keychain.del(s);
    }), Ae(this, "encode", async (s, n, o) => {
      this.isInitialized();
      const a = Lf(o), c = Ii(n);
      if (yu(a))
        return GE(c, o?.encoding);
      if (gu(a)) {
        const f = a.senderPublicKey, p = a.receiverPublicKey;
        s = await this.generateSharedKey(f, p);
      }
      const u = this.getSymKey(s), { type: h, senderPublicKey: l } = a;
      return HE({ type: h, symKey: u, message: c, senderPublicKey: l, encoding: o?.encoding });
    }), Ae(this, "decode", async (s, n, o) => {
      this.isInitialized();
      const a = JE(n, o);
      if (yu(a)) {
        const c = YE(n, o?.encoding);
        return Yi(c);
      }
      if (gu(a)) {
        const c = a.receiverPublicKey, u = a.senderPublicKey;
        s = await this.generateSharedKey(c, u);
      }
      try {
        const c = this.getSymKey(s), u = WE({ symKey: c, encoded: n, encoding: o?.encoding });
        return Yi(u);
      } catch (c) {
        this.logger.error(`Failed to decode message from topic: '${s}', clientId: '${await this.getClientId()}'`), this.logger.error(c);
      }
    }), Ae(this, "getPayloadType", (s, n = Ye) => {
      const o = Kr({ encoded: s, encoding: n });
      return $i(o.type);
    }), Ae(this, "getPayloadSenderPublicKey", (s, n = Ye) => {
      const o = Kr({ encoded: s, encoding: n });
      return o.senderPublicKey ? Ze(o.senderPublicKey, qe) : void 0;
    }), this.core = e, this.logger = je(i, this.name), this.keychain = r || new T8(this.core, this.logger);
  }
  get context() {
    return Qe(this.logger);
  }
  async setPrivateKey(e, i) {
    return await this.keychain.set(e, i), e;
  }
  getPrivateKey(e) {
    return this.keychain.get(e);
  }
  async getClientSeed() {
    let e = "";
    try {
      e = this.keychain.get(Fu);
    } catch {
      e = To(), await this.keychain.set(Fu, e);
    }
    return A8(e, "base16");
  }
  getSymKey(e) {
    return this.keychain.get(e);
  }
  isInitialized() {
    if (!this.initialized) {
      const { message: e } = M("NOT_INITIALIZED", this.name);
      throw new Error(e);
    }
  }
}
var F8 = Object.defineProperty, U8 = Object.defineProperties, B8 = Object.getOwnPropertyDescriptors, ju = Object.getOwnPropertySymbols, N8 = Object.prototype.hasOwnProperty, k8 = Object.prototype.propertyIsEnumerable, Uo = (t, e, i) => e in t ? F8(t, e, { enumerable: !0, configurable: !0, writable: !0, value: i }) : t[e] = i, L8 = (t, e) => {
  for (var i in e || (e = {}))
    N8.call(e, i) && Uo(t, i, e[i]);
  if (ju)
    for (var i of ju(e))
      k8.call(e, i) && Uo(t, i, e[i]);
  return t;
}, M8 = (t, e) => U8(t, B8(e)), Xe = (t, e, i) => Uo(t, typeof e != "symbol" ? e + "" : e, i);
class q8 extends Tg {
  constructor(e, i) {
    super(e, i), this.logger = e, this.core = i, Xe(this, "messages", /* @__PURE__ */ new Map()), Xe(this, "messagesWithoutClientAck", /* @__PURE__ */ new Map()), Xe(this, "name", T_), Xe(this, "version", C_), Xe(this, "initialized", !1), Xe(this, "storagePrefix", Ot), Xe(this, "init", async () => {
      if (!this.initialized) {
        this.logger.trace("Initialized");
        try {
          const r = await this.getRelayerMessages();
          typeof r < "u" && (this.messages = r);
          const s = await this.getRelayerMessagesWithoutClientAck();
          typeof s < "u" && (this.messagesWithoutClientAck = s), this.logger.debug(`Successfully Restored records for ${this.name}`), this.logger.trace({ type: "method", method: "restore", size: this.messages.size });
        } catch (r) {
          this.logger.debug(`Failed to Restore records for ${this.name}`), this.logger.error(r);
        } finally {
          this.initialized = !0;
        }
      }
    }), Xe(this, "set", async (r, s, n) => {
      this.isInitialized();
      const o = at(s);
      let a = this.messages.get(r);
      if (typeof a > "u" && (a = {}), typeof a[o] < "u")
        return o;
      if (a[o] = s, this.messages.set(r, a), n === Ts.inbound) {
        const c = this.messagesWithoutClientAck.get(r) || {};
        this.messagesWithoutClientAck.set(r, M8(L8({}, c), { [o]: s }));
      }
      return await this.persist(), o;
    }), Xe(this, "get", (r) => {
      this.isInitialized();
      let s = this.messages.get(r);
      return typeof s > "u" && (s = {}), s;
    }), Xe(this, "getWithoutAck", (r) => {
      this.isInitialized();
      const s = {};
      for (const n of r) {
        const o = this.messagesWithoutClientAck.get(n) || {};
        s[n] = Object.values(o);
      }
      return s;
    }), Xe(this, "has", (r, s) => {
      this.isInitialized();
      const n = this.get(r), o = at(s);
      return typeof n[o] < "u";
    }), Xe(this, "ack", async (r, s) => {
      this.isInitialized();
      const n = this.messagesWithoutClientAck.get(r);
      if (typeof n > "u")
        return;
      const o = at(s);
      delete n[o], Object.keys(n).length === 0 ? this.messagesWithoutClientAck.delete(r) : this.messagesWithoutClientAck.set(r, n), await this.persist();
    }), Xe(this, "del", async (r) => {
      this.isInitialized(), this.messages.delete(r), this.messagesWithoutClientAck.delete(r), await this.persist();
    }), this.logger = je(e, this.name), this.core = i;
  }
  get context() {
    return Qe(this.logger);
  }
  get storageKey() {
    return this.storagePrefix + this.version + this.core.customStoragePrefix + "//" + this.name;
  }
  get storageKeyWithoutClientAck() {
    return this.storagePrefix + this.version + this.core.customStoragePrefix + "//" + this.name + "_withoutClientAck";
  }
  async setRelayerMessages(e) {
    await this.core.storage.setItem(this.storageKey, bo(e));
  }
  async setRelayerMessagesWithoutClientAck(e) {
    await this.core.storage.setItem(this.storageKeyWithoutClientAck, bo(e));
  }
  async getRelayerMessages() {
    const e = await this.core.storage.getItem(this.storageKey);
    return typeof e < "u" ? vo(e) : void 0;
  }
  async getRelayerMessagesWithoutClientAck() {
    const e = await this.core.storage.getItem(this.storageKeyWithoutClientAck);
    return typeof e < "u" ? vo(e) : void 0;
  }
  async persist() {
    await this.setRelayerMessages(this.messages), await this.setRelayerMessagesWithoutClientAck(this.messagesWithoutClientAck);
  }
  isInitialized() {
    if (!this.initialized) {
      const { message: e } = M("NOT_INITIALIZED", this.name);
      throw new Error(e);
    }
  }
}
var j8 = Object.defineProperty, z8 = Object.defineProperties, K8 = Object.getOwnPropertyDescriptors, zu = Object.getOwnPropertySymbols, V8 = Object.prototype.hasOwnProperty, H8 = Object.prototype.propertyIsEnumerable, Bo = (t, e, i) => e in t ? j8(t, e, { enumerable: !0, configurable: !0, writable: !0, value: i }) : t[e] = i, zi = (t, e) => {
  for (var i in e || (e = {}))
    V8.call(e, i) && Bo(t, i, e[i]);
  if (zu)
    for (var i of zu(e))
      H8.call(e, i) && Bo(t, i, e[i]);
  return t;
}, Ku = (t, e) => z8(t, K8(e)), nt = (t, e, i) => Bo(t, typeof e != "symbol" ? e + "" : e, i);
class W8 extends Cg {
  constructor(e, i) {
    super(e, i), this.relayer = e, this.logger = i, nt(this, "events", new rt.EventEmitter()), nt(this, "name", R_), nt(this, "queue", /* @__PURE__ */ new Map()), nt(this, "publishTimeout", L.toMiliseconds(L.ONE_MINUTE)), nt(this, "initialPublishTimeout", L.toMiliseconds(L.ONE_SECOND * 15)), nt(this, "needsTransportRestart", !1), nt(this, "publish", async (r, s, n) => {
      var o, a, c, u, h;
      this.logger.debug("Publishing Payload"), this.logger.trace({ type: "method", method: "publish", params: { topic: r, message: s, opts: n } });
      const l = n?.ttl || P_, f = n?.prompt || !1, p = n?.tag || 0, d = n?.id || ni().toString(), g = Wi(Vs().protocol), y = { id: d, method: n?.publishMethod || g.publish, params: zi({ topic: r, message: s, ttl: l, prompt: f, tag: p, attestation: n?.attestation }, n?.tvf && { tvf: n.tvf }) }, E = `Failed to publish payload, please try again. id:${d} tag:${p}`;
      try {
        ve((o = y.params) == null ? void 0 : o.prompt) && ((a = y.params) == null || delete a.prompt), ve((c = y.params) == null ? void 0 : c.tag) && ((u = y.params) == null || delete u.tag);
        const v = new Promise(async (m) => {
          const D = ({ id: R }) => {
            var B;
            ((B = y.id) == null ? void 0 : B.toString()) === R.toString() && (this.removeRequestFromQueue(R), this.relayer.events.removeListener(de.publish, D), m());
          };
          this.relayer.events.on(de.publish, D);
          const I = At(new Promise((R, B) => {
            this.rpcPublish(y, n).then(R).catch((C) => {
              this.logger.warn(C, C?.message), B(C);
            });
          }), this.initialPublishTimeout, `Failed initial publish, retrying.... id:${d} tag:${p}`);
          try {
            await I, this.events.removeListener(de.publish, D);
          } catch (R) {
            this.queue.set(d, { request: y, opts: n, attempt: 1 }), this.logger.warn(R, R?.message);
          }
        });
        this.logger.trace({ type: "method", method: "publish", params: { id: d, topic: r, message: s, opts: n } }), await At(v, this.publishTimeout, E);
      } catch (v) {
        if (this.logger.debug("Failed to Publish Payload"), this.logger.error(v), (h = n?.internal) != null && h.throwOnFailedPublish)
          throw v;
      } finally {
        this.queue.delete(d);
      }
    }), nt(this, "publishCustom", async (r) => {
      var s, n, o, a, c;
      this.logger.debug("Publishing custom payload"), this.logger.trace({ type: "method", method: "publishCustom", params: r });
      const { payload: u, opts: h = {} } = r, { attestation: l, tvf: f, publishMethod: p, prompt: d, tag: g, ttl: y = L.FIVE_MINUTES } = h, E = h.id || ni().toString(), v = Wi(Vs().protocol), m = p || v.publish, D = { id: E, method: m, params: zi(Ku(zi({}, u), { ttl: y, prompt: d, tag: g, attestation: l }), f) }, I = `Failed to publish custom payload, please try again. id:${E} tag:${g}`;
      try {
        ve((s = D.params) == null ? void 0 : s.prompt) && ((n = D.params) == null || delete n.prompt), ve((o = D.params) == null ? void 0 : o.tag) && ((a = D.params) == null || delete a.tag);
        const R = new Promise(async (B) => {
          const C = ({ id: O }) => {
            var _;
            ((_ = D.id) == null ? void 0 : _.toString()) === O.toString() && (this.removeRequestFromQueue(O), this.relayer.events.removeListener(de.publish, C), B());
          };
          this.relayer.events.on(de.publish, C);
          const w = At(new Promise((O, _) => {
            this.rpcPublish(D, h).then(O).catch(($) => {
              this.logger.warn($, $?.message), _($);
            });
          }), this.initialPublishTimeout, `Failed initial custom payload publish, retrying.... method:${m} id:${E} tag:${g}`);
          try {
            await w, this.events.removeListener(de.publish, C);
          } catch (O) {
            this.queue.set(E, { request: D, opts: h, attempt: 1 }), this.logger.warn(O, O?.message);
          }
        });
        this.logger.trace({ type: "method", method: "publish", params: { id: E, payload: u, opts: h } }), await At(R, this.publishTimeout, I);
      } catch (R) {
        if (this.logger.debug("Failed to Publish Payload"), this.logger.error(R), (c = h?.internal) != null && c.throwOnFailedPublish)
          throw R;
      } finally {
        this.queue.delete(E);
      }
    }), nt(this, "on", (r, s) => {
      this.events.on(r, s);
    }), nt(this, "once", (r, s) => {
      this.events.once(r, s);
    }), nt(this, "off", (r, s) => {
      this.events.off(r, s);
    }), nt(this, "removeListener", (r, s) => {
      this.events.removeListener(r, s);
    }), this.relayer = e, this.logger = je(i, this.name), this.registerEventListeners();
  }
  get context() {
    return Qe(this.logger);
  }
  async rpcPublish(e, i) {
    this.logger.debug("Outgoing Relay Payload"), this.logger.trace({ type: "message", direction: "outgoing", request: e });
    const r = await this.relayer.request(e);
    return this.relayer.events.emit(de.publish, zi(zi({}, e), i)), this.logger.debug("Successfully Published Payload"), r;
  }
  removeRequestFromQueue(e) {
    this.queue.delete(e);
  }
  checkQueue() {
    this.queue.forEach(async (e, i) => {
      var r;
      const s = e.attempt + 1;
      this.queue.set(i, Ku(zi({}, e), { attempt: s })), this.logger.warn({}, `Publisher: queue->publishing: ${e.request.id}, tag: ${(r = e.request.params) == null ? void 0 : r.tag}, attempt: ${s}`), await this.rpcPublish(e.request, e.opts), this.logger.warn({}, `Publisher: queue->published: ${e.request.id}`);
    });
  }
  registerEventListeners() {
    this.relayer.core.heartbeat.on(Ti.pulse, () => {
      if (this.needsTransportRestart) {
        this.needsTransportRestart = !1, this.relayer.events.emit(de.connection_stalled);
        return;
      }
      this.checkQueue();
    }), this.relayer.on(de.message_ack, (e) => {
      this.removeRequestFromQueue(e.id.toString());
    });
  }
}
var G8 = Object.defineProperty, Y8 = (t, e, i) => e in t ? G8(t, e, { enumerable: !0, configurable: !0, writable: !0, value: i }) : t[e] = i, Ki = (t, e, i) => Y8(t, typeof e != "symbol" ? e + "" : e, i);
class J8 {
  constructor() {
    Ki(this, "map", /* @__PURE__ */ new Map()), Ki(this, "set", (e, i) => {
      const r = this.get(e);
      this.exists(e, i) || this.map.set(e, [...r, i]);
    }), Ki(this, "get", (e) => this.map.get(e) || []), Ki(this, "exists", (e, i) => this.get(e).includes(i)), Ki(this, "delete", (e, i) => {
      if (typeof i > "u") {
        this.map.delete(e);
        return;
      }
      if (!this.map.has(e))
        return;
      const r = this.get(e);
      if (!this.exists(e, i))
        return;
      const s = r.filter((n) => n !== i);
      if (!s.length) {
        this.map.delete(e);
        return;
      }
      this.map.set(e, s);
    }), Ki(this, "clear", () => {
      this.map.clear();
    });
  }
  get topics() {
    return Array.from(this.map.keys());
  }
}
var Z8 = Object.defineProperty, Q8 = Object.defineProperties, X8 = Object.getOwnPropertyDescriptors, Vu = Object.getOwnPropertySymbols, eI = Object.prototype.hasOwnProperty, tI = Object.prototype.propertyIsEnumerable, No = (t, e, i) => e in t ? Z8(t, e, { enumerable: !0, configurable: !0, writable: !0, value: i }) : t[e] = i, Er = (t, e) => {
  for (var i in e || (e = {}))
    eI.call(e, i) && No(t, i, e[i]);
  if (Vu)
    for (var i of Vu(e))
      tI.call(e, i) && No(t, i, e[i]);
  return t;
}, Gn = (t, e) => Q8(t, X8(e)), ae = (t, e, i) => No(t, typeof e != "symbol" ? e + "" : e, i);
class iI extends Fg {
  constructor(e, i) {
    super(e, i), this.relayer = e, this.logger = i, ae(this, "subscriptions", /* @__PURE__ */ new Map()), ae(this, "topicMap", new J8()), ae(this, "events", new rt.EventEmitter()), ae(this, "name", M_), ae(this, "version", q_), ae(this, "pending", /* @__PURE__ */ new Map()), ae(this, "cached", []), ae(this, "initialized", !1), ae(this, "storagePrefix", Ot), ae(this, "subscribeTimeout", L.toMiliseconds(L.ONE_MINUTE)), ae(this, "initialSubscribeTimeout", L.toMiliseconds(L.ONE_SECOND * 15)), ae(this, "clientId"), ae(this, "batchSubscribeTopicsLimit", 500), ae(this, "init", async () => {
      this.initialized || (this.logger.trace("Initialized"), this.registerEventListeners(), await this.restore()), this.initialized = !0;
    }), ae(this, "subscribe", async (r, s) => {
      var n;
      this.isInitialized(), this.logger.debug("Subscribing Topic"), this.logger.trace({ type: "method", method: "subscribe", params: { topic: r, opts: s } });
      try {
        const o = Vs(s), a = { topic: r, relay: o, transportType: s?.transportType };
        (n = s?.internal) != null && n.skipSubscribe || this.pending.set(r, a);
        const c = await this.rpcSubscribe(r, o, s);
        return typeof c == "string" && (this.onSubscribe(c, a), this.logger.debug("Successfully Subscribed Topic"), this.logger.trace({ type: "method", method: "subscribe", params: { topic: r, opts: s } })), c;
      } catch (o) {
        throw this.logger.debug("Failed to Subscribe Topic"), this.logger.error(o), o;
      }
    }), ae(this, "unsubscribe", async (r, s) => {
      this.isInitialized(), typeof s?.id < "u" ? await this.unsubscribeById(r, s.id, s) : await this.unsubscribeByTopic(r, s);
    }), ae(this, "isSubscribed", (r) => new Promise((s) => {
      s(this.topicMap.topics.includes(r));
    })), ae(this, "isKnownTopic", (r) => new Promise((s) => {
      s(this.topicMap.topics.includes(r) || this.pending.has(r) || this.cached.some((n) => n.topic === r));
    })), ae(this, "on", (r, s) => {
      this.events.on(r, s);
    }), ae(this, "once", (r, s) => {
      this.events.once(r, s);
    }), ae(this, "off", (r, s) => {
      this.events.off(r, s);
    }), ae(this, "removeListener", (r, s) => {
      this.events.removeListener(r, s);
    }), ae(this, "start", async () => {
      await this.onConnect();
    }), ae(this, "stop", async () => {
      await this.onDisconnect();
    }), ae(this, "restart", async () => {
      await this.restore(), await this.onRestart();
    }), ae(this, "checkPending", async () => {
      if (this.pending.size === 0 && (!this.initialized || !this.relayer.connected))
        return;
      const r = [];
      this.pending.forEach((s) => {
        r.push(s);
      }), await this.batchSubscribe(r);
    }), ae(this, "registerEventListeners", () => {
      this.relayer.core.heartbeat.on(Ti.pulse, async () => {
        await this.checkPending();
      }), this.events.on(et.created, async (r) => {
        const s = et.created;
        this.logger.info(`Emitting ${s}`), this.logger.debug({ type: "event", event: s, data: r }), await this.persist();
      }), this.events.on(et.deleted, async (r) => {
        const s = et.deleted;
        this.logger.info(`Emitting ${s}`), this.logger.debug({ type: "event", event: s, data: r }), await this.persist();
      });
    }), this.relayer = e, this.logger = je(i, this.name), this.clientId = "";
  }
  get context() {
    return Qe(this.logger);
  }
  get storageKey() {
    return this.storagePrefix + this.version + this.relayer.core.customStoragePrefix + "//" + this.name;
  }
  get length() {
    return this.subscriptions.size;
  }
  get ids() {
    return Array.from(this.subscriptions.keys());
  }
  get values() {
    return Array.from(this.subscriptions.values());
  }
  get topics() {
    return this.topicMap.topics;
  }
  get hasAnyTopics() {
    return this.topicMap.topics.length > 0 || this.pending.size > 0 || this.cached.length > 0 || this.subscriptions.size > 0;
  }
  hasSubscription(e, i) {
    let r = !1;
    try {
      r = this.getSubscription(e).topic === i;
    } catch {
    }
    return r;
  }
  reset() {
    this.cached = [], this.initialized = !0;
  }
  onDisable() {
    this.values.length > 0 && (this.cached = this.values), this.subscriptions.clear(), this.topicMap.clear();
  }
  async unsubscribeByTopic(e, i) {
    const r = this.topicMap.get(e);
    await Promise.all(r.map(async (s) => await this.unsubscribeById(e, s, i)));
  }
  async unsubscribeById(e, i, r) {
    this.logger.debug("Unsubscribing Topic"), this.logger.trace({ type: "method", method: "unsubscribe", params: { topic: e, id: i, opts: r } });
    try {
      const s = Vs(r);
      await this.restartToComplete({ topic: e, id: i, relay: s }), await this.rpcUnsubscribe(e, i, s);
      const n = le("USER_DISCONNECTED", `${this.name}, ${e}`);
      await this.onUnsubscribe(e, i, n), this.logger.debug("Successfully Unsubscribed Topic"), this.logger.trace({ type: "method", method: "unsubscribe", params: { topic: e, id: i, opts: r } });
    } catch (s) {
      throw this.logger.debug("Failed to Unsubscribe Topic"), this.logger.error(s), s;
    }
  }
  async rpcSubscribe(e, i, r) {
    var s, n;
    const o = await this.getSubscriptionId(e);
    if ((s = r?.internal) != null && s.skipSubscribe)
      return o;
    (!r || r?.transportType === he.relay) && await this.restartToComplete({ topic: e, id: e, relay: i });
    const a = { method: Wi(i.protocol).subscribe, params: { topic: e } };
    this.logger.debug("Outgoing Relay Payload"), this.logger.trace({ type: "payload", direction: "outgoing", request: a });
    const c = (n = r?.internal) == null ? void 0 : n.throwOnFailedPublish;
    try {
      if (r?.transportType === he.link_mode)
        return setTimeout(() => {
          (this.relayer.connected || this.relayer.connecting) && this.relayer.request(a).catch((l) => this.logger.warn(l));
        }, L.toMiliseconds(L.ONE_SECOND)), o;
      const u = new Promise(async (l) => {
        const f = (p) => {
          p.topic === e && (this.events.removeListener(et.created, f), l(p.id));
        };
        this.events.on(et.created, f);
        try {
          const p = await At(new Promise((d, g) => {
            this.relayer.request(a).catch((y) => {
              this.logger.warn(y, y?.message), g(y);
            }).then(d);
          }), this.initialSubscribeTimeout, `Subscribing to ${e} failed, please try again`);
          this.events.removeListener(et.created, f), l(p);
        } catch {
        }
      }), h = await At(u, this.subscribeTimeout, `Subscribing to ${e} failed, please try again`);
      if (!h && c)
        throw new Error(`Subscribing to ${e} failed, please try again`);
      return h ? o : null;
    } catch (u) {
      if (this.logger.debug("Outgoing Relay Subscribe Payload stalled"), this.relayer.events.emit(de.connection_stalled), c)
        throw u;
    }
    return null;
  }
  async rpcBatchSubscribe(e) {
    if (!e.length)
      return;
    const i = e[0].relay, r = { method: Wi(i.protocol).batchSubscribe, params: { topics: e.map((s) => s.topic) } };
    this.logger.debug("Outgoing Relay Payload"), this.logger.trace({ type: "payload", direction: "outgoing", request: r });
    try {
      await await At(new Promise((s) => {
        this.relayer.request(r).catch((n) => this.logger.warn(n)).then(s);
      }), this.subscribeTimeout, "rpcBatchSubscribe failed, please try again");
    } catch {
      this.relayer.events.emit(de.connection_stalled);
    }
  }
  async rpcBatchFetchMessages(e) {
    if (!e.length)
      return;
    const i = e[0].relay, r = { method: Wi(i.protocol).batchFetchMessages, params: { topics: e.map((n) => n.topic) } };
    this.logger.debug("Outgoing Relay Payload"), this.logger.trace({ type: "payload", direction: "outgoing", request: r });
    let s;
    try {
      s = await await At(new Promise((n, o) => {
        this.relayer.request(r).catch((a) => {
          this.logger.warn(a), o(a);
        }).then(n);
      }), this.subscribeTimeout, "rpcBatchFetchMessages failed, please try again");
    } catch {
      this.relayer.events.emit(de.connection_stalled);
    }
    return s;
  }
  rpcUnsubscribe(e, i, r) {
    const s = { method: Wi(r.protocol).unsubscribe, params: { topic: e, id: i } };
    return this.logger.debug("Outgoing Relay Payload"), this.logger.trace({ type: "payload", direction: "outgoing", request: s }), this.relayer.request(s);
  }
  onSubscribe(e, i) {
    this.setSubscription(e, Gn(Er({}, i), { id: e })), this.pending.delete(i.topic);
  }
  onBatchSubscribe(e) {
    e.length && e.forEach((i) => {
      this.setSubscription(i.id, Er({}, i)), this.pending.delete(i.topic);
    });
  }
  async onUnsubscribe(e, i, r) {
    this.events.removeAllListeners(i), this.hasSubscription(i, e) && this.deleteSubscription(i, r), await this.relayer.messages.del(e);
  }
  async setRelayerSubscriptions(e) {
    await this.relayer.core.storage.setItem(this.storageKey, e);
  }
  async getRelayerSubscriptions() {
    return await this.relayer.core.storage.getItem(this.storageKey);
  }
  setSubscription(e, i) {
    this.logger.debug("Setting subscription"), this.logger.trace({ type: "method", method: "setSubscription", id: e, subscription: i }), this.addSubscription(e, i);
  }
  addSubscription(e, i) {
    this.subscriptions.set(e, Er({}, i)), this.topicMap.set(i.topic, e), this.events.emit(et.created, i);
  }
  getSubscription(e) {
    this.logger.debug("Getting subscription"), this.logger.trace({ type: "method", method: "getSubscription", id: e });
    const i = this.subscriptions.get(e);
    if (!i) {
      const { message: r } = M("NO_MATCHING_KEY", `${this.name}: ${e}`);
      throw new Error(r);
    }
    return i;
  }
  deleteSubscription(e, i) {
    this.logger.debug("Deleting subscription"), this.logger.trace({ type: "method", method: "deleteSubscription", id: e, reason: i });
    const r = this.getSubscription(e);
    this.subscriptions.delete(e), this.topicMap.delete(r.topic, e), this.events.emit(et.deleted, Gn(Er({}, r), { reason: i }));
  }
  async persist() {
    await this.setRelayerSubscriptions(this.values), this.events.emit(et.sync);
  }
  async onRestart() {
    if (this.cached.length) {
      const e = [...this.cached], i = Math.ceil(this.cached.length / this.batchSubscribeTopicsLimit);
      for (let r = 0; r < i; r++) {
        const s = e.splice(0, this.batchSubscribeTopicsLimit);
        await this.batchSubscribe(s);
      }
    }
    this.events.emit(et.resubscribed);
  }
  async restore() {
    try {
      const e = await this.getRelayerSubscriptions();
      if (typeof e > "u" || !e.length)
        return;
      if (this.subscriptions.size && !e.every((i) => {
        var r;
        return i.topic === ((r = this.subscriptions.get(i.id)) == null ? void 0 : r.topic);
      })) {
        const { message: i } = M("RESTORE_WILL_OVERRIDE", this.name);
        throw this.logger.error(i), this.logger.error(`${this.name}: ${JSON.stringify(this.values)}`), new Error(i);
      }
      this.cached = e, this.logger.debug(`Successfully Restored subscriptions for ${this.name}`), this.logger.trace({ type: "method", method: "restore", subscriptions: this.values });
    } catch (e) {
      this.logger.debug(`Failed to Restore subscriptions for ${this.name}`), this.logger.error(e);
    }
  }
  async batchSubscribe(e) {
    e.length && (await this.rpcBatchSubscribe(e), this.onBatchSubscribe(await Promise.all(e.map(async (i) => Gn(Er({}, i), { id: await this.getSubscriptionId(i.topic) })))));
  }
  async batchFetchMessages(e) {
    if (!e.length)
      return;
    this.logger.trace(`Fetching batch messages for ${e.length} subscriptions`);
    const i = await this.rpcBatchFetchMessages(e);
    i && i.messages && (await lv(L.toMiliseconds(L.ONE_SECOND)), await this.relayer.handleBatchMessageEvents(i.messages));
  }
  async onConnect() {
    await this.restart(), this.reset();
  }
  onDisconnect() {
    this.onDisable();
  }
  isInitialized() {
    if (!this.initialized) {
      const { message: e } = M("NOT_INITIALIZED", this.name);
      throw new Error(e);
    }
  }
  async restartToComplete(e) {
    !this.relayer.connected && !this.relayer.connecting && (this.cached.push(e), await this.relayer.transportOpen());
  }
  async getClientId() {
    return this.clientId || (this.clientId = await this.relayer.core.crypto.getClientId()), this.clientId;
  }
  async getSubscriptionId(e) {
    return at(e + await this.getClientId());
  }
}
var rI = Object.defineProperty, Hu = Object.getOwnPropertySymbols, sI = Object.prototype.hasOwnProperty, nI = Object.prototype.propertyIsEnumerable, ko = (t, e, i) => e in t ? rI(t, e, { enumerable: !0, configurable: !0, writable: !0, value: i }) : t[e] = i, Wu = (t, e) => {
  for (var i in e || (e = {}))
    sI.call(e, i) && ko(t, i, e[i]);
  if (Hu)
    for (var i of Hu(e))
      nI.call(e, i) && ko(t, i, e[i]);
  return t;
}, ee = (t, e, i) => ko(t, typeof e != "symbol" ? e + "" : e, i);
class oI extends Pg {
  constructor(e) {
    super(e), ee(this, "protocol", "wc"), ee(this, "version", 2), ee(this, "core"), ee(this, "logger"), ee(this, "events", new rt.EventEmitter()), ee(this, "provider"), ee(this, "messages"), ee(this, "subscriber"), ee(this, "publisher"), ee(this, "name", U_), ee(this, "transportExplicitlyClosed", !1), ee(this, "initialized", !1), ee(this, "connectionAttemptInProgress", !1), ee(this, "relayUrl"), ee(this, "projectId"), ee(this, "packageName"), ee(this, "bundleId"), ee(this, "hasExperiencedNetworkDisruption", !1), ee(this, "pingTimeout"), ee(this, "heartBeatTimeout", L.toMiliseconds(L.THIRTY_SECONDS + L.FIVE_SECONDS)), ee(this, "reconnectTimeout"), ee(this, "connectPromise"), ee(this, "reconnectInProgress", !1), ee(this, "requestsInFlight", []), ee(this, "connectTimeout", L.toMiliseconds(L.ONE_SECOND * 15)), ee(this, "request", async (i) => {
      var r, s;
      this.logger.debug("Publishing Request Payload");
      const n = i.id || ni().toString();
      await this.toEstablishConnection();
      try {
        this.logger.trace({ id: n, method: i.method, topic: (r = i.params) == null ? void 0 : r.topic }, "relayer.request - publishing...");
        const o = `${n}:${((s = i.params) == null ? void 0 : s.tag) || ""}`;
        this.requestsInFlight.push(o);
        const a = await this.provider.request(i);
        return this.requestsInFlight = this.requestsInFlight.filter((c) => c !== o), a;
      } catch (o) {
        throw this.logger.debug(`Failed to Publish Request: ${n}`), o;
      }
    }), ee(this, "resetPingTimeout", () => {
      qs() && (clearTimeout(this.pingTimeout), this.pingTimeout = setTimeout(() => {
        var i, r, s, n;
        try {
          this.logger.debug({}, "pingTimeout: Connection stalled, terminating..."), (n = (s = (r = (i = this.provider) == null ? void 0 : i.connection) == null ? void 0 : r.socket) == null ? void 0 : s.terminate) == null || n.call(s);
        } catch (o) {
          this.logger.warn(o, o?.message);
        }
      }, this.heartBeatTimeout));
    }), ee(this, "onPayloadHandler", (i) => {
      this.onProviderPayload(i), this.resetPingTimeout();
    }), ee(this, "onConnectHandler", () => {
      this.logger.warn({}, "Relayer connected 🛜"), this.startPingTimeout(), this.events.emit(de.connect);
    }), ee(this, "onDisconnectHandler", () => {
      this.logger.warn({}, "Relayer disconnected 🛑"), this.requestsInFlight = [], this.onProviderDisconnect();
    }), ee(this, "onProviderErrorHandler", (i) => {
      this.logger.fatal(`Fatal socket error: ${i.message}`), this.events.emit(de.error, i), this.logger.fatal("Fatal socket error received, closing transport"), this.transportClose();
    }), ee(this, "registerProviderListeners", () => {
      this.provider.on(st.payload, this.onPayloadHandler), this.provider.on(st.connect, this.onConnectHandler), this.provider.on(st.disconnect, this.onDisconnectHandler), this.provider.on(st.error, this.onProviderErrorHandler);
    }), this.core = e.core, this.logger = typeof e.logger < "u" && typeof e.logger != "string" ? je(e.logger, this.name) : Zs(Vo({ level: e.logger || F_ })), this.messages = new q8(this.logger, e.core), this.subscriber = new iI(this, this.logger), this.publisher = new W8(this, this.logger), this.projectId = e?.projectId, this.relayUrl = e?.relayUrl || Qf, Yb() ? this.packageName = Nc() : Jb() && (this.bundleId = Nc()), this.provider = {};
  }
  async init() {
    this.logger.trace("Initialized"), this.registerEventListeners(), await Promise.all([this.messages.init(), this.subscriber.init()]), this.initialized = !0, this.transportOpen().catch((e) => this.logger.warn(e, e?.message));
  }
  get context() {
    return Qe(this.logger);
  }
  get connected() {
    var e, i, r;
    return ((r = (i = (e = this.provider) == null ? void 0 : e.connection) == null ? void 0 : i.socket) == null ? void 0 : r.readyState) === 1 || !1;
  }
  get connecting() {
    var e, i, r;
    return ((r = (i = (e = this.provider) == null ? void 0 : e.connection) == null ? void 0 : i.socket) == null ? void 0 : r.readyState) === 0 || this.connectPromise !== void 0 || !1;
  }
  async publish(e, i, r) {
    this.isInitialized(), await this.publisher.publish(e, i, r), await this.recordMessageEvent({ topic: e, message: i, publishedAt: Date.now(), transportType: he.relay }, Ts.outbound);
  }
  async publishCustom(e) {
    this.isInitialized(), await this.publisher.publishCustom(e);
  }
  async subscribe(e, i) {
    var r, s, n;
    this.isInitialized(), (!(i != null && i.transportType) || i?.transportType === "relay") && await this.toEstablishConnection();
    const o = typeof ((r = i?.internal) == null ? void 0 : r.throwOnFailedPublish) > "u" ? !0 : (s = i?.internal) == null ? void 0 : s.throwOnFailedPublish;
    let a = ((n = this.subscriber.topicMap.get(e)) == null ? void 0 : n[0]) || "", c;
    const u = (h) => {
      h.topic === e && (this.subscriber.off(et.created, u), c());
    };
    return await Promise.all([new Promise((h) => {
      c = h, this.subscriber.on(et.created, u);
    }), new Promise(async (h, l) => {
      a = await this.subscriber.subscribe(e, Wu({ internal: { throwOnFailedPublish: o } }, i)).catch((f) => {
        o && l(f);
      }) || a, h();
    })]), a;
  }
  async unsubscribe(e, i) {
    this.isInitialized(), await this.subscriber.unsubscribe(e, i);
  }
  on(e, i) {
    this.events.on(e, i);
  }
  once(e, i) {
    this.events.once(e, i);
  }
  off(e, i) {
    this.events.off(e, i);
  }
  removeListener(e, i) {
    this.events.removeListener(e, i);
  }
  async transportDisconnect() {
    this.provider.disconnect && (this.hasExperiencedNetworkDisruption || this.connected) ? await At(this.provider.disconnect(), 2e3, "provider.disconnect()").catch(() => this.onProviderDisconnect()) : this.onProviderDisconnect();
  }
  async transportClose() {
    this.transportExplicitlyClosed = !0, await this.transportDisconnect();
  }
  async transportOpen(e) {
    if (!this.subscriber.hasAnyTopics) {
      this.logger.info("Starting WS connection skipped because the client has no topics to work with.");
      return;
    }
    if (this.connectPromise ? (this.logger.debug({}, "Waiting for existing connection attempt to resolve..."), await this.connectPromise, this.logger.debug({}, "Existing connection attempt resolved")) : (this.connectPromise = new Promise(async (i, r) => {
      await this.connect(e).then(i).catch(r).finally(() => {
        this.connectPromise = void 0;
      });
    }), await this.connectPromise), !this.connected)
      throw new Error(`Couldn't establish socket connection to the relay server: ${this.relayUrl}`);
  }
  async restartTransport(e) {
    this.logger.debug({}, "Restarting transport..."), !this.connectionAttemptInProgress && (this.relayUrl = e || this.relayUrl, await this.confirmOnlineStateOrThrow(), await this.transportClose(), await this.transportOpen());
  }
  async confirmOnlineStateOrThrow() {
    if (!await Au())
      throw new Error("No internet connection detected. Please restart your network and try again.");
  }
  async handleBatchMessageEvents(e) {
    if (e?.length === 0) {
      this.logger.trace("Batch message events is empty. Ignoring...");
      return;
    }
    const i = e.sort((r, s) => r.publishedAt - s.publishedAt);
    this.logger.debug(`Batch of ${i.length} message events sorted`);
    for (const r of i)
      try {
        await this.onMessageEvent(r);
      } catch (s) {
        this.logger.warn(s, "Error while processing batch message event: " + s?.message);
      }
    this.logger.trace(`Batch of ${i.length} message events processed`);
  }
  async onLinkMessageEvent(e, i) {
    const { topic: r } = e;
    if (!i.sessionExists) {
      const s = me(L.FIVE_MINUTES), n = { topic: r, expiry: s, relay: { protocol: "irn" }, active: !1 };
      await this.core.pairing.pairings.set(r, n);
    }
    this.events.emit(de.message, e), await this.recordMessageEvent(e, Ts.inbound);
  }
  async connect(e) {
    await this.confirmOnlineStateOrThrow(), e && e !== this.relayUrl && (this.relayUrl = e, await this.transportDisconnect()), this.connectionAttemptInProgress = !0, this.transportExplicitlyClosed = !1;
    let i = 1;
    for (; i < 6; ) {
      try {
        if (this.transportExplicitlyClosed)
          break;
        this.logger.debug({}, `Connecting to ${this.relayUrl}, attempt: ${i}...`), await this.createProvider(), await new Promise(async (r, s) => {
          const n = () => {
            s(new Error("Connection interrupted while trying to connect"));
          };
          this.provider.once(st.disconnect, n), await At(new Promise((o, a) => {
            this.provider.connect().then(o).catch(a);
          }), this.connectTimeout, `Socket stalled when trying to connect to ${this.relayUrl}`).catch((o) => {
            s(o);
          }).finally(() => {
            this.provider.off(st.disconnect, n), clearTimeout(this.reconnectTimeout);
          }), await new Promise(async (o, a) => {
            const c = () => {
              s(new Error("Connection interrupted while trying to subscribe"));
            };
            this.provider.once(st.disconnect, c), await this.subscriber.start().then(o).catch(a).finally(() => {
              this.provider.off(st.disconnect, c);
            });
          }), this.hasExperiencedNetworkDisruption = !1, r();
        });
      } catch (r) {
        await this.subscriber.stop();
        const s = r;
        this.logger.warn({}, s.message), this.hasExperiencedNetworkDisruption = !0;
      } finally {
        this.connectionAttemptInProgress = !1;
      }
      if (this.connected) {
        this.logger.debug({}, `Connected to ${this.relayUrl} successfully on attempt: ${i}`);
        break;
      }
      await new Promise((r) => setTimeout(r, L.toMiliseconds(i * 1))), i++;
    }
  }
  startPingTimeout() {
    var e, i, r, s, n;
    if (qs())
      try {
        (i = (e = this.provider) == null ? void 0 : e.connection) != null && i.socket && ((n = (s = (r = this.provider) == null ? void 0 : r.connection) == null ? void 0 : s.socket) == null || n.on("ping", () => {
          this.resetPingTimeout();
        })), this.resetPingTimeout();
      } catch (o) {
        this.logger.warn(o, o?.message);
      }
  }
  async createProvider() {
    this.provider.connection && this.unregisterProviderListeners();
    const e = await this.core.crypto.signJWT(this.relayUrl);
    this.provider = new Gf(new x_(tv({ sdkVersion: Po, protocol: this.protocol, version: this.version, relayUrl: this.relayUrl, projectId: this.projectId, auth: e, useOnCloseEvent: !0, bundleId: this.bundleId, packageName: this.packageName }))), this.registerProviderListeners();
  }
  async recordMessageEvent(e, i) {
    const { topic: r, message: s } = e;
    await this.messages.set(r, s, i);
  }
  async shouldIgnoreMessageEvent(e) {
    const { topic: i, message: r } = e;
    if (!r || r.length === 0)
      return this.logger.warn(`Ignoring invalid/empty message: ${r}`), !0;
    if (!await this.subscriber.isKnownTopic(i))
      return this.logger.warn(`Ignoring message for unknown topic ${i}`), !0;
    const s = this.messages.has(i, r);
    return s && this.logger.warn(`Ignoring duplicate message: ${r}`), s;
  }
  async onProviderPayload(e) {
    if (this.logger.debug("Incoming Relay Payload"), this.logger.trace({ type: "payload", direction: "incoming", payload: e }), Ia(e)) {
      if (!e.method.endsWith(B_))
        return;
      const i = e.params, { topic: r, message: s, publishedAt: n, attestation: o } = i.data, a = { topic: r, message: s, publishedAt: n, transportType: he.relay, attestation: o };
      this.logger.debug("Emitting Relayer Payload"), this.logger.trace(Wu({ type: "event", event: i.id }, a)), this.events.emit(i.id, a), await this.acknowledgePayload(e), await this.onMessageEvent(a);
    } else
      ln(e) && this.events.emit(de.message_ack, e);
  }
  async onMessageEvent(e) {
    await this.shouldIgnoreMessageEvent(e) || (await this.recordMessageEvent(e, Ts.inbound), this.events.emit(de.message, e));
  }
  async acknowledgePayload(e) {
    const i = Hr(e.id, !0);
    await this.provider.connection.send(i);
  }
  unregisterProviderListeners() {
    this.provider.off(st.payload, this.onPayloadHandler), this.provider.off(st.connect, this.onConnectHandler), this.provider.off(st.disconnect, this.onDisconnectHandler), this.provider.off(st.error, this.onProviderErrorHandler), clearTimeout(this.pingTimeout);
  }
  async registerEventListeners() {
    let e = await Au();
    K3(async (i) => {
      e !== i && (e = i, i ? await this.transportOpen().catch((r) => this.logger.error(r, r?.message)) : (this.hasExperiencedNetworkDisruption = !0, await this.transportDisconnect(), this.transportExplicitlyClosed = !1));
    }), this.core.heartbeat.on(Ti.pulse, async () => {
      if (!this.transportExplicitlyClosed && !this.connected && W3())
        try {
          await this.confirmOnlineStateOrThrow(), await this.transportOpen();
        } catch (i) {
          this.logger.warn(i, i?.message);
        }
    });
  }
  async onProviderDisconnect() {
    clearTimeout(this.pingTimeout), this.events.emit(de.disconnect), this.connectionAttemptInProgress = !1, !this.reconnectInProgress && (this.reconnectInProgress = !0, await this.subscriber.stop(), this.subscriber.hasAnyTopics && (this.transportExplicitlyClosed || (this.reconnectTimeout = setTimeout(async () => {
      await this.transportOpen().catch((e) => this.logger.error(e, e?.message)), this.reconnectTimeout = void 0, this.reconnectInProgress = !1;
    }, L.toMiliseconds(N_)))));
  }
  isInitialized() {
    if (!this.initialized) {
      const { message: e } = M("NOT_INITIALIZED", this.name);
      throw new Error(e);
    }
  }
  async toEstablishConnection() {
    if (await this.confirmOnlineStateOrThrow(), !this.connected) {
      if (this.connectPromise) {
        await this.connectPromise;
        return;
      }
      await this.connect();
    }
  }
}
function aI(t, e) {
  return t === e || Number.isNaN(t) && Number.isNaN(e);
}
function Gu(t) {
  return Object.getOwnPropertySymbols(t).filter((e) => Object.prototype.propertyIsEnumerable.call(t, e));
}
function Yu(t) {
  return t == null ? t === void 0 ? "[object Undefined]" : "[object Null]" : Object.prototype.toString.call(t);
}
const cI = "[object RegExp]", uI = "[object String]", hI = "[object Number]", lI = "[object Boolean]", Ju = "[object Arguments]", fI = "[object Symbol]", dI = "[object Date]", pI = "[object Map]", gI = "[object Set]", yI = "[object Array]", wI = "[object Function]", mI = "[object ArrayBuffer]", Yn = "[object Object]", bI = "[object Error]", vI = "[object DataView]", EI = "[object Uint8Array]", _I = "[object Uint8ClampedArray]", xI = "[object Uint16Array]", II = "[object Uint32Array]", SI = "[object BigUint64Array]", DI = "[object Int8Array]", AI = "[object Int16Array]", $I = "[object Int32Array]", OI = "[object BigInt64Array]", TI = "[object Float32Array]", CI = "[object Float64Array]";
function PI() {
}
function Zu(t) {
  if (!t || typeof t != "object")
    return !1;
  const e = Object.getPrototypeOf(t);
  return e === null || e === Object.prototype || Object.getPrototypeOf(e) === null ? Object.prototype.toString.call(t) === "[object Object]" : !1;
}
function RI(t, e, i) {
  return Dr(t, e, void 0, void 0, void 0, void 0, i);
}
function Dr(t, e, i, r, s, n, o) {
  const a = o(t, e, i, r, s, n);
  if (a !== void 0)
    return a;
  if (typeof t == typeof e)
    switch (typeof t) {
      case "bigint":
      case "string":
      case "boolean":
      case "symbol":
      case "undefined":
        return t === e;
      case "number":
        return t === e || Object.is(t, e);
      case "function":
        return t === e;
      case "object":
        return Ur(t, e, n, o);
    }
  return Ur(t, e, n, o);
}
function Ur(t, e, i, r) {
  if (Object.is(t, e))
    return !0;
  let s = Yu(t), n = Yu(e);
  if (s === Ju && (s = Yn), n === Ju && (n = Yn), s !== n)
    return !1;
  switch (s) {
    case uI:
      return t.toString() === e.toString();
    case hI: {
      const c = t.valueOf(), u = e.valueOf();
      return aI(c, u);
    }
    case lI:
    case dI:
    case fI:
      return Object.is(t.valueOf(), e.valueOf());
    case cI:
      return t.source === e.source && t.flags === e.flags;
    case wI:
      return t === e;
  }
  i = i ?? /* @__PURE__ */ new Map();
  const o = i.get(t), a = i.get(e);
  if (o != null && a != null)
    return o === e;
  i.set(t, e), i.set(e, t);
  try {
    switch (s) {
      case pI: {
        if (t.size !== e.size)
          return !1;
        for (const [c, u] of t.entries())
          if (!e.has(c) || !Dr(u, e.get(c), c, t, e, i, r))
            return !1;
        return !0;
      }
      case gI: {
        if (t.size !== e.size)
          return !1;
        const c = Array.from(t.values()), u = Array.from(e.values());
        for (let h = 0; h < c.length; h++) {
          const l = c[h], f = u.findIndex((p) => Dr(l, p, void 0, t, e, i, r));
          if (f === -1)
            return !1;
          u.splice(f, 1);
        }
        return !0;
      }
      case yI:
      case EI:
      case _I:
      case xI:
      case II:
      case SI:
      case DI:
      case AI:
      case $I:
      case OI:
      case TI:
      case CI: {
        if (typeof Buffer < "u" && Buffer.isBuffer(t) !== Buffer.isBuffer(e) || t.length !== e.length)
          return !1;
        for (let c = 0; c < t.length; c++)
          if (!Dr(t[c], e[c], c, t, e, i, r))
            return !1;
        return !0;
      }
      case mI:
        return t.byteLength !== e.byteLength ? !1 : Ur(new Uint8Array(t), new Uint8Array(e), i, r);
      case vI:
        return t.byteLength !== e.byteLength || t.byteOffset !== e.byteOffset ? !1 : Ur(new Uint8Array(t), new Uint8Array(e), i, r);
      case bI:
        return t.name === e.name && t.message === e.message;
      case Yn: {
        if (!(Ur(t.constructor, e.constructor, i, r) || Zu(t) && Zu(e)))
          return !1;
        const c = [...Object.keys(t), ...Gu(t)], u = [...Object.keys(e), ...Gu(e)];
        if (c.length !== u.length)
          return !1;
        for (let h = 0; h < c.length; h++) {
          const l = c[h], f = t[l];
          if (!Object.hasOwn(e, l))
            return !1;
          const p = e[l];
          if (!Dr(f, p, l, t, e, i, r))
            return !1;
        }
        return !0;
      }
      default:
        return !1;
    }
  } finally {
    i.delete(t), i.delete(e);
  }
}
function FI(t, e) {
  return RI(t, e, PI);
}
var UI = Object.defineProperty, Qu = Object.getOwnPropertySymbols, BI = Object.prototype.hasOwnProperty, NI = Object.prototype.propertyIsEnumerable, Lo = (t, e, i) => e in t ? UI(t, e, { enumerable: !0, configurable: !0, writable: !0, value: i }) : t[e] = i, Xu = (t, e) => {
  for (var i in e || (e = {}))
    BI.call(e, i) && Lo(t, i, e[i]);
  if (Qu)
    for (var i of Qu(e))
      NI.call(e, i) && Lo(t, i, e[i]);
  return t;
}, Ke = (t, e, i) => Lo(t, typeof e != "symbol" ? e + "" : e, i);
class Ri extends Rg {
  constructor(e, i, r, s = Ot, n = void 0) {
    super(e, i, r, s), this.core = e, this.logger = i, this.name = r, Ke(this, "map", /* @__PURE__ */ new Map()), Ke(this, "version", k_), Ke(this, "cached", []), Ke(this, "initialized", !1), Ke(this, "getKey"), Ke(this, "storagePrefix", Ot), Ke(this, "recentlyDeleted", []), Ke(this, "recentlyDeletedLimit", 200), Ke(this, "init", async () => {
      this.initialized || (this.logger.trace("Initialized"), await this.restore(), this.cached.forEach((o) => {
        this.getKey && o !== null && !ve(o) ? this.map.set(this.getKey(o), o) : E3(o) ? this.map.set(o.id, o) : _3(o) && this.map.set(o.topic, o);
      }), this.cached = [], this.initialized = !0);
    }), Ke(this, "set", async (o, a) => {
      this.isInitialized(), this.map.has(o) ? await this.update(o, a) : (this.logger.debug("Setting value"), this.logger.trace({ type: "method", method: "set", key: o, value: a }), this.map.set(o, a), await this.persist());
    }), Ke(this, "get", (o) => (this.isInitialized(), this.logger.debug("Getting value"), this.logger.trace({ type: "method", method: "get", key: o }), this.getData(o))), Ke(this, "getAll", (o) => (this.isInitialized(), o ? this.values.filter((a) => Object.keys(o).every((c) => FI(a[c], o[c]))) : this.values)), Ke(this, "update", async (o, a) => {
      this.isInitialized(), this.logger.debug("Updating value"), this.logger.trace({ type: "method", method: "update", key: o, update: a });
      const c = Xu(Xu({}, this.getData(o)), a);
      this.map.set(o, c), await this.persist();
    }), Ke(this, "delete", async (o, a) => {
      this.isInitialized(), this.map.has(o) && (this.logger.debug("Deleting value"), this.logger.trace({ type: "method", method: "delete", key: o, reason: a }), this.map.delete(o), this.addToRecentlyDeleted(o), await this.persist());
    }), this.logger = je(i, this.name), this.storagePrefix = s, this.getKey = n;
  }
  get context() {
    return Qe(this.logger);
  }
  get storageKey() {
    return this.storagePrefix + this.version + this.core.customStoragePrefix + "//" + this.name;
  }
  get length() {
    return this.map.size;
  }
  get keys() {
    return Array.from(this.map.keys());
  }
  get values() {
    return Array.from(this.map.values());
  }
  addToRecentlyDeleted(e) {
    this.recentlyDeleted.push(e), this.recentlyDeleted.length >= this.recentlyDeletedLimit && this.recentlyDeleted.splice(0, this.recentlyDeletedLimit / 2);
  }
  async setDataStore(e) {
    await this.core.storage.setItem(this.storageKey, e);
  }
  async getDataStore() {
    return await this.core.storage.getItem(this.storageKey);
  }
  getData(e) {
    const i = this.map.get(e);
    if (!i) {
      if (this.recentlyDeleted.includes(e)) {
        const { message: s } = M("MISSING_OR_INVALID", `Record was recently deleted - ${this.name}: ${e}`);
        throw this.logger.error(s), new Error(s);
      }
      const { message: r } = M("NO_MATCHING_KEY", `${this.name}: ${e}`);
      throw this.logger.error(r), new Error(r);
    }
    return i;
  }
  async persist() {
    await this.setDataStore(this.values);
  }
  async restore() {
    try {
      const e = await this.getDataStore();
      if (typeof e > "u" || !e.length)
        return;
      if (this.map.size) {
        const { message: i } = M("RESTORE_WILL_OVERRIDE", this.name);
        throw this.logger.error(i), new Error(i);
      }
      this.cached = e, this.logger.debug(`Successfully Restored value for ${this.name}`), this.logger.trace({ type: "method", method: "restore", value: this.values });
    } catch (e) {
      this.logger.debug(`Failed to Restore value for ${this.name}`), this.logger.error(e);
    }
  }
  isInitialized() {
    if (!this.initialized) {
      const { message: e } = M("NOT_INITIALIZED", this.name);
      throw new Error(e);
    }
  }
}
var kI = Object.defineProperty, LI = (t, e, i) => e in t ? kI(t, e, { enumerable: !0, configurable: !0, writable: !0, value: i }) : t[e] = i, Z = (t, e, i) => LI(t, typeof e != "symbol" ? e + "" : e, i);
class MI {
  constructor(e, i) {
    this.core = e, this.logger = i, Z(this, "name", j_), Z(this, "version", z_), Z(this, "events", new mh()), Z(this, "pairings"), Z(this, "initialized", !1), Z(this, "storagePrefix", Ot), Z(this, "ignoredPayloadTypes", [Mt]), Z(this, "registeredMethods", []), Z(this, "init", async () => {
      this.initialized || (await this.pairings.init(), await this.cleanup(), this.registerRelayerEvents(), this.registerExpirerEvents(), this.initialized = !0, this.logger.trace("Initialized"));
    }), Z(this, "register", ({ methods: r }) => {
      this.isInitialized(), this.registeredMethods = [.../* @__PURE__ */ new Set([...this.registeredMethods, ...r])];
    }), Z(this, "create", async (r) => {
      this.isInitialized();
      const s = To(), n = await this.core.crypto.setSymKey(s), o = me(L.FIVE_MINUTES), a = { protocol: Zf }, c = { topic: n, expiry: o, relay: a, active: !1, methods: r?.methods }, u = mu({ protocol: this.core.protocol, version: this.core.version, topic: n, symKey: s, relay: a, expiryTimestamp: o, methods: r?.methods });
      return this.events.emit(mi.create, c), this.core.expirer.set(n, o), await this.pairings.set(n, c), await this.core.relayer.subscribe(n, { transportType: r?.transportType, internal: r?.internal }), { topic: n, uri: u };
    }), Z(this, "pair", async (r) => {
      this.isInitialized();
      const s = this.core.eventClient.createEvent({ properties: { topic: r?.uri, trace: [xt.pairing_started] } });
      this.isValidPair(r, s);
      const { topic: n, symKey: o, relay: a, expiryTimestamp: c, methods: u } = wu(r.uri);
      s.props.properties.topic = n, s.addTrace(xt.pairing_uri_validation_success), s.addTrace(xt.pairing_uri_not_expired);
      let h;
      if (this.pairings.keys.includes(n)) {
        if (h = this.pairings.get(n), s.addTrace(xt.existing_pairing), h.active)
          throw s.setError(Nt.active_pairing_already_exists), new Error(`Pairing already exists: ${n}. Please try again with a new connection URI.`);
        s.addTrace(xt.pairing_not_expired);
      }
      const l = c || me(L.FIVE_MINUTES), f = { topic: n, relay: a, expiry: l, active: !1, methods: u };
      this.core.expirer.set(n, l), await this.pairings.set(n, f), s.addTrace(xt.store_new_pairing), r.activatePairing && await this.activate({ topic: n }), this.events.emit(mi.create, f), s.addTrace(xt.emit_inactive_pairing), this.core.crypto.keychain.has(n) || await this.core.crypto.setSymKey(o, n), s.addTrace(xt.subscribing_pairing_topic);
      try {
        await this.core.relayer.confirmOnlineStateOrThrow();
      } catch {
        s.setError(Nt.no_internet_connection);
      }
      try {
        await this.core.relayer.subscribe(n, { relay: a });
      } catch (p) {
        throw s.setError(Nt.subscribe_pairing_topic_failure), p;
      }
      return s.addTrace(xt.subscribe_pairing_topic_success), f;
    }), Z(this, "activate", async ({ topic: r }) => {
      this.isInitialized();
      const s = me(L.FIVE_MINUTES);
      this.core.expirer.set(r, s), await this.pairings.update(r, { active: !0, expiry: s });
    }), Z(this, "ping", async (r) => {
      this.isInitialized(), await this.isValidPing(r), this.logger.warn("ping() is deprecated and will be removed in the next major release.");
      const { topic: s } = r;
      if (this.pairings.keys.includes(s)) {
        const n = await this.sendRequest(s, "wc_pairingPing", {}), { done: o, resolve: a, reject: c } = yi();
        this.events.once(se("pairing_ping", n), ({ error: u }) => {
          u ? c(u) : a();
        }), await o();
      }
    }), Z(this, "updateExpiry", async ({ topic: r, expiry: s }) => {
      this.isInitialized(), await this.pairings.update(r, { expiry: s });
    }), Z(this, "updateMetadata", async ({ topic: r, metadata: s }) => {
      this.isInitialized(), await this.pairings.update(r, { peerMetadata: s });
    }), Z(this, "getPairings", () => (this.isInitialized(), this.pairings.values)), Z(this, "disconnect", async (r) => {
      this.isInitialized(), await this.isValidDisconnect(r);
      const { topic: s } = r;
      this.pairings.keys.includes(s) && (await this.sendRequest(s, "wc_pairingDelete", le("USER_DISCONNECTED")), await this.deletePairing(s));
    }), Z(this, "formatUriFromPairing", (r) => {
      this.isInitialized();
      const { topic: s, relay: n, expiry: o, methods: a } = r, c = this.core.crypto.keychain.get(s);
      return mu({ protocol: this.core.protocol, version: this.core.version, topic: s, symKey: c, relay: n, expiryTimestamp: o, methods: a });
    }), Z(this, "sendRequest", async (r, s, n) => {
      const o = Lt(s, n), a = await this.core.crypto.encode(r, o), c = mr[s].req;
      return this.core.history.set(r, o), this.core.relayer.publish(r, a, c), o.id;
    }), Z(this, "sendResult", async (r, s, n) => {
      const o = Hr(r, n), a = await this.core.crypto.encode(s, o), c = (await this.core.history.get(s, r)).request.method, u = mr[c].res;
      await this.core.relayer.publish(s, a, u), await this.core.history.resolve(o);
    }), Z(this, "sendError", async (r, s, n) => {
      const o = hn(r, n), a = await this.core.crypto.encode(s, o), c = (await this.core.history.get(s, r)).request.method, u = mr[c] ? mr[c].res : mr.unregistered_method.res;
      await this.core.relayer.publish(s, a, u), await this.core.history.resolve(o);
    }), Z(this, "deletePairing", async (r, s) => {
      await this.core.relayer.unsubscribe(r), await Promise.all([this.pairings.delete(r, le("USER_DISCONNECTED")), this.core.crypto.deleteSymKey(r), s ? Promise.resolve() : this.core.expirer.del(r)]);
    }), Z(this, "cleanup", async () => {
      const r = this.pairings.getAll().filter((s) => ei(s.expiry));
      await Promise.all(r.map((s) => this.deletePairing(s.topic)));
    }), Z(this, "onRelayEventRequest", async (r) => {
      const { topic: s, payload: n } = r;
      switch (n.method) {
        case "wc_pairingPing":
          return await this.onPairingPingRequest(s, n);
        case "wc_pairingDelete":
          return await this.onPairingDeleteRequest(s, n);
        default:
          return await this.onUnknownRpcMethodRequest(s, n);
      }
    }), Z(this, "onRelayEventResponse", async (r) => {
      const { topic: s, payload: n } = r, o = (await this.core.history.get(s, n.id)).request.method;
      switch (o) {
        case "wc_pairingPing":
          return this.onPairingPingResponse(s, n);
        default:
          return this.onUnknownRpcMethodResponse(o);
      }
    }), Z(this, "onPairingPingRequest", async (r, s) => {
      const { id: n } = s;
      try {
        this.isValidPing({ topic: r }), await this.sendResult(n, r, !0), this.events.emit(mi.ping, { id: n, topic: r });
      } catch (o) {
        await this.sendError(n, r, o), this.logger.error(o);
      }
    }), Z(this, "onPairingPingResponse", (r, s) => {
      const { id: n } = s;
      setTimeout(() => {
        St(s) ? this.events.emit(se("pairing_ping", n), {}) : ct(s) && this.events.emit(se("pairing_ping", n), { error: s.error });
      }, 500);
    }), Z(this, "onPairingDeleteRequest", async (r, s) => {
      const { id: n } = s;
      try {
        this.isValidDisconnect({ topic: r }), await this.deletePairing(r), this.events.emit(mi.delete, { id: n, topic: r });
      } catch (o) {
        await this.sendError(n, r, o), this.logger.error(o);
      }
    }), Z(this, "onUnknownRpcMethodRequest", async (r, s) => {
      const { id: n, method: o } = s;
      try {
        if (this.registeredMethods.includes(o))
          return;
        const a = le("WC_METHOD_UNSUPPORTED", o);
        await this.sendError(n, r, a), this.logger.error(a);
      } catch (a) {
        await this.sendError(n, r, a), this.logger.error(a);
      }
    }), Z(this, "onUnknownRpcMethodResponse", (r) => {
      this.registeredMethods.includes(r) || this.logger.error(le("WC_METHOD_UNSUPPORTED", r));
    }), Z(this, "isValidPair", (r, s) => {
      var n;
      if (!He(r)) {
        const { message: a } = M("MISSING_OR_INVALID", `pair() params: ${r}`);
        throw s.setError(Nt.malformed_pairing_uri), new Error(a);
      }
      if (!v3(r.uri)) {
        const { message: a } = M("MISSING_OR_INVALID", `pair() uri: ${r.uri}`);
        throw s.setError(Nt.malformed_pairing_uri), new Error(a);
      }
      const o = wu(r?.uri);
      if (!((n = o?.relay) != null && n.protocol)) {
        const { message: a } = M("MISSING_OR_INVALID", "pair() uri#relay-protocol");
        throw s.setError(Nt.malformed_pairing_uri), new Error(a);
      }
      if (!(o != null && o.symKey)) {
        const { message: a } = M("MISSING_OR_INVALID", "pair() uri#symKey");
        throw s.setError(Nt.malformed_pairing_uri), new Error(a);
      }
      if (o != null && o.expiryTimestamp && L.toMiliseconds(o?.expiryTimestamp) < Date.now()) {
        s.setError(Nt.pairing_expired);
        const { message: a } = M("EXPIRED", "pair() URI has expired. Please try again with a new connection URI.");
        throw new Error(a);
      }
    }), Z(this, "isValidPing", async (r) => {
      if (!He(r)) {
        const { message: n } = M("MISSING_OR_INVALID", `ping() params: ${r}`);
        throw new Error(n);
      }
      const { topic: s } = r;
      await this.isValidPairingTopic(s);
    }), Z(this, "isValidDisconnect", async (r) => {
      if (!He(r)) {
        const { message: n } = M("MISSING_OR_INVALID", `disconnect() params: ${r}`);
        throw new Error(n);
      }
      const { topic: s } = r;
      await this.isValidPairingTopic(s);
    }), Z(this, "isValidPairingTopic", async (r) => {
      if (!ye(r, !1)) {
        const { message: s } = M("MISSING_OR_INVALID", `pairing topic should be a string: ${r}`);
        throw new Error(s);
      }
      if (!this.pairings.keys.includes(r)) {
        const { message: s } = M("NO_MATCHING_KEY", `pairing topic doesn't exist: ${r}`);
        throw new Error(s);
      }
      if (ei(this.pairings.get(r).expiry)) {
        await this.deletePairing(r);
        const { message: s } = M("EXPIRED", `pairing topic: ${r}`);
        throw new Error(s);
      }
    }), this.core = e, this.logger = je(i, this.name), this.pairings = new Ri(this.core, this.logger, this.name, this.storagePrefix);
  }
  get context() {
    return Qe(this.logger);
  }
  isInitialized() {
    if (!this.initialized) {
      const { message: e } = M("NOT_INITIALIZED", this.name);
      throw new Error(e);
    }
  }
  registerRelayerEvents() {
    this.core.relayer.on(de.message, async (e) => {
      const { topic: i, message: r, transportType: s } = e;
      if (this.pairings.keys.includes(i) && s !== he.link_mode && !this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(r)))
        try {
          const n = await this.core.crypto.decode(i, r);
          Ia(n) ? (this.core.history.set(i, n), await this.onRelayEventRequest({ topic: i, payload: n })) : ln(n) && (await this.core.history.resolve(n), await this.onRelayEventResponse({ topic: i, payload: n }), this.core.history.delete(i, n.id)), await this.core.relayer.messages.ack(i, r);
        } catch (n) {
          this.logger.error(n);
        }
    });
  }
  registerExpirerEvents() {
    this.core.expirer.on(ot.expired, async (e) => {
      const { topic: i } = Gl(e.target);
      i && this.pairings.keys.includes(i) && (await this.deletePairing(i, !0), this.events.emit(mi.expire, { topic: i }));
    });
  }
}
var qI = Object.defineProperty, jI = (t, e, i) => e in t ? qI(t, e, { enumerable: !0, configurable: !0, writable: !0, value: i }) : t[e] = i, $e = (t, e, i) => jI(t, typeof e != "symbol" ? e + "" : e, i);
class zI extends Og {
  constructor(e, i) {
    super(e, i), this.core = e, this.logger = i, $e(this, "records", /* @__PURE__ */ new Map()), $e(this, "events", new rt.EventEmitter()), $e(this, "name", K_), $e(this, "version", V_), $e(this, "cached", []), $e(this, "initialized", !1), $e(this, "storagePrefix", Ot), $e(this, "init", async () => {
      this.initialized || (this.logger.trace("Initialized"), await this.restore(), this.cached.forEach((r) => this.records.set(r.id, r)), this.cached = [], this.registerEventListeners(), this.initialized = !0);
    }), $e(this, "set", (r, s, n) => {
      if (this.isInitialized(), this.logger.debug("Setting JSON-RPC request history record"), this.logger.trace({ type: "method", method: "set", topic: r, request: s, chainId: n }), this.records.has(s.id))
        return;
      const o = { id: s.id, topic: r, request: { method: s.method, params: s.params || null }, chainId: n, expiry: me(L.THIRTY_DAYS) };
      this.records.set(o.id, o), this.persist(), this.events.emit(pt.created, o);
    }), $e(this, "resolve", async (r) => {
      if (this.isInitialized(), this.logger.debug("Updating JSON-RPC response history record"), this.logger.trace({ type: "method", method: "update", response: r }), !this.records.has(r.id))
        return;
      const s = await this.getRecord(r.id);
      typeof s.response > "u" && (s.response = ct(r) ? { error: r.error } : { result: r.result }, this.records.set(s.id, s), this.persist(), this.events.emit(pt.updated, s));
    }), $e(this, "get", async (r, s) => (this.isInitialized(), this.logger.debug("Getting record"), this.logger.trace({ type: "method", method: "get", topic: r, id: s }), await this.getRecord(s))), $e(this, "delete", (r, s) => {
      this.isInitialized(), this.logger.debug("Deleting record"), this.logger.trace({ type: "method", method: "delete", id: s }), this.values.forEach((n) => {
        if (n.topic === r) {
          if (typeof s < "u" && n.id !== s)
            return;
          this.records.delete(n.id), this.events.emit(pt.deleted, n);
        }
      }), this.persist();
    }), $e(this, "exists", async (r, s) => (this.isInitialized(), this.records.has(s) ? (await this.getRecord(s)).topic === r : !1)), $e(this, "on", (r, s) => {
      this.events.on(r, s);
    }), $e(this, "once", (r, s) => {
      this.events.once(r, s);
    }), $e(this, "off", (r, s) => {
      this.events.off(r, s);
    }), $e(this, "removeListener", (r, s) => {
      this.events.removeListener(r, s);
    }), this.logger = je(i, this.name);
  }
  get context() {
    return Qe(this.logger);
  }
  get storageKey() {
    return this.storagePrefix + this.version + this.core.customStoragePrefix + "//" + this.name;
  }
  get size() {
    return this.records.size;
  }
  get keys() {
    return Array.from(this.records.keys());
  }
  get values() {
    return Array.from(this.records.values());
  }
  get pending() {
    const e = [];
    return this.values.forEach((i) => {
      if (typeof i.response < "u")
        return;
      const r = { topic: i.topic, request: Lt(i.request.method, i.request.params, i.id), chainId: i.chainId };
      return e.push(r);
    }), e;
  }
  async setJsonRpcRecords(e) {
    await this.core.storage.setItem(this.storageKey, e);
  }
  async getJsonRpcRecords() {
    return await this.core.storage.getItem(this.storageKey);
  }
  getRecord(e) {
    this.isInitialized();
    const i = this.records.get(e);
    if (!i) {
      const { message: r } = M("NO_MATCHING_KEY", `${this.name}: ${e}`);
      throw new Error(r);
    }
    return i;
  }
  async persist() {
    await this.setJsonRpcRecords(this.values), this.events.emit(pt.sync);
  }
  async restore() {
    try {
      const e = await this.getJsonRpcRecords();
      if (typeof e > "u" || !e.length)
        return;
      if (this.records.size) {
        const { message: i } = M("RESTORE_WILL_OVERRIDE", this.name);
        throw this.logger.error(i), new Error(i);
      }
      this.cached = e, this.logger.debug(`Successfully Restored records for ${this.name}`), this.logger.trace({ type: "method", method: "restore", records: this.values });
    } catch (e) {
      this.logger.debug(`Failed to Restore records for ${this.name}`), this.logger.error(e);
    }
  }
  registerEventListeners() {
    this.events.on(pt.created, (e) => {
      const i = pt.created;
      this.logger.info(`Emitting ${i}`), this.logger.debug({ type: "event", event: i, record: e });
    }), this.events.on(pt.updated, (e) => {
      const i = pt.updated;
      this.logger.info(`Emitting ${i}`), this.logger.debug({ type: "event", event: i, record: e });
    }), this.events.on(pt.deleted, (e) => {
      const i = pt.deleted;
      this.logger.info(`Emitting ${i}`), this.logger.debug({ type: "event", event: i, record: e });
    }), this.core.heartbeat.on(Ti.pulse, () => {
      this.cleanup();
    });
  }
  cleanup() {
    try {
      this.isInitialized();
      let e = !1;
      this.records.forEach((i) => {
        L.toMiliseconds(i.expiry || 0) - Date.now() <= 0 && (this.logger.info(`Deleting expired history log: ${i.id}`), this.records.delete(i.id), this.events.emit(pt.deleted, i, !1), e = !0);
      }), e && this.persist();
    } catch (e) {
      this.logger.warn(e);
    }
  }
  isInitialized() {
    if (!this.initialized) {
      const { message: e } = M("NOT_INITIALIZED", this.name);
      throw new Error(e);
    }
  }
}
var KI = Object.defineProperty, VI = (t, e, i) => e in t ? KI(t, e, { enumerable: !0, configurable: !0, writable: !0, value: i }) : t[e] = i, ke = (t, e, i) => VI(t, typeof e != "symbol" ? e + "" : e, i);
class HI extends Ug {
  constructor(e, i) {
    super(e, i), this.core = e, this.logger = i, ke(this, "expirations", /* @__PURE__ */ new Map()), ke(this, "events", new rt.EventEmitter()), ke(this, "name", H_), ke(this, "version", W_), ke(this, "cached", []), ke(this, "initialized", !1), ke(this, "storagePrefix", Ot), ke(this, "init", async () => {
      this.initialized || (this.logger.trace("Initialized"), await this.restore(), this.cached.forEach((r) => this.expirations.set(r.target, r)), this.cached = [], this.registerEventListeners(), this.initialized = !0);
    }), ke(this, "has", (r) => {
      try {
        const s = this.formatTarget(r);
        return typeof this.getExpiration(s) < "u";
      } catch {
        return !1;
      }
    }), ke(this, "set", (r, s) => {
      this.isInitialized();
      const n = this.formatTarget(r), o = { target: n, expiry: s };
      this.expirations.set(n, o), this.checkExpiry(n, o), this.events.emit(ot.created, { target: n, expiration: o });
    }), ke(this, "get", (r) => {
      this.isInitialized();
      const s = this.formatTarget(r);
      return this.getExpiration(s);
    }), ke(this, "del", (r) => {
      if (this.isInitialized(), this.has(r)) {
        const s = this.formatTarget(r), n = this.getExpiration(s);
        this.expirations.delete(s), this.events.emit(ot.deleted, { target: s, expiration: n });
      }
    }), ke(this, "on", (r, s) => {
      this.events.on(r, s);
    }), ke(this, "once", (r, s) => {
      this.events.once(r, s);
    }), ke(this, "off", (r, s) => {
      this.events.off(r, s);
    }), ke(this, "removeListener", (r, s) => {
      this.events.removeListener(r, s);
    }), this.logger = je(i, this.name);
  }
  get context() {
    return Qe(this.logger);
  }
  get storageKey() {
    return this.storagePrefix + this.version + this.core.customStoragePrefix + "//" + this.name;
  }
  get length() {
    return this.expirations.size;
  }
  get keys() {
    return Array.from(this.expirations.keys());
  }
  get values() {
    return Array.from(this.expirations.values());
  }
  formatTarget(e) {
    if (typeof e == "string")
      return iv(e);
    if (typeof e == "number")
      return rv(e);
    const { message: i } = M("UNKNOWN_TYPE", `Target type: ${typeof e}`);
    throw new Error(i);
  }
  async setExpirations(e) {
    await this.core.storage.setItem(this.storageKey, e);
  }
  async getExpirations() {
    return await this.core.storage.getItem(this.storageKey);
  }
  async persist() {
    await this.setExpirations(this.values), this.events.emit(ot.sync);
  }
  async restore() {
    try {
      const e = await this.getExpirations();
      if (typeof e > "u" || !e.length)
        return;
      if (this.expirations.size) {
        const { message: i } = M("RESTORE_WILL_OVERRIDE", this.name);
        throw this.logger.error(i), new Error(i);
      }
      this.cached = e, this.logger.debug(`Successfully Restored expirations for ${this.name}`), this.logger.trace({ type: "method", method: "restore", expirations: this.values });
    } catch (e) {
      this.logger.debug(`Failed to Restore expirations for ${this.name}`), this.logger.error(e);
    }
  }
  getExpiration(e) {
    const i = this.expirations.get(e);
    if (!i) {
      const { message: r } = M("NO_MATCHING_KEY", `${this.name}: ${e}`);
      throw this.logger.warn(r), new Error(r);
    }
    return i;
  }
  checkExpiry(e, i) {
    const { expiry: r } = i;
    L.toMiliseconds(r) - Date.now() <= 0 && this.expire(e, i);
  }
  expire(e, i) {
    this.expirations.delete(e), this.events.emit(ot.expired, { target: e, expiration: i });
  }
  checkExpirations() {
    this.core.relayer.connected && this.expirations.forEach((e, i) => this.checkExpiry(i, e));
  }
  registerEventListeners() {
    this.core.heartbeat.on(Ti.pulse, () => this.checkExpirations()), this.events.on(ot.created, (e) => {
      const i = ot.created;
      this.logger.info(`Emitting ${i}`), this.logger.debug({ type: "event", event: i, data: e }), this.persist();
    }), this.events.on(ot.expired, (e) => {
      const i = ot.expired;
      this.logger.info(`Emitting ${i}`), this.logger.debug({ type: "event", event: i, data: e }), this.persist();
    }), this.events.on(ot.deleted, (e) => {
      const i = ot.deleted;
      this.logger.info(`Emitting ${i}`), this.logger.debug({ type: "event", event: i, data: e }), this.persist();
    });
  }
  isInitialized() {
    if (!this.initialized) {
      const { message: e } = M("NOT_INITIALIZED", this.name);
      throw new Error(e);
    }
  }
}
var WI = Object.defineProperty, GI = (t, e, i) => e in t ? WI(t, e, { enumerable: !0, configurable: !0, writable: !0, value: i }) : t[e] = i, ge = (t, e, i) => GI(t, typeof e != "symbol" ? e + "" : e, i);
class YI extends Bg {
  constructor(e, i, r) {
    super(e, i, r), this.core = e, this.logger = i, this.store = r, ge(this, "name", G_), ge(this, "abortController"), ge(this, "isDevEnv"), ge(this, "verifyUrlV3", J_), ge(this, "storagePrefix", Ot), ge(this, "version", Jf), ge(this, "publicKey"), ge(this, "fetchPromise"), ge(this, "init", async () => {
      var s;
      this.isDevEnv || (this.publicKey = await this.store.getItem(this.storeKey), this.publicKey && L.toMiliseconds((s = this.publicKey) == null ? void 0 : s.expiresAt) < Date.now() && (this.logger.debug("verify v2 public key expired"), await this.removePublicKey()));
    }), ge(this, "register", async (s) => {
      if (!rr() || this.isDevEnv)
        return;
      const n = window.location.origin, { id: o, decryptedId: a } = s, c = `${this.verifyUrlV3}/attestation?projectId=${this.core.projectId}&origin=${n}&id=${o}&decryptedId=${a}`;
      try {
        const u = Si(), h = this.startAbortTimer(L.ONE_SECOND * 5), l = await new Promise((f, p) => {
          const d = () => {
            window.removeEventListener("message", y), u.body.removeChild(g), p("attestation aborted");
          };
          this.abortController.signal.addEventListener("abort", d);
          const g = u.createElement("iframe");
          g.src = c, g.style.display = "none", g.addEventListener("error", d, { signal: this.abortController.signal });
          const y = (E) => {
            if (E.data && typeof E.data == "string")
              try {
                const v = JSON.parse(E.data);
                if (v.type === "verify_attestation") {
                  if (ho(v.attestation).payload.id !== o)
                    return;
                  clearInterval(h), u.body.removeChild(g), this.abortController.signal.removeEventListener("abort", d), window.removeEventListener("message", y), f(v.attestation === null ? "" : v.attestation);
                }
              } catch (v) {
                this.logger.warn(v);
              }
          };
          u.body.appendChild(g), window.addEventListener("message", y, { signal: this.abortController.signal });
        });
        return this.logger.debug("jwt attestation", l), l;
      } catch (u) {
        this.logger.warn(u);
      }
      return "";
    }), ge(this, "resolve", async (s) => {
      if (this.isDevEnv)
        return "";
      const { attestationId: n, hash: o, encryptedId: a } = s;
      if (n === "") {
        this.logger.debug("resolve: attestationId is empty, skipping");
        return;
      }
      if (n) {
        if (ho(n).payload.id !== a)
          return;
        const u = await this.isValidJwtAttestation(n);
        if (u) {
          if (!u.isVerified) {
            this.logger.warn("resolve: jwt attestation: origin url not verified");
            return;
          }
          return u;
        }
      }
      if (!o)
        return;
      const c = this.getVerifyUrl(s?.verifyUrl);
      return this.fetchAttestation(o, c);
    }), ge(this, "fetchAttestation", async (s, n) => {
      this.logger.debug(`resolving attestation: ${s} from url: ${n}`);
      const o = this.startAbortTimer(L.ONE_SECOND * 5), a = await fetch(`${n}/attestation/${s}?v2Supported=true`, { signal: this.abortController.signal });
      return clearTimeout(o), a.status === 200 ? await a.json() : void 0;
    }), ge(this, "getVerifyUrl", (s) => {
      let n = s || Fr;
      return Z_.includes(n) || (this.logger.info(`verify url: ${n}, not included in trusted list, assigning default: ${Fr}`), n = Fr), n;
    }), ge(this, "fetchPublicKey", async () => {
      try {
        this.logger.debug(`fetching public key from: ${this.verifyUrlV3}`);
        const s = this.startAbortTimer(L.FIVE_SECONDS), n = await fetch(`${this.verifyUrlV3}/public-key`, { signal: this.abortController.signal });
        return clearTimeout(s), await n.json();
      } catch (s) {
        this.logger.warn(s);
      }
    }), ge(this, "persistPublicKey", async (s) => {
      this.logger.debug("persisting public key to local storage", s), await this.store.setItem(this.storeKey, s), this.publicKey = s;
    }), ge(this, "removePublicKey", async () => {
      this.logger.debug("removing verify v2 public key from storage"), await this.store.removeItem(this.storeKey), this.publicKey = void 0;
    }), ge(this, "isValidJwtAttestation", async (s) => {
      const n = await this.getPublicKey();
      try {
        if (n)
          return this.validateAttestation(s, n);
      } catch (a) {
        this.logger.error(a), this.logger.warn("error validating attestation");
      }
      const o = await this.fetchAndPersistPublicKey();
      try {
        if (o)
          return this.validateAttestation(s, o);
      } catch (a) {
        this.logger.error(a), this.logger.warn("error validating attestation");
      }
    }), ge(this, "getPublicKey", async () => this.publicKey ? this.publicKey : await this.fetchAndPersistPublicKey()), ge(this, "fetchAndPersistPublicKey", async () => {
      if (this.fetchPromise)
        return await this.fetchPromise, this.publicKey;
      this.fetchPromise = new Promise(async (n) => {
        const o = await this.fetchPublicKey();
        o && (await this.persistPublicKey(o), n(o));
      });
      const s = await this.fetchPromise;
      return this.fetchPromise = void 0, s;
    }), ge(this, "validateAttestation", (s, n) => {
      const o = QE(s, n.publicKey), a = { hasExpired: L.toMiliseconds(o.exp) < Date.now(), payload: o };
      if (a.hasExpired)
        throw this.logger.warn("resolve: jwt attestation expired"), new Error("JWT attestation expired");
      return { origin: a.payload.origin, isScam: a.payload.isScam, isVerified: a.payload.isVerified };
    }), this.logger = je(i, this.name), this.abortController = new AbortController(), this.isDevEnv = ua(), this.init();
  }
  get storeKey() {
    return this.storagePrefix + this.version + this.core.customStoragePrefix + "//verify:public:key";
  }
  get context() {
    return Qe(this.logger);
  }
  startAbortTimer(e) {
    return this.abortController = new AbortController(), setTimeout(() => this.abortController.abort(), L.toMiliseconds(e));
  }
}
var JI = Object.defineProperty, ZI = (t, e, i) => e in t ? JI(t, e, { enumerable: !0, configurable: !0, writable: !0, value: i }) : t[e] = i, eh = (t, e, i) => ZI(t, typeof e != "symbol" ? e + "" : e, i);
class QI extends Ng {
  constructor(e, i) {
    super(e, i), this.projectId = e, this.logger = i, eh(this, "context", Q_), eh(this, "registerDeviceToken", async (r) => {
      const { clientId: s, token: n, notificationType: o, enableEncrypted: a = !1 } = r, c = `${X_}/${this.projectId}/clients`;
      await fetch(c, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ client_id: s, type: o, token: n, always_raw: a }) });
    }), this.logger = je(i, this.context);
  }
}
var XI = Object.defineProperty, th = Object.getOwnPropertySymbols, eS = Object.prototype.hasOwnProperty, tS = Object.prototype.propertyIsEnumerable, Mo = (t, e, i) => e in t ? XI(t, e, { enumerable: !0, configurable: !0, writable: !0, value: i }) : t[e] = i, _r = (t, e) => {
  for (var i in e || (e = {}))
    eS.call(e, i) && Mo(t, i, e[i]);
  if (th)
    for (var i of th(e))
      tS.call(e, i) && Mo(t, i, e[i]);
  return t;
}, Ee = (t, e, i) => Mo(t, typeof e != "symbol" ? e + "" : e, i);
class iS extends kg {
  constructor(e, i, r = !0) {
    super(e, i, r), this.core = e, this.logger = i, Ee(this, "context", tx), Ee(this, "storagePrefix", Ot), Ee(this, "storageVersion", ex), Ee(this, "events", /* @__PURE__ */ new Map()), Ee(this, "shouldPersist", !1), Ee(this, "init", async () => {
      if (!ua())
        try {
          const s = { eventId: Lc(), timestamp: Date.now(), domain: this.getAppDomain(), props: { event: "INIT", type: "", properties: { client_id: await this.core.crypto.getClientId(), user_agent: Hl(this.core.relayer.protocol, this.core.relayer.version, Po) } } };
          await this.sendEvent([s]);
        } catch (s) {
          this.logger.warn(s);
        }
    }), Ee(this, "createEvent", (s) => {
      const { event: n = "ERROR", type: o = "", properties: { topic: a, trace: c } } = s, u = Lc(), h = this.core.projectId || "", l = Date.now(), f = _r({ eventId: u, timestamp: l, props: { event: n, type: o, properties: { topic: a, trace: c } }, bundleId: h, domain: this.getAppDomain() }, this.setMethods(u));
      return this.telemetryEnabled && (this.events.set(u, f), this.shouldPersist = !0), f;
    }), Ee(this, "getEvent", (s) => {
      const { eventId: n, topic: o } = s;
      if (n)
        return this.events.get(n);
      const a = Array.from(this.events.values()).find((c) => c.props.properties.topic === o);
      if (a)
        return _r(_r({}, a), this.setMethods(a.eventId));
    }), Ee(this, "deleteEvent", (s) => {
      const { eventId: n } = s;
      this.events.delete(n), this.shouldPersist = !0;
    }), Ee(this, "setEventListeners", () => {
      this.core.heartbeat.on(Ti.pulse, async () => {
        this.shouldPersist && await this.persist(), this.events.forEach((s) => {
          L.fromMiliseconds(Date.now()) - L.fromMiliseconds(s.timestamp) > ix && (this.events.delete(s.eventId), this.shouldPersist = !0);
        });
      });
    }), Ee(this, "setMethods", (s) => ({ addTrace: (n) => this.addTrace(s, n), setError: (n) => this.setError(s, n) })), Ee(this, "addTrace", (s, n) => {
      const o = this.events.get(s);
      o && (o.props.properties.trace.push(n), this.events.set(s, o), this.shouldPersist = !0);
    }), Ee(this, "setError", (s, n) => {
      const o = this.events.get(s);
      o && (o.props.type = n, o.timestamp = Date.now(), this.events.set(s, o), this.shouldPersist = !0);
    }), Ee(this, "persist", async () => {
      await this.core.storage.setItem(this.storageKey, Array.from(this.events.values())), this.shouldPersist = !1;
    }), Ee(this, "restore", async () => {
      try {
        const s = await this.core.storage.getItem(this.storageKey) || [];
        if (!s.length)
          return;
        s.forEach((n) => {
          this.events.set(n.eventId, _r(_r({}, n), this.setMethods(n.eventId)));
        });
      } catch (s) {
        this.logger.warn(s);
      }
    }), Ee(this, "submit", async () => {
      if (!this.telemetryEnabled || this.events.size === 0)
        return;
      const s = [];
      for (const [n, o] of this.events)
        o.props.type && s.push(o);
      if (s.length !== 0)
        try {
          if ((await this.sendEvent(s)).ok)
            for (const n of s)
              this.events.delete(n.eventId), this.shouldPersist = !0;
        } catch (n) {
          this.logger.warn(n);
        }
    }), Ee(this, "sendEvent", async (s) => {
      const n = this.getAppDomain() ? "" : "&sp=desktop";
      return await fetch(`${rx}?projectId=${this.core.projectId}&st=events_sdk&sv=js-${Po}${n}`, { method: "POST", body: JSON.stringify(s) });
    }), Ee(this, "getAppDomain", () => Vl().url), this.logger = je(i, this.context), this.telemetryEnabled = r, r ? this.restore().then(async () => {
      await this.submit(), this.setEventListeners();
    }) : this.persist();
  }
  get storageKey() {
    return this.storagePrefix + this.storageVersion + this.core.customStoragePrefix + "//" + this.context;
  }
}
var rS = Object.defineProperty, ih = Object.getOwnPropertySymbols, sS = Object.prototype.hasOwnProperty, nS = Object.prototype.propertyIsEnumerable, qo = (t, e, i) => e in t ? rS(t, e, { enumerable: !0, configurable: !0, writable: !0, value: i }) : t[e] = i, rh = (t, e) => {
  for (var i in e || (e = {}))
    sS.call(e, i) && qo(t, i, e[i]);
  if (ih)
    for (var i of ih(e))
      nS.call(e, i) && qo(t, i, e[i]);
  return t;
}, ce = (t, e, i) => qo(t, typeof e != "symbol" ? e + "" : e, i);
class Sa extends Sg {
  constructor(e) {
    var i;
    super(e), ce(this, "protocol", Yf), ce(this, "version", Jf), ce(this, "name", Ws), ce(this, "relayUrl"), ce(this, "projectId"), ce(this, "customStoragePrefix"), ce(this, "events", new rt.EventEmitter()), ce(this, "logger"), ce(this, "heartbeat"), ce(this, "relayer"), ce(this, "crypto"), ce(this, "storage"), ce(this, "history"), ce(this, "expirer"), ce(this, "pairing"), ce(this, "verify"), ce(this, "echoClient"), ce(this, "linkModeSupportedApps"), ce(this, "eventClient"), ce(this, "initialized", !1), ce(this, "logChunkController"), ce(this, "on", (a, c) => this.events.on(a, c)), ce(this, "once", (a, c) => this.events.once(a, c)), ce(this, "off", (a, c) => this.events.off(a, c)), ce(this, "removeListener", (a, c) => this.events.removeListener(a, c)), ce(this, "dispatchEnvelope", ({ topic: a, message: c, sessionExists: u }) => {
      if (!a || !c)
        return;
      const h = { topic: a, message: c, publishedAt: Date.now(), transportType: he.link_mode };
      this.relayer.onLinkMessageEvent(h, { sessionExists: u });
    });
    const r = this.getGlobalCore(e?.customStoragePrefix);
    if (r)
      try {
        return this.customStoragePrefix = r.customStoragePrefix, this.logger = r.logger, this.heartbeat = r.heartbeat, this.crypto = r.crypto, this.history = r.history, this.expirer = r.expirer, this.storage = r.storage, this.relayer = r.relayer, this.pairing = r.pairing, this.verify = r.verify, this.echoClient = r.echoClient, this.linkModeSupportedApps = r.linkModeSupportedApps, this.eventClient = r.eventClient, this.initialized = r.initialized, this.logChunkController = r.logChunkController, r;
      } catch (a) {
        console.warn("Failed to copy global core", a);
      }
    this.projectId = e?.projectId, this.relayUrl = e?.relayUrl || Qf, this.customStoragePrefix = e != null && e.customStoragePrefix ? `:${e.customStoragePrefix}` : "";
    const s = Vo({ level: typeof e?.logger == "string" && e.logger ? e.logger : I_.logger, name: Ws }), { logger: n, chunkLoggerController: o } = _g({ opts: s, maxSizeInBytes: e?.maxLogBlobSizeInBytes, loggerOverride: e?.logger });
    this.logChunkController = o, (i = this.logChunkController) != null && i.downloadLogsBlobInBrowser && (window.downloadLogsBlobInBrowser = async () => {
      var a, c;
      (a = this.logChunkController) != null && a.downloadLogsBlobInBrowser && ((c = this.logChunkController) == null || c.downloadLogsBlobInBrowser({ clientId: await this.crypto.getClientId() }));
    }), this.logger = je(n, this.name), this.heartbeat = new fp(), this.crypto = new R8(this, this.logger, e?.keychain), this.history = new zI(this, this.logger), this.expirer = new HI(this, this.logger), this.storage = e != null && e.storage ? e.storage : new Gp(rh(rh({}, S_), e?.storageOptions)), this.relayer = new oI({ core: this, logger: this.logger, relayUrl: this.relayUrl, projectId: this.projectId }), this.pairing = new MI(this, this.logger), this.verify = new YI(this, this.logger, this.storage), this.echoClient = new QI(this.projectId || "", this.logger), this.linkModeSupportedApps = [], this.eventClient = new iS(this, this.logger, e?.telemetryEnabled), this.setGlobalCore(this);
  }
  static async init(e) {
    const i = new Sa(e);
    await i.initialize();
    const r = await i.crypto.getClientId();
    return await i.storage.setItem(L_, r), i;
  }
  get context() {
    return Qe(this.logger);
  }
  async start() {
    this.initialized || await this.initialize();
  }
  async getLogsBlob() {
    var e;
    return (e = this.logChunkController) == null ? void 0 : e.logsToBlob({ clientId: await this.crypto.getClientId() });
  }
  async addLinkModeSupportedApp(e) {
    this.linkModeSupportedApps.includes(e) || (this.linkModeSupportedApps.push(e), await this.storage.setItem(Uu, this.linkModeSupportedApps));
  }
  async initialize() {
    this.logger.trace("Initialized");
    try {
      await this.crypto.init(), await this.history.init(), await this.expirer.init(), await this.relayer.init(), await this.heartbeat.init(), await this.pairing.init(), this.linkModeSupportedApps = await this.storage.getItem(Uu) || [], this.initialized = !0, this.logger.info("Core Initialization Success");
    } catch (e) {
      throw this.logger.warn(`Core Initialization Failure at epoch ${Date.now()}`, e), this.logger.error(e.message), e;
    }
  }
  getGlobalCore(e = "") {
    try {
      if (this.isGlobalCoreDisabled())
        return;
      const i = `_walletConnectCore_${e}`, r = `${i}_count`;
      return globalThis[r] = (globalThis[r] || 0) + 1, globalThis[r] > 1 && console.warn(`WalletConnect Core is already initialized. This is probably a mistake and can lead to unexpected behavior. Init() was called ${globalThis[r]} times.`), globalThis[i];
    } catch (i) {
      console.warn("Failed to get global WalletConnect core", i);
      return;
    }
  }
  setGlobalCore(e) {
    var i;
    try {
      if (this.isGlobalCoreDisabled())
        return;
      const r = `_walletConnectCore_${((i = e.opts) == null ? void 0 : i.customStoragePrefix) || ""}`;
      globalThis[r] = e;
    } catch (r) {
      console.warn("Failed to set global WalletConnect core", r);
    }
  }
  isGlobalCoreDisabled() {
    try {
      return typeof process < "u" && process.env.DISABLE_GLOBAL_CORE === "true";
    } catch {
      return !0;
    }
  }
}
const oS = Sa, ld = "wc", fd = 2, dd = "client", Da = `${ld}@${fd}:${dd}:`, Jn = { name: dd, logger: "error", controller: !1, relayUrl: "wss://relay.walletconnect.org" }, sh = "WALLETCONNECT_DEEPLINK_CHOICE", aS = "proposal", nh = "Proposal expired", cS = "session", Vi = L.SEVEN_DAYS, uS = "engine", Oe = { wc_sessionPropose: { req: { ttl: L.FIVE_MINUTES, prompt: !0, tag: 1100 }, res: { ttl: L.FIVE_MINUTES, prompt: !1, tag: 1101 }, reject: { ttl: L.FIVE_MINUTES, prompt: !1, tag: 1120 }, autoReject: { ttl: L.FIVE_MINUTES, prompt: !1, tag: 1121 } }, wc_sessionSettle: { req: { ttl: L.FIVE_MINUTES, prompt: !1, tag: 1102 }, res: { ttl: L.FIVE_MINUTES, prompt: !1, tag: 1103 } }, wc_sessionUpdate: { req: { ttl: L.ONE_DAY, prompt: !1, tag: 1104 }, res: { ttl: L.ONE_DAY, prompt: !1, tag: 1105 } }, wc_sessionExtend: { req: { ttl: L.ONE_DAY, prompt: !1, tag: 1106 }, res: { ttl: L.ONE_DAY, prompt: !1, tag: 1107 } }, wc_sessionRequest: { req: { ttl: L.FIVE_MINUTES, prompt: !0, tag: 1108 }, res: { ttl: L.FIVE_MINUTES, prompt: !1, tag: 1109 } }, wc_sessionEvent: { req: { ttl: L.FIVE_MINUTES, prompt: !0, tag: 1110 }, res: { ttl: L.FIVE_MINUTES, prompt: !1, tag: 1111 } }, wc_sessionDelete: { req: { ttl: L.ONE_DAY, prompt: !1, tag: 1112 }, res: { ttl: L.ONE_DAY, prompt: !1, tag: 1113 } }, wc_sessionPing: { req: { ttl: L.ONE_DAY, prompt: !1, tag: 1114 }, res: { ttl: L.ONE_DAY, prompt: !1, tag: 1115 } }, wc_sessionAuthenticate: { req: { ttl: L.ONE_HOUR, prompt: !0, tag: 1116 }, res: { ttl: L.ONE_HOUR, prompt: !1, tag: 1117 }, reject: { ttl: L.FIVE_MINUTES, prompt: !1, tag: 1118 }, autoReject: { ttl: L.FIVE_MINUTES, prompt: !1, tag: 1119 } } }, Zn = { min: L.FIVE_MINUTES, max: L.SEVEN_DAYS }, _t = { idle: "IDLE", active: "ACTIVE" }, hS = { eth_sendTransaction: { key: "" }, eth_sendRawTransaction: { key: "" }, wallet_sendCalls: { key: "" }, solana_signTransaction: { key: "signature" }, solana_signAllTransactions: { key: "transactions" }, solana_signAndSendTransaction: { key: "signature" }, sui_signAndExecuteTransaction: { key: "digest" }, sui_signTransaction: { key: "" }, hedera_signAndExecuteTransaction: { key: "transactionId" }, hedera_executeTransaction: { key: "transactionId" }, near_signTransaction: { key: "" }, near_signTransactions: { key: "" }, tron_signTransaction: { key: "txID" }, xrpl_signTransaction: { key: "" }, xrpl_signTransactionFor: { key: "" }, algo_signTxn: { key: "" }, sendTransfer: { key: "txid" }, stacks_stxTransfer: { key: "txId" }, polkadot_signTransaction: { key: "" }, cosmos_signDirect: { key: "" } }, lS = "request", fS = ["wc_sessionPropose", "wc_sessionRequest", "wc_authRequest", "wc_sessionAuthenticate"], dS = "wc", pS = "auth", gS = "authKeys", yS = "pairingTopics", wS = "requests", dn = `${dS}@${1.5}:${pS}:`, Cs = `${dn}:PUB_KEY`;
var mS = Object.defineProperty, bS = Object.defineProperties, vS = Object.getOwnPropertyDescriptors, oh = Object.getOwnPropertySymbols, ES = Object.prototype.hasOwnProperty, _S = Object.prototype.propertyIsEnumerable, jo = (t, e, i) => e in t ? mS(t, e, { enumerable: !0, configurable: !0, writable: !0, value: i }) : t[e] = i, ne = (t, e) => {
  for (var i in e || (e = {}))
    ES.call(e, i) && jo(t, i, e[i]);
  if (oh)
    for (var i of oh(e))
      _S.call(e, i) && jo(t, i, e[i]);
  return t;
}, Le = (t, e) => bS(t, vS(e)), F = (t, e, i) => jo(t, typeof e != "symbol" ? e + "" : e, i);
class xS extends jg {
  constructor(e) {
    super(e), F(this, "name", uS), F(this, "events", new mh()), F(this, "initialized", !1), F(this, "requestQueue", { state: _t.idle, queue: [] }), F(this, "sessionRequestQueue", { state: _t.idle, queue: [] }), F(this, "emittedSessionRequests", new fv({ limit: 500 })), F(this, "requestQueueDelay", L.ONE_SECOND), F(this, "expectedPairingMethodMap", /* @__PURE__ */ new Map()), F(this, "recentlyDeletedMap", /* @__PURE__ */ new Map()), F(this, "recentlyDeletedLimit", 200), F(this, "relayMessageCache", []), F(this, "pendingSessions", /* @__PURE__ */ new Map()), F(this, "init", async () => {
      this.initialized || (await this.cleanup(), this.registerRelayerEvents(), this.registerExpirerEvents(), this.registerPairingEvents(), await this.registerLinkModeListeners(), this.client.core.pairing.register({ methods: Object.keys(Oe) }), this.initialized = !0, setTimeout(async () => {
        await this.processPendingMessageEvents(), this.sessionRequestQueue.queue = this.getPendingSessionRequests(), this.processSessionRequestQueue();
      }, L.toMiliseconds(this.requestQueueDelay)));
    }), F(this, "connect", async (i) => {
      this.isInitialized(), await this.confirmOnlineStateOrThrow();
      const r = Le(ne({}, i), { requiredNamespaces: i.requiredNamespaces || {}, optionalNamespaces: i.optionalNamespaces || {} });
      await this.isValidConnect(r), r.optionalNamespaces = g3(r.requiredNamespaces, r.optionalNamespaces), r.requiredNamespaces = {};
      const { pairingTopic: s, requiredNamespaces: n, optionalNamespaces: o, sessionProperties: a, scopedProperties: c, relays: u } = r;
      let h = s, l, f = !1;
      try {
        if (h) {
          const R = this.client.core.pairing.pairings.get(h);
          this.client.logger.warn("connect() with existing pairing topic is deprecated and will be removed in the next major release."), f = R.active;
        }
      } catch (R) {
        throw this.client.logger.error(`connect() -> pairing.get(${h}) failed`), R;
      }
      if (!h || !f) {
        const { topic: R, uri: B } = await this.client.core.pairing.create({ internal: { skipSubscribe: !0 } });
        h = R, l = B;
      }
      if (!h) {
        const { message: R } = M("NO_MATCHING_KEY", `connect() pairing topic: ${h}`);
        throw new Error(R);
      }
      const p = await this.client.core.crypto.generateKeyPair(), d = Oe.wc_sessionPropose.req.ttl || L.FIVE_MINUTES, g = me(d), y = Le(ne(ne({ requiredNamespaces: n, optionalNamespaces: o, relays: u ?? [{ protocol: Zf }], proposer: { publicKey: p, metadata: this.client.metadata }, expiryTimestamp: g, pairingTopic: h }, a && { sessionProperties: a }), c && { scopedProperties: c }), { id: It() }), E = se("session_connect", y.id), { reject: v, resolve: m, done: D } = yi(d, nh), I = ({ id: R }) => {
        R === y.id && (this.client.events.off("proposal_expire", I), this.pendingSessions.delete(y.id), this.events.emit(E, { error: { message: nh, code: 0 } }));
      };
      return this.client.events.on("proposal_expire", I), this.events.once(E, ({ error: R, session: B }) => {
        this.client.events.off("proposal_expire", I), R ? v(R) : B && m(B);
      }), await this.sendProposeSession({ proposal: y, publishOpts: { internal: { throwOnFailedPublish: !0 }, tvf: { correlationId: y.id } } }), await this.setProposal(y.id, y), { uri: l, approval: D };
    }), F(this, "pair", async (i) => {
      this.isInitialized(), await this.confirmOnlineStateOrThrow();
      try {
        return await this.client.core.pairing.pair(i);
      } catch (r) {
        throw this.client.logger.error("pair() failed"), r;
      }
    }), F(this, "approve", async (i) => {
      var r, s, n;
      const o = this.client.core.eventClient.createEvent({ properties: { topic: (r = i?.id) == null ? void 0 : r.toString(), trace: [Xt.session_approve_started] } });
      try {
        this.isInitialized(), await this.confirmOnlineStateOrThrow();
      } catch (w) {
        throw o.setError(br.no_internet_connection), w;
      }
      try {
        await this.isValidProposalId(i?.id);
      } catch (w) {
        throw this.client.logger.error(`approve() -> proposal.get(${i?.id}) failed`), o.setError(br.proposal_not_found), w;
      }
      try {
        await this.isValidApprove(i);
      } catch (w) {
        throw this.client.logger.error("approve() -> isValidApprove() failed"), o.setError(br.session_approve_namespace_validation_failure), w;
      }
      const { id: a, relayProtocol: c, namespaces: u, sessionProperties: h, scopedProperties: l, sessionConfig: f } = i, p = this.client.proposal.get(a);
      this.client.core.eventClient.deleteEvent({ eventId: o.eventId });
      const { pairingTopic: d, proposer: g, requiredNamespaces: y, optionalNamespaces: E } = p;
      let v = (s = this.client.core.eventClient) == null ? void 0 : s.getEvent({ topic: d });
      v || (v = (n = this.client.core.eventClient) == null ? void 0 : n.createEvent({ type: Xt.session_approve_started, properties: { topic: d, trace: [Xt.session_approve_started, Xt.session_namespaces_validation_success] } }));
      const m = await this.client.core.crypto.generateKeyPair(), D = g.publicKey, I = await this.client.core.crypto.generateSharedKey(m, D), R = ne(ne(ne({ relay: { protocol: c ?? "irn" }, namespaces: u, controller: { publicKey: m, metadata: this.client.metadata }, expiry: me(Vi) }, h && { sessionProperties: h }), l && { scopedProperties: l }), f && { sessionConfig: f }), B = he.relay;
      v.addTrace(Xt.subscribing_session_topic);
      try {
        await this.client.core.relayer.subscribe(I, { transportType: B, internal: { skipSubscribe: !0 } });
      } catch (w) {
        throw v.setError(br.subscribe_session_topic_failure), w;
      }
      v.addTrace(Xt.subscribe_session_topic_success);
      const C = Le(ne({}, R), { topic: I, requiredNamespaces: y, optionalNamespaces: E, pairingTopic: d, acknowledged: !1, self: R.controller, peer: { publicKey: g.publicKey, metadata: g.metadata }, controller: m, transportType: he.relay });
      await this.client.session.set(I, C), v.addTrace(Xt.store_session);
      try {
        await this.sendApproveSession({ sessionTopic: I, proposal: p, pairingProposalResponse: { relay: { protocol: c ?? "irn" }, responderPublicKey: m }, sessionSettleRequest: R, publishOpts: { internal: { throwOnFailedPublish: !0 }, tvf: { correlationId: a } } }), v.addTrace(Xt.session_approve_publish_success);
      } catch (w) {
        throw this.client.logger.error(w), this.client.session.delete(I, le("USER_DISCONNECTED")), await this.client.core.relayer.unsubscribe(I), w;
      }
      return this.client.core.eventClient.deleteEvent({ eventId: v.eventId }), await this.client.core.pairing.updateMetadata({ topic: d, metadata: g.metadata }), await this.deleteProposal(a), await this.client.core.pairing.activate({ topic: d }), await this.setExpiry(I, me(Vi)), { topic: I, acknowledged: () => Promise.resolve(this.client.session.get(I)) };
    }), F(this, "reject", async (i) => {
      this.isInitialized(), await this.confirmOnlineStateOrThrow();
      try {
        await this.isValidReject(i);
      } catch (o) {
        throw this.client.logger.error("reject() -> isValidReject() failed"), o;
      }
      const { id: r, reason: s } = i;
      let n;
      try {
        n = this.client.proposal.get(r).pairingTopic;
      } catch (o) {
        throw this.client.logger.error(`reject() -> proposal.get(${r}) failed`), o;
      }
      n && await this.sendError({ id: r, topic: n, error: s, rpcOpts: Oe.wc_sessionPropose.reject }), await this.deleteProposal(r);
    }), F(this, "update", async (i) => {
      this.isInitialized(), await this.confirmOnlineStateOrThrow();
      try {
        await this.isValidUpdate(i);
      } catch (l) {
        throw this.client.logger.error("update() -> isValidUpdate() failed"), l;
      }
      const { topic: r, namespaces: s } = i, { done: n, resolve: o, reject: a } = yi(), c = It(), u = ni().toString(), h = this.client.session.get(r).namespaces;
      return this.events.once(se("session_update", c), ({ error: l }) => {
        l ? a(l) : o();
      }), await this.client.session.update(r, { namespaces: s }), await this.sendRequest({ topic: r, method: "wc_sessionUpdate", params: { namespaces: s }, throwOnFailedPublish: !0, clientRpcId: c, relayRpcId: u }).catch((l) => {
        this.client.logger.error(l), this.client.session.update(r, { namespaces: h }), a(l);
      }), { acknowledged: n };
    }), F(this, "extend", async (i) => {
      this.isInitialized(), await this.confirmOnlineStateOrThrow();
      try {
        await this.isValidExtend(i);
      } catch (c) {
        throw this.client.logger.error("extend() -> isValidExtend() failed"), c;
      }
      const { topic: r } = i, s = It(), { done: n, resolve: o, reject: a } = yi();
      return this.events.once(se("session_extend", s), ({ error: c }) => {
        c ? a(c) : o();
      }), await this.setExpiry(r, me(Vi)), this.sendRequest({ topic: r, method: "wc_sessionExtend", params: {}, clientRpcId: s, throwOnFailedPublish: !0 }).catch((c) => {
        a(c);
      }), { acknowledged: n };
    }), F(this, "request", async (i) => {
      this.isInitialized();
      try {
        await this.isValidRequest(i);
      } catch (y) {
        throw this.client.logger.error("request() -> isValidRequest() failed"), y;
      }
      const { chainId: r, request: s, topic: n, expiry: o = Oe.wc_sessionRequest.req.ttl } = i, a = this.client.session.get(n);
      a?.transportType === he.relay && await this.confirmOnlineStateOrThrow();
      const c = It(), u = ni().toString(), { done: h, resolve: l, reject: f } = yi(o, "Request expired. Please try again.");
      this.events.once(se("session_request", c), ({ error: y, result: E }) => {
        y ? f(y) : l(E);
      });
      const p = "wc_sessionRequest", d = this.getAppLinkIfEnabled(a.peer.metadata, a.transportType);
      if (d)
        return await this.sendRequest({ clientRpcId: c, relayRpcId: u, topic: n, method: p, params: { request: Le(ne({}, s), { expiryTimestamp: me(o) }), chainId: r }, expiry: o, throwOnFailedPublish: !0, appLink: d }).catch((y) => f(y)), this.client.events.emit("session_request_sent", { topic: n, request: s, chainId: r, id: c }), await h();
      const g = { request: Le(ne({}, s), { expiryTimestamp: me(o) }), chainId: r };
      return await Promise.all([new Promise(async (y) => {
        await this.sendRequest({ clientRpcId: c, relayRpcId: u, topic: n, method: p, params: g, expiry: o, throwOnFailedPublish: !0, tvf: this.getTVFParams(c, g) }).catch((E) => f(E)), this.client.events.emit("session_request_sent", { topic: n, request: s, chainId: r, id: c }), y();
      }), new Promise(async (y) => {
        var E;
        if (!((E = a.sessionConfig) != null && E.disableDeepLink)) {
          const v = await av(this.client.core.storage, sh);
          await sv({ id: c, topic: n, wcDeepLink: v });
        }
        y();
      }), h()]).then((y) => y[2]);
    }), F(this, "respond", async (i) => {
      this.isInitialized(), await this.isValidRespond(i);
      const { topic: r, response: s } = i, { id: n } = s, o = this.client.session.get(r);
      o.transportType === he.relay && await this.confirmOnlineStateOrThrow();
      const a = this.getAppLinkIfEnabled(o.peer.metadata, o.transportType);
      St(s) ? await this.sendResult({ id: n, topic: r, result: s.result, throwOnFailedPublish: !0, appLink: a }) : ct(s) && await this.sendError({ id: n, topic: r, error: s.error, appLink: a }), this.cleanupAfterResponse(i);
    }), F(this, "ping", async (i) => {
      this.isInitialized(), await this.confirmOnlineStateOrThrow();
      try {
        await this.isValidPing(i);
      } catch (s) {
        throw this.client.logger.error("ping() -> isValidPing() failed"), s;
      }
      const { topic: r } = i;
      if (this.client.session.keys.includes(r)) {
        const s = It(), n = ni().toString(), { done: o, resolve: a, reject: c } = yi();
        this.events.once(se("session_ping", s), ({ error: u }) => {
          u ? c(u) : a();
        }), await Promise.all([this.sendRequest({ topic: r, method: "wc_sessionPing", params: {}, throwOnFailedPublish: !0, clientRpcId: s, relayRpcId: n }), o()]);
      } else
        this.client.core.pairing.pairings.keys.includes(r) && (this.client.logger.warn("ping() on pairing topic is deprecated and will be removed in the next major release."), await this.client.core.pairing.ping({ topic: r }));
    }), F(this, "emit", async (i) => {
      this.isInitialized(), await this.confirmOnlineStateOrThrow(), await this.isValidEmit(i);
      const { topic: r, event: s, chainId: n } = i, o = ni().toString(), a = It();
      await this.sendRequest({ topic: r, method: "wc_sessionEvent", params: { event: s, chainId: n }, throwOnFailedPublish: !0, relayRpcId: o, clientRpcId: a });
    }), F(this, "disconnect", async (i) => {
      this.isInitialized(), await this.confirmOnlineStateOrThrow(), await this.isValidDisconnect(i);
      const { topic: r } = i;
      if (this.client.session.keys.includes(r))
        await this.sendRequest({ topic: r, method: "wc_sessionDelete", params: le("USER_DISCONNECTED"), throwOnFailedPublish: !0 }), await this.deleteSession({ topic: r, emitEvent: !1 });
      else if (this.client.core.pairing.pairings.keys.includes(r))
        await this.client.core.pairing.disconnect({ topic: r });
      else {
        const { message: s } = M("MISMATCHED_TOPIC", `Session or pairing topic not found: ${r}`);
        throw new Error(s);
      }
    }), F(this, "find", (i) => (this.isInitialized(), this.client.session.getAll().filter((r) => m3(r, i)))), F(this, "getPendingSessionRequests", () => this.client.pendingRequest.getAll()), F(this, "authenticate", async (i, r) => {
      var s;
      this.isInitialized(), this.isValidAuthenticate(i);
      const n = r && this.client.core.linkModeSupportedApps.includes(r) && ((s = this.client.metadata.redirect) == null ? void 0 : s.linkMode), o = n ? he.link_mode : he.relay;
      o === he.relay && await this.confirmOnlineStateOrThrow();
      const { chains: a, statement: c = "", uri: u, domain: h, nonce: l, type: f, exp: p, nbf: d, methods: g = [], expiry: y } = i, E = [...i.resources || []], { topic: v, uri: m } = await this.client.core.pairing.create({ methods: ["wc_sessionAuthenticate"], transportType: o });
      this.client.logger.info({ message: "Generated new pairing", pairing: { topic: v, uri: m } });
      const D = await this.client.core.crypto.generateKeyPair(), I = Os(D);
      if (await Promise.all([this.client.auth.authKeys.set(Cs, { responseTopic: I, publicKey: D }), this.client.auth.pairingTopics.set(I, { topic: I, pairingTopic: v })]), await this.client.core.relayer.subscribe(I, { transportType: o }), this.client.logger.info(`sending request to new pairing topic: ${v}`), g.length > 0) {
        const { namespace: A } = As(a[0]);
        let U = x2(A, "request", g);
        $s(E) && (U = S2(U, E.pop())), E.push(U);
      }
      const R = y && y > Oe.wc_sessionAuthenticate.req.ttl ? y : Oe.wc_sessionAuthenticate.req.ttl, B = { authPayload: { type: f ?? "caip122", chains: a, statement: c, aud: u, domain: h, version: "1", nonce: l, iat: (/* @__PURE__ */ new Date()).toISOString(), exp: p, nbf: d, resources: E }, requester: { publicKey: D, metadata: this.client.metadata }, expiryTimestamp: me(R) }, C = { eip155: { chains: a, methods: [.../* @__PURE__ */ new Set(["personal_sign", ...g])], events: ["chainChanged", "accountsChanged"] } }, w = { requiredNamespaces: {}, optionalNamespaces: C, relays: [{ protocol: "irn" }], pairingTopic: v, proposer: { publicKey: D, metadata: this.client.metadata }, expiryTimestamp: me(Oe.wc_sessionPropose.req.ttl), id: It() }, { done: O, resolve: _, reject: $ } = yi(R, "Request expired"), P = It(), k = se("session_connect", w.id), x = se("session_request", P), b = async ({ error: A, session: U }) => {
        this.events.off(x, S), A ? $(A) : U && _({ session: U });
      }, S = async (A) => {
        var U, N, j;
        if (await this.deletePendingAuthRequest(P, { message: "fulfilled", code: 0 }), A.error) {
          const J = le("WC_METHOD_UNSUPPORTED", "wc_sessionAuthenticate");
          return A.error.code === J.code ? void 0 : (this.events.off(k, b), $(A.error.message));
        }
        await this.deleteProposal(w.id), this.events.off(k, b);
        const { cacaos: z, responder: K } = A.result, V = [], H = [];
        for (const J of z) {
          await Jc({ cacao: J, projectId: this.client.core.projectId }) || (this.client.logger.error(J, "Signature verification failed"), $(le("SESSION_SETTLEMENT_FAILED", "Signature verification failed")));
          const { p: fe } = J, Ie = $s(fe.resources), ui = [Eo(fe.iss)], ss = js(fe.iss);
          if (Ie) {
            const Fi = Zc(Ie), gn = Qc(Ie);
            V.push(...Fi), ui.push(...gn);
          }
          for (const Fi of ui)
            H.push(`${Fi}:${ss}`);
        }
        const re = await this.client.core.crypto.generateSharedKey(D, K.publicKey);
        let ie;
        V.length > 0 && (ie = { topic: re, acknowledged: !0, self: { publicKey: D, metadata: this.client.metadata }, peer: K, controller: K.publicKey, expiry: me(Vi), requiredNamespaces: {}, optionalNamespaces: {}, relay: { protocol: "irn" }, pairingTopic: v, namespaces: _u([...new Set(V)], [...new Set(H)]), transportType: o }, await this.client.core.relayer.subscribe(re, { transportType: o }), await this.client.session.set(re, ie), v && await this.client.core.pairing.updateMetadata({ topic: v, metadata: K.metadata }), ie = this.client.session.get(re)), (U = this.client.metadata.redirect) != null && U.linkMode && (N = K.metadata.redirect) != null && N.linkMode && (j = K.metadata.redirect) != null && j.universal && r && (this.client.core.addLinkModeSupportedApp(K.metadata.redirect.universal), this.client.session.update(re, { transportType: he.link_mode })), _({ auths: z, session: ie });
      };
      this.events.once(k, b), this.events.once(x, S);
      let T;
      try {
        if (n) {
          const A = Lt("wc_sessionAuthenticate", B, P);
          this.client.core.history.set(v, A);
          const U = await this.client.core.crypto.encode("", A, { type: is, encoding: si });
          T = Es(r, v, U);
        } else
          await Promise.all([this.sendRequest({ topic: v, method: "wc_sessionAuthenticate", params: B, expiry: i.expiry, throwOnFailedPublish: !0, clientRpcId: P }), this.sendRequest({ topic: v, method: "wc_sessionPropose", params: w, expiry: Oe.wc_sessionPropose.req.ttl, throwOnFailedPublish: !0, clientRpcId: w.id })]);
      } catch (A) {
        throw this.events.off(k, b), this.events.off(x, S), A;
      }
      return await this.setProposal(w.id, w), await this.setAuthRequest(P, { request: Le(ne({}, B), { verifyContext: {} }), pairingTopic: v, transportType: o }), { uri: T ?? m, response: O };
    }), F(this, "approveSessionAuthenticate", async (i) => {
      const { id: r, auths: s } = i, n = this.client.core.eventClient.createEvent({ properties: { topic: r.toString(), trace: [di.authenticated_session_approve_started] } });
      try {
        this.isInitialized();
      } catch (y) {
        throw n.setError(vr.no_internet_connection), y;
      }
      const o = this.getPendingAuthRequest(r);
      if (!o)
        throw n.setError(vr.authenticated_session_pending_request_not_found), new Error(`Could not find pending auth request with id ${r}`);
      const a = o.transportType || he.relay;
      a === he.relay && await this.confirmOnlineStateOrThrow();
      const c = o.requester.publicKey, u = await this.client.core.crypto.generateKeyPair(), h = Os(c), l = { type: Mt, receiverPublicKey: c, senderPublicKey: u }, f = [], p = [];
      for (const y of s) {
        if (!await Jc({ cacao: y, projectId: this.client.core.projectId })) {
          n.setError(vr.invalid_cacao);
          const I = le("SESSION_SETTLEMENT_FAILED", "Signature verification failed");
          throw await this.sendError({ id: r, topic: h, error: I, encodeOpts: l }), new Error(I.message);
        }
        n.addTrace(di.cacaos_verified);
        const { p: E } = y, v = $s(E.resources), m = [Eo(E.iss)], D = js(E.iss);
        if (v) {
          const I = Zc(v), R = Qc(v);
          f.push(...I), m.push(...R);
        }
        for (const I of m)
          p.push(`${I}:${D}`);
      }
      const d = await this.client.core.crypto.generateSharedKey(u, c);
      n.addTrace(di.create_authenticated_session_topic);
      let g;
      if (f?.length > 0) {
        g = { topic: d, acknowledged: !0, self: { publicKey: u, metadata: this.client.metadata }, peer: { publicKey: c, metadata: o.requester.metadata }, controller: c, expiry: me(Vi), authentication: s, requiredNamespaces: {}, optionalNamespaces: {}, relay: { protocol: "irn" }, pairingTopic: o.pairingTopic, namespaces: _u([...new Set(f)], [...new Set(p)]), transportType: a }, n.addTrace(di.subscribing_authenticated_session_topic);
        try {
          await this.client.core.relayer.subscribe(d, { transportType: a });
        } catch (y) {
          throw n.setError(vr.subscribe_authenticated_session_topic_failure), y;
        }
        n.addTrace(di.subscribe_authenticated_session_topic_success), await this.client.session.set(d, g), n.addTrace(di.store_authenticated_session), await this.client.core.pairing.updateMetadata({ topic: o.pairingTopic, metadata: o.requester.metadata });
      }
      n.addTrace(di.publishing_authenticated_session_approve);
      try {
        await this.sendResult({ topic: h, id: r, result: { cacaos: s, responder: { publicKey: u, metadata: this.client.metadata } }, encodeOpts: l, throwOnFailedPublish: !0, appLink: this.getAppLinkIfEnabled(o.requester.metadata, a) });
      } catch (y) {
        throw n.setError(vr.authenticated_session_approve_publish_failure), y;
      }
      return await this.client.auth.requests.delete(r, { message: "fulfilled", code: 0 }), await this.client.core.pairing.activate({ topic: o.pairingTopic }), this.client.core.eventClient.deleteEvent({ eventId: n.eventId }), { session: g };
    }), F(this, "rejectSessionAuthenticate", async (i) => {
      this.isInitialized();
      const { id: r, reason: s } = i, n = this.getPendingAuthRequest(r);
      if (!n)
        throw new Error(`Could not find pending auth request with id ${r}`);
      n.transportType === he.relay && await this.confirmOnlineStateOrThrow();
      const o = n.requester.publicKey, a = await this.client.core.crypto.generateKeyPair(), c = Os(o), u = { type: Mt, receiverPublicKey: o, senderPublicKey: a };
      await this.sendError({ id: r, topic: c, error: s, encodeOpts: u, rpcOpts: Oe.wc_sessionAuthenticate.reject, appLink: this.getAppLinkIfEnabled(n.requester.metadata, n.transportType) }), await this.client.auth.requests.delete(r, { message: "rejected", code: 0 }), await this.deleteProposal(r);
    }), F(this, "formatAuthMessage", (i) => {
      this.isInitialized();
      const { request: r, iss: s } = i;
      return hf(r, s);
    }), F(this, "processRelayMessageCache", () => {
      setTimeout(async () => {
        if (this.relayMessageCache.length !== 0)
          for (; this.relayMessageCache.length > 0; )
            try {
              const i = this.relayMessageCache.shift();
              i && await this.onRelayMessage(i);
            } catch (i) {
              this.client.logger.error(i);
            }
      }, 50);
    }), F(this, "cleanupDuplicatePairings", async (i) => {
      if (i.pairingTopic)
        try {
          const r = this.client.core.pairing.pairings.get(i.pairingTopic), s = this.client.core.pairing.pairings.getAll().filter((n) => {
            var o, a;
            return ((o = n.peerMetadata) == null ? void 0 : o.url) && ((a = n.peerMetadata) == null ? void 0 : a.url) === i.peer.metadata.url && n.topic && n.topic !== r.topic;
          });
          if (s.length === 0)
            return;
          this.client.logger.info(`Cleaning up ${s.length} duplicate pairing(s)`), await Promise.all(s.map((n) => this.client.core.pairing.disconnect({ topic: n.topic }))), this.client.logger.info("Duplicate pairings clean up finished");
        } catch (r) {
          this.client.logger.error(r);
        }
    }), F(this, "deleteSession", async (i) => {
      var r;
      const { topic: s, expirerHasDeleted: n = !1, emitEvent: o = !0, id: a = 0 } = i, { self: c } = this.client.session.get(s);
      await this.client.core.relayer.unsubscribe(s), await this.client.session.delete(s, le("USER_DISCONNECTED")), this.addToRecentlyDeleted(s, "session"), this.client.core.crypto.keychain.has(c.publicKey) && await this.client.core.crypto.deleteKeyPair(c.publicKey), this.client.core.crypto.keychain.has(s) && await this.client.core.crypto.deleteSymKey(s), n || this.client.core.expirer.del(s), this.client.core.storage.removeItem(sh).catch((u) => this.client.logger.warn(u)), this.getPendingSessionRequests().forEach((u) => {
        u.topic === s && this.deletePendingSessionRequest(u.id, le("USER_DISCONNECTED"));
      }), s === ((r = this.sessionRequestQueue.queue[0]) == null ? void 0 : r.topic) && (this.sessionRequestQueue.state = _t.idle), o && this.client.events.emit("session_delete", { id: a, topic: s });
    }), F(this, "deleteProposal", async (i, r) => {
      if (r)
        try {
          const s = this.client.proposal.get(i);
          this.client.core.eventClient.getEvent({ topic: s.pairingTopic })?.setError(br.proposal_expired);
        } catch {
        }
      await Promise.all([this.client.proposal.delete(i, le("USER_DISCONNECTED")), r ? Promise.resolve() : this.client.core.expirer.del(i)]), this.addToRecentlyDeleted(i, "proposal");
    }), F(this, "deletePendingSessionRequest", async (i, r, s = !1) => {
      await Promise.all([this.client.pendingRequest.delete(i, r), s ? Promise.resolve() : this.client.core.expirer.del(i)]), this.addToRecentlyDeleted(i, "request"), this.sessionRequestQueue.queue = this.sessionRequestQueue.queue.filter((n) => n.id !== i), s && (this.sessionRequestQueue.state = _t.idle, this.client.events.emit("session_request_expire", { id: i }));
    }), F(this, "deletePendingAuthRequest", async (i, r, s = !1) => {
      await Promise.all([this.client.auth.requests.delete(i, r), s ? Promise.resolve() : this.client.core.expirer.del(i)]);
    }), F(this, "setExpiry", async (i, r) => {
      this.client.session.keys.includes(i) && (this.client.core.expirer.set(i, r), await this.client.session.update(i, { expiry: r }));
    }), F(this, "setProposal", async (i, r) => {
      this.client.core.expirer.set(i, me(Oe.wc_sessionPropose.req.ttl)), await this.client.proposal.set(i, r);
    }), F(this, "setAuthRequest", async (i, r) => {
      const { request: s, pairingTopic: n, transportType: o = he.relay } = r;
      this.client.core.expirer.set(i, s.expiryTimestamp), await this.client.auth.requests.set(i, { authPayload: s.authPayload, requester: s.requester, expiryTimestamp: s.expiryTimestamp, id: i, pairingTopic: n, verifyContext: s.verifyContext, transportType: o });
    }), F(this, "setPendingSessionRequest", async (i) => {
      const { id: r, topic: s, params: n, verifyContext: o } = i, a = n.request.expiryTimestamp || me(Oe.wc_sessionRequest.req.ttl);
      this.client.core.expirer.set(r, a), await this.client.pendingRequest.set(r, { id: r, topic: s, params: n, verifyContext: o });
    }), F(this, "sendRequest", async (i) => {
      const { topic: r, method: s, params: n, expiry: o, relayRpcId: a, clientRpcId: c, throwOnFailedPublish: u, appLink: h, tvf: l, publishOpts: f = {} } = i, p = Lt(s, n, c);
      let d;
      const g = !!h;
      try {
        const v = g ? si : Ye;
        d = await this.client.core.crypto.encode(r, p, { encoding: v });
      } catch (v) {
        throw await this.cleanup(), this.client.logger.error(`sendRequest() -> core.crypto.encode() for topic ${r} failed`), v;
      }
      let y;
      if (fS.includes(s)) {
        const v = at(JSON.stringify(p)), m = at(d);
        y = await this.client.core.verify.register({ id: m, decryptedId: v });
      }
      const E = ne(ne({}, Oe[s].req), f);
      if (E.attestation = y, o && (E.ttl = o), a && (E.id = a), this.client.core.history.set(r, p), g) {
        const v = Es(h, r, d);
        await global.Linking.openURL(v, this.client.name);
      } else
        E.tvf = Le(ne({}, l), { correlationId: p.id }), u ? (E.internal = Le(ne({}, E.internal), { throwOnFailedPublish: !0 }), await this.client.core.relayer.publish(r, d, E)) : this.client.core.relayer.publish(r, d, E).catch((v) => this.client.logger.error(v));
      return p.id;
    }), F(this, "sendProposeSession", async (i) => {
      const { proposal: r, publishOpts: s } = i, n = Lt("wc_sessionPropose", r, r.id);
      this.client.core.history.set(r.pairingTopic, n);
      const o = await this.client.core.crypto.encode(r.pairingTopic, n, { encoding: Ye }), a = at(JSON.stringify(n)), c = at(o), u = await this.client.core.verify.register({ id: c, decryptedId: a });
      await this.client.core.relayer.publishCustom({ payload: { pairingTopic: r.pairingTopic, sessionProposal: o }, opts: Le(ne({}, s), { publishMethod: "wc_proposeSession", attestation: u }) });
    }), F(this, "sendApproveSession", async (i) => {
      const { sessionTopic: r, pairingProposalResponse: s, proposal: n, sessionSettleRequest: o, publishOpts: a } = i, c = Hr(n.id, s), u = await this.client.core.crypto.encode(n.pairingTopic, c, { encoding: Ye }), h = Lt("wc_sessionSettle", o, a?.id), l = await this.client.core.crypto.encode(r, h, { encoding: Ye });
      this.client.core.history.set(r, h), await this.client.core.relayer.publishCustom({ payload: { sessionTopic: r, pairingTopic: n.pairingTopic, sessionProposalResponse: u, sessionSettlementRequest: l }, opts: Le(ne({}, a), { publishMethod: "wc_approveSession" }) });
    }), F(this, "sendResult", async (i) => {
      const { id: r, topic: s, result: n, throwOnFailedPublish: o, encodeOpts: a, appLink: c } = i, u = Hr(r, n);
      let h;
      const l = c && typeof (global == null ? void 0 : global.Linking) < "u";
      try {
        const d = l ? si : Ye;
        h = await this.client.core.crypto.encode(s, u, Le(ne({}, a || {}), { encoding: d }));
      } catch (d) {
        throw await this.cleanup(), this.client.logger.error(`sendResult() -> core.crypto.encode() for topic ${s} failed`), d;
      }
      let f, p;
      try {
        f = await this.client.core.history.get(s, r);
        const d = f.request;
        try {
          p = this.getTVFParams(r, d.params, n);
        } catch (g) {
          this.client.logger.warn(`sendResult() -> getTVFParams() failed: ${g?.message}`);
        }
      } catch (d) {
        throw this.client.logger.error(`sendResult() -> history.get(${s}, ${r}) failed`), d;
      }
      if (l) {
        const d = Es(c, s, h);
        await global.Linking.openURL(d, this.client.name);
      } else {
        const d = f.request.method, g = Oe[d].res;
        g.tvf = Le(ne({}, p), { correlationId: r }), o ? (g.internal = Le(ne({}, g.internal), { throwOnFailedPublish: !0 }), await this.client.core.relayer.publish(s, h, g)) : this.client.core.relayer.publish(s, h, g).catch((y) => this.client.logger.error(y));
      }
      await this.client.core.history.resolve(u);
    }), F(this, "sendError", async (i) => {
      const { id: r, topic: s, error: n, encodeOpts: o, rpcOpts: a, appLink: c } = i, u = hn(r, n);
      let h;
      const l = c && typeof (global == null ? void 0 : global.Linking) < "u";
      try {
        const p = l ? si : Ye;
        h = await this.client.core.crypto.encode(s, u, Le(ne({}, o || {}), { encoding: p }));
      } catch (p) {
        throw await this.cleanup(), this.client.logger.error(`sendError() -> core.crypto.encode() for topic ${s} failed`), p;
      }
      let f;
      try {
        f = await this.client.core.history.get(s, r);
      } catch (p) {
        throw this.client.logger.error(`sendError() -> history.get(${s}, ${r}) failed`), p;
      }
      if (l) {
        const p = Es(c, s, h);
        await global.Linking.openURL(p, this.client.name);
      } else {
        const p = f.request.method, d = a || Oe[p].res;
        this.client.core.relayer.publish(s, h, d);
      }
      await this.client.core.history.resolve(u);
    }), F(this, "cleanup", async () => {
      const i = [], r = [];
      this.client.session.getAll().forEach((s) => {
        let n = !1;
        ei(s.expiry) && (n = !0), this.client.core.crypto.keychain.has(s.topic) || (n = !0), n && i.push(s.topic);
      }), this.client.proposal.getAll().forEach((s) => {
        ei(s.expiryTimestamp) && r.push(s.id);
      }), await Promise.all([...i.map((s) => this.deleteSession({ topic: s })), ...r.map((s) => this.deleteProposal(s))]);
    }), F(this, "onProviderMessageEvent", async (i) => {
      !this.initialized || this.relayMessageCache.length > 0 ? this.relayMessageCache.push(i) : await this.onRelayMessage(i);
    }), F(this, "onRelayEventRequest", async (i) => {
      this.requestQueue.queue.push(i), await this.processRequestsQueue();
    }), F(this, "processRequestsQueue", async () => {
      if (this.requestQueue.state === _t.active) {
        this.client.logger.info("Request queue already active, skipping...");
        return;
      }
      for (this.client.logger.info(`Request queue starting with ${this.requestQueue.queue.length} requests`); this.requestQueue.queue.length > 0; ) {
        this.requestQueue.state = _t.active;
        const i = this.requestQueue.queue.shift();
        if (i)
          try {
            await this.processRequest(i);
          } catch (r) {
            this.client.logger.warn(r);
          }
      }
      this.requestQueue.state = _t.idle;
    }), F(this, "processRequest", async (i) => {
      const { topic: r, payload: s, attestation: n, transportType: o, encryptedId: a } = i, c = s.method;
      if (!this.shouldIgnorePairingRequest({ topic: r, requestMethod: c }))
        switch (c) {
          case "wc_sessionPropose":
            return await this.onSessionProposeRequest({ topic: r, payload: s, attestation: n, encryptedId: a });
          case "wc_sessionSettle":
            return await this.onSessionSettleRequest(r, s);
          case "wc_sessionUpdate":
            return await this.onSessionUpdateRequest(r, s);
          case "wc_sessionExtend":
            return await this.onSessionExtendRequest(r, s);
          case "wc_sessionPing":
            return await this.onSessionPingRequest(r, s);
          case "wc_sessionDelete":
            return await this.onSessionDeleteRequest(r, s);
          case "wc_sessionRequest":
            return await this.onSessionRequest({ topic: r, payload: s, attestation: n, encryptedId: a, transportType: o });
          case "wc_sessionEvent":
            return await this.onSessionEventRequest(r, s);
          case "wc_sessionAuthenticate":
            return await this.onSessionAuthenticateRequest({ topic: r, payload: s, attestation: n, encryptedId: a, transportType: o });
          default:
            return this.client.logger.info(`Unsupported request method ${c}`);
        }
    }), F(this, "onRelayEventResponse", async (i) => {
      const { topic: r, payload: s, transportType: n } = i, o = (await this.client.core.history.get(r, s.id)).request.method;
      switch (o) {
        case "wc_sessionPropose":
          return this.onSessionProposeResponse(r, s, n);
        case "wc_sessionSettle":
          return this.onSessionSettleResponse(r, s);
        case "wc_sessionUpdate":
          return this.onSessionUpdateResponse(r, s);
        case "wc_sessionExtend":
          return this.onSessionExtendResponse(r, s);
        case "wc_sessionPing":
          return this.onSessionPingResponse(r, s);
        case "wc_sessionRequest":
          return this.onSessionRequestResponse(r, s);
        case "wc_sessionAuthenticate":
          return this.onSessionAuthenticateResponse(r, s);
        default:
          return this.client.logger.info(`Unsupported response method ${o}`);
      }
    }), F(this, "onRelayEventUnknownPayload", (i) => {
      const { topic: r } = i, { message: s } = M("MISSING_OR_INVALID", `Decoded payload on topic ${r} is not identifiable as a JSON-RPC request or a response.`);
      throw new Error(s);
    }), F(this, "shouldIgnorePairingRequest", (i) => {
      const { topic: r, requestMethod: s } = i, n = this.expectedPairingMethodMap.get(r);
      return !n || n.includes(s) ? !1 : !!(n.includes("wc_sessionAuthenticate") && this.client.events.listenerCount("session_authenticate") > 0);
    }), F(this, "onSessionProposeRequest", async (i) => {
      const { topic: r, payload: s, attestation: n, encryptedId: o } = i, { params: a, id: c } = s;
      try {
        const u = this.client.core.eventClient.getEvent({ topic: r });
        this.client.events.listenerCount("session_proposal") === 0 && (console.warn("No listener for session_proposal event"), u?.setError(Nt.proposal_listener_not_found)), this.isValidConnect(ne({}, s.params));
        const h = a.expiryTimestamp || me(Oe.wc_sessionPropose.req.ttl), l = ne({ id: c, pairingTopic: r, expiryTimestamp: h, attestation: n, encryptedId: o }, a);
        await this.setProposal(c, l);
        const f = await this.getVerifyContext({ attestationId: n, hash: at(JSON.stringify(s)), encryptedId: o, metadata: l.proposer.metadata });
        u?.addTrace(xt.emit_session_proposal), this.client.events.emit("session_proposal", { id: c, params: l, verifyContext: f });
      } catch (u) {
        await this.sendError({ id: c, topic: r, error: u, rpcOpts: Oe.wc_sessionPropose.autoReject }), this.client.logger.error(u);
      }
    }), F(this, "onSessionProposeResponse", async (i, r, s) => {
      const { id: n } = r;
      if (St(r)) {
        const { result: o } = r;
        this.client.logger.trace({ type: "method", method: "onSessionProposeResponse", result: o });
        const a = this.client.proposal.get(n);
        this.client.logger.trace({ type: "method", method: "onSessionProposeResponse", proposal: a });
        const c = a.proposer.publicKey;
        this.client.logger.trace({ type: "method", method: "onSessionProposeResponse", selfPublicKey: c });
        const u = o.responderPublicKey;
        this.client.logger.trace({ type: "method", method: "onSessionProposeResponse", peerPublicKey: u });
        const h = await this.client.core.crypto.generateSharedKey(c, u);
        this.pendingSessions.set(n, { sessionTopic: h, pairingTopic: i, proposalId: n, publicKey: c });
        const l = await this.client.core.relayer.subscribe(h, { transportType: s });
        this.client.logger.trace({ type: "method", method: "onSessionProposeResponse", subscriptionId: l }), await this.client.core.pairing.activate({ topic: i });
      } else if (ct(r)) {
        await this.deleteProposal(n);
        const o = se("session_connect", n);
        if (this.events.listenerCount(o) === 0)
          throw new Error(`emitting ${o} without any listeners, 954`);
        this.events.emit(o, { error: r.error });
      }
    }), F(this, "onSessionSettleRequest", async (i, r) => {
      const { id: s, params: n } = r;
      try {
        this.isValidSessionSettleRequest(n);
        const { relay: o, controller: a, expiry: c, namespaces: u, sessionProperties: h, scopedProperties: l, sessionConfig: f } = r.params, p = [...this.pendingSessions.values()].find((y) => y.sessionTopic === i);
        if (!p)
          return this.client.logger.error(`Pending session not found for topic ${i}`);
        const d = this.client.proposal.get(p.proposalId), g = Le(ne(ne(ne({ topic: i, relay: o, expiry: c, namespaces: u, acknowledged: !0, pairingTopic: p.pairingTopic, requiredNamespaces: d.requiredNamespaces, optionalNamespaces: d.optionalNamespaces, controller: a.publicKey, self: { publicKey: p.publicKey, metadata: this.client.metadata }, peer: { publicKey: a.publicKey, metadata: a.metadata } }, h && { sessionProperties: h }), l && { scopedProperties: l }), f && { sessionConfig: f }), { transportType: he.relay });
        await this.client.session.set(g.topic, g), await this.setExpiry(g.topic, g.expiry), await this.client.core.pairing.updateMetadata({ topic: p.pairingTopic, metadata: g.peer.metadata }), this.client.events.emit("session_connect", { session: g }), this.events.emit(se("session_connect", p.proposalId), { session: g }), this.pendingSessions.delete(p.proposalId), this.deleteProposal(p.proposalId, !1), this.cleanupDuplicatePairings(g), await this.sendResult({ id: r.id, topic: i, result: !0 });
      } catch (o) {
        await this.sendError({ id: s, topic: i, error: o }), this.client.logger.error(o);
      }
    }), F(this, "onSessionSettleResponse", async (i, r) => {
      const { id: s } = r;
      St(r) ? (await this.client.session.update(i, { acknowledged: !0 }), this.events.emit(se("session_approve", s), {})) : ct(r) && (await this.client.session.delete(i, le("USER_DISCONNECTED")), this.events.emit(se("session_approve", s), { error: r.error }));
    }), F(this, "onSessionUpdateRequest", async (i, r) => {
      const { params: s, id: n } = r;
      try {
        const o = `${i}_session_update`, a = wr.get(o);
        if (a && this.isRequestOutOfSync(a, n)) {
          this.client.logger.warn(`Discarding out of sync request - ${n}`), this.sendError({ id: n, topic: i, error: le("INVALID_UPDATE_REQUEST") });
          return;
        }
        this.isValidUpdate(ne({ topic: i }, s));
        try {
          wr.set(o, n), await this.client.session.update(i, { namespaces: s.namespaces }), await this.sendResult({ id: n, topic: i, result: !0 });
        } catch (c) {
          throw wr.delete(o), c;
        }
        this.client.events.emit("session_update", { id: n, topic: i, params: s });
      } catch (o) {
        await this.sendError({ id: n, topic: i, error: o }), this.client.logger.error(o);
      }
    }), F(this, "isRequestOutOfSync", (i, r) => r.toString().slice(0, -3) < i.toString().slice(0, -3)), F(this, "onSessionUpdateResponse", (i, r) => {
      const { id: s } = r, n = se("session_update", s);
      if (this.events.listenerCount(n) === 0)
        throw new Error(`emitting ${n} without any listeners`);
      St(r) ? this.events.emit(se("session_update", s), {}) : ct(r) && this.events.emit(se("session_update", s), { error: r.error });
    }), F(this, "onSessionExtendRequest", async (i, r) => {
      const { id: s } = r;
      try {
        this.isValidExtend({ topic: i }), await this.setExpiry(i, me(Vi)), await this.sendResult({ id: s, topic: i, result: !0 }), this.client.events.emit("session_extend", { id: s, topic: i });
      } catch (n) {
        await this.sendError({ id: s, topic: i, error: n }), this.client.logger.error(n);
      }
    }), F(this, "onSessionExtendResponse", (i, r) => {
      const { id: s } = r, n = se("session_extend", s);
      if (this.events.listenerCount(n) === 0)
        throw new Error(`emitting ${n} without any listeners`);
      St(r) ? this.events.emit(se("session_extend", s), {}) : ct(r) && this.events.emit(se("session_extend", s), { error: r.error });
    }), F(this, "onSessionPingRequest", async (i, r) => {
      const { id: s } = r;
      try {
        this.isValidPing({ topic: i }), await this.sendResult({ id: s, topic: i, result: !0, throwOnFailedPublish: !0 }), this.client.events.emit("session_ping", { id: s, topic: i });
      } catch (n) {
        await this.sendError({ id: s, topic: i, error: n }), this.client.logger.error(n);
      }
    }), F(this, "onSessionPingResponse", (i, r) => {
      const { id: s } = r, n = se("session_ping", s);
      setTimeout(() => {
        if (this.events.listenerCount(n) === 0)
          throw new Error(`emitting ${n} without any listeners 2176`);
        St(r) ? this.events.emit(se("session_ping", s), {}) : ct(r) && this.events.emit(se("session_ping", s), { error: r.error });
      }, 500);
    }), F(this, "onSessionDeleteRequest", async (i, r) => {
      const { id: s } = r;
      try {
        this.isValidDisconnect({ topic: i, reason: r.params }), await Promise.all([new Promise((n) => {
          this.client.core.relayer.once(de.publish, async () => {
            n(await this.deleteSession({ topic: i, id: s }));
          });
        }), this.sendResult({ id: s, topic: i, result: !0 }), this.cleanupPendingSentRequestsForTopic({ topic: i, error: le("USER_DISCONNECTED") })]).catch((n) => this.client.logger.error(n));
      } catch (n) {
        this.client.logger.error(n);
      }
    }), F(this, "onSessionRequest", async (i) => {
      var r, s, n;
      const { topic: o, payload: a, attestation: c, encryptedId: u, transportType: h } = i, { id: l, params: f } = a;
      try {
        await this.isValidRequest(ne({ topic: o }, f));
        const p = this.client.session.get(o), d = await this.getVerifyContext({ attestationId: c, hash: at(JSON.stringify(Lt("wc_sessionRequest", f, l))), encryptedId: u, metadata: p.peer.metadata, transportType: h }), g = { id: l, topic: o, params: f, verifyContext: d };
        await this.setPendingSessionRequest(g), h === he.link_mode && (r = p.peer.metadata.redirect) != null && r.universal && this.client.core.addLinkModeSupportedApp((s = p.peer.metadata.redirect) == null ? void 0 : s.universal), (n = this.client.signConfig) != null && n.disableRequestQueue ? this.emitSessionRequest(g) : (this.addSessionRequestToSessionRequestQueue(g), this.processSessionRequestQueue());
      } catch (p) {
        await this.sendError({ id: l, topic: o, error: p }), this.client.logger.error(p);
      }
    }), F(this, "onSessionRequestResponse", (i, r) => {
      const { id: s } = r, n = se("session_request", s);
      if (this.events.listenerCount(n) === 0)
        throw new Error(`emitting ${n} without any listeners`);
      St(r) ? this.events.emit(se("session_request", s), { result: r.result }) : ct(r) && this.events.emit(se("session_request", s), { error: r.error });
    }), F(this, "onSessionEventRequest", async (i, r) => {
      const { id: s, params: n } = r;
      try {
        const o = `${i}_session_event_${n.event.name}`, a = wr.get(o);
        if (a && this.isRequestOutOfSync(a, s)) {
          this.client.logger.info(`Discarding out of sync request - ${s}`);
          return;
        }
        this.isValidEmit(ne({ topic: i }, n)), this.client.events.emit("session_event", { id: s, topic: i, params: n }), wr.set(o, s);
      } catch (o) {
        await this.sendError({ id: s, topic: i, error: o }), this.client.logger.error(o);
      }
    }), F(this, "onSessionAuthenticateResponse", (i, r) => {
      const { id: s } = r;
      this.client.logger.trace({ type: "method", method: "onSessionAuthenticateResponse", topic: i, payload: r }), St(r) ? this.events.emit(se("session_request", s), { result: r.result }) : ct(r) && this.events.emit(se("session_request", s), { error: r.error });
    }), F(this, "onSessionAuthenticateRequest", async (i) => {
      var r;
      const { topic: s, payload: n, attestation: o, encryptedId: a, transportType: c } = i;
      try {
        const { requester: u, authPayload: h, expiryTimestamp: l } = n.params, f = await this.getVerifyContext({ attestationId: o, hash: at(JSON.stringify(n)), encryptedId: a, metadata: u.metadata, transportType: c }), p = { requester: u, pairingTopic: s, id: n.id, authPayload: h, verifyContext: f, expiryTimestamp: l };
        await this.setAuthRequest(n.id, { request: p, pairingTopic: s, transportType: c }), c === he.link_mode && (r = u.metadata.redirect) != null && r.universal && this.client.core.addLinkModeSupportedApp(u.metadata.redirect.universal), this.client.events.emit("session_authenticate", { topic: s, params: n.params, id: n.id, verifyContext: f });
      } catch (u) {
        this.client.logger.error(u);
        const h = n.params.requester.publicKey, l = await this.client.core.crypto.generateKeyPair(), f = this.getAppLinkIfEnabled(n.params.requester.metadata, c), p = { type: Mt, receiverPublicKey: h, senderPublicKey: l };
        await this.sendError({ id: n.id, topic: s, error: u, encodeOpts: p, rpcOpts: Oe.wc_sessionAuthenticate.autoReject, appLink: f });
      }
    }), F(this, "addSessionRequestToSessionRequestQueue", (i) => {
      this.sessionRequestQueue.queue.push(i);
    }), F(this, "cleanupAfterResponse", (i) => {
      this.deletePendingSessionRequest(i.response.id, { message: "fulfilled", code: 0 }), setTimeout(() => {
        this.sessionRequestQueue.state = _t.idle, this.processSessionRequestQueue();
      }, L.toMiliseconds(this.requestQueueDelay));
    }), F(this, "cleanupPendingSentRequestsForTopic", ({ topic: i, error: r }) => {
      const s = this.client.core.history.pending;
      s.length > 0 && s.filter((n) => n.topic === i && n.request.method === "wc_sessionRequest").forEach((n) => {
        const o = n.request.id, a = se("session_request", o);
        if (this.events.listenerCount(a) === 0)
          throw new Error(`emitting ${a} without any listeners`);
        this.events.emit(se("session_request", n.request.id), { error: r });
      });
    }), F(this, "processSessionRequestQueue", () => {
      if (this.sessionRequestQueue.state === _t.active) {
        this.client.logger.info("session request queue is already active.");
        return;
      }
      const i = this.sessionRequestQueue.queue[0];
      if (!i) {
        this.client.logger.info("session request queue is empty.");
        return;
      }
      try {
        this.emitSessionRequest(i);
      } catch (r) {
        this.client.logger.error(r);
      }
    }), F(this, "emitSessionRequest", (i) => {
      if (this.emittedSessionRequests.has(i.id)) {
        this.client.logger.warn({ id: i.id }, `Skipping emitting \`session_request\` event for duplicate request. id: ${i.id}`);
        return;
      }
      this.sessionRequestQueue.state = _t.active, this.emittedSessionRequests.add(i.id), this.client.events.emit("session_request", i);
    }), F(this, "onPairingCreated", (i) => {
      if (i.methods && this.expectedPairingMethodMap.set(i.topic, i.methods), i.active)
        return;
      const r = this.client.proposal.getAll().find((s) => s.pairingTopic === i.topic);
      r && this.onSessionProposeRequest({ topic: i.topic, payload: Lt("wc_sessionPropose", Le(ne({}, r), { requiredNamespaces: r.requiredNamespaces, optionalNamespaces: r.optionalNamespaces, relays: r.relays, proposer: r.proposer, sessionProperties: r.sessionProperties, scopedProperties: r.scopedProperties }), r.id), attestation: r.attestation, encryptedId: r.encryptedId });
    }), F(this, "isValidConnect", async (i) => {
      if (!He(i)) {
        const { message: u } = M("MISSING_OR_INVALID", `connect() params: ${JSON.stringify(i)}`);
        throw new Error(u);
      }
      const { pairingTopic: r, requiredNamespaces: s, optionalNamespaces: n, sessionProperties: o, scopedProperties: a, relays: c } = i;
      if (ve(r) || await this.isValidPairingTopic(r), !T3(c, !0)) {
        const { message: u } = M("MISSING_OR_INVALID", `connect() relays: ${c}`);
        throw new Error(u);
      }
      if (!ve(s) && Vr(s) !== 0) {
        const u = "requiredNamespaces are deprecated and are automatically assigned to optionalNamespaces";
        ["fatal", "error", "silent"].includes(this.client.logger.level) ? console.warn(u) : this.client.logger.warn(u), this.validateNamespaces(s, "requiredNamespaces");
      }
      if (!ve(n) && Vr(n) !== 0 && this.validateNamespaces(n, "optionalNamespaces"), ve(o) || this.validateSessionProps(o, "sessionProperties"), !ve(a)) {
        this.validateSessionProps(a, "scopedProperties");
        const u = Object.keys(s || {}).concat(Object.keys(n || {}));
        if (!Object.keys(a).every((h) => u.includes(h.split(":")[0])))
          throw new Error(`Scoped properties must be a subset of required/optional namespaces, received: ${JSON.stringify(a)}, required/optional namespaces: ${JSON.stringify(u)}`);
      }
    }), F(this, "validateNamespaces", (i, r) => {
      const s = O3(i, "connect()", r);
      if (s)
        throw new Error(s.message);
    }), F(this, "isValidApprove", async (i) => {
      if (!He(i))
        throw new Error(M("MISSING_OR_INVALID", `approve() params: ${i}`).message);
      const { id: r, namespaces: s, relayProtocol: n, sessionProperties: o, scopedProperties: a } = i;
      this.checkRecentlyDeleted(r), await this.isValidProposalId(r);
      const c = this.client.proposal.get(r), u = Vn(s, "approve()");
      if (u)
        throw new Error(u.message);
      const h = Su(c.requiredNamespaces, s, "approve()");
      if (h)
        throw new Error(h.message);
      if (!ye(n, !0)) {
        const { message: l } = M("MISSING_OR_INVALID", `approve() relayProtocol: ${n}`);
        throw new Error(l);
      }
      if (ve(o) || this.validateSessionProps(o, "sessionProperties"), !ve(a)) {
        this.validateSessionProps(a, "scopedProperties");
        const l = new Set(Object.keys(s));
        if (!Object.keys(a).every((f) => l.has(f.split(":")[0])))
          throw new Error(`Scoped properties must be a subset of approved namespaces, received: ${JSON.stringify(a)}, approved namespaces: ${Array.from(l).join(", ")}`);
      }
    }), F(this, "isValidReject", async (i) => {
      if (!He(i)) {
        const { message: n } = M("MISSING_OR_INVALID", `reject() params: ${i}`);
        throw new Error(n);
      }
      const { id: r, reason: s } = i;
      if (this.checkRecentlyDeleted(r), await this.isValidProposalId(r), !P3(s)) {
        const { message: n } = M("MISSING_OR_INVALID", `reject() reason: ${JSON.stringify(s)}`);
        throw new Error(n);
      }
    }), F(this, "isValidSessionSettleRequest", (i) => {
      if (!He(i)) {
        const { message: u } = M("MISSING_OR_INVALID", `onSessionSettleRequest() params: ${i}`);
        throw new Error(u);
      }
      const { relay: r, controller: s, namespaces: n, expiry: o } = i;
      if (!jf(r)) {
        const { message: u } = M("MISSING_OR_INVALID", "onSessionSettleRequest() relay protocol should be a string");
        throw new Error(u);
      }
      const a = x3(s, "onSessionSettleRequest()");
      if (a)
        throw new Error(a.message);
      const c = Vn(n, "onSessionSettleRequest()");
      if (c)
        throw new Error(c.message);
      if (ei(o)) {
        const { message: u } = M("EXPIRED", "onSessionSettleRequest()");
        throw new Error(u);
      }
    }), F(this, "isValidUpdate", async (i) => {
      if (!He(i)) {
        const { message: c } = M("MISSING_OR_INVALID", `update() params: ${i}`);
        throw new Error(c);
      }
      const { topic: r, namespaces: s } = i;
      this.checkRecentlyDeleted(r), await this.isValidSessionTopic(r);
      const n = this.client.session.get(r), o = Vn(s, "update()");
      if (o)
        throw new Error(o.message);
      const a = Su(n.requiredNamespaces, s, "update()");
      if (a)
        throw new Error(a.message);
    }), F(this, "isValidExtend", async (i) => {
      if (!He(i)) {
        const { message: s } = M("MISSING_OR_INVALID", `extend() params: ${i}`);
        throw new Error(s);
      }
      const { topic: r } = i;
      this.checkRecentlyDeleted(r), await this.isValidSessionTopic(r);
    }), F(this, "isValidRequest", async (i) => {
      if (!He(i)) {
        const { message: c } = M("MISSING_OR_INVALID", `request() params: ${i}`);
        throw new Error(c);
      }
      const { topic: r, request: s, chainId: n, expiry: o } = i;
      this.checkRecentlyDeleted(r), await this.isValidSessionTopic(r);
      const { namespaces: a } = this.client.session.get(r);
      if (!Iu(a, n)) {
        const { message: c } = M("MISSING_OR_INVALID", `request() chainId: ${n}`);
        throw new Error(c);
      }
      if (!R3(s)) {
        const { message: c } = M("MISSING_OR_INVALID", `request() ${JSON.stringify(s)}`);
        throw new Error(c);
      }
      if (!B3(a, n, s.method)) {
        const { message: c } = M("MISSING_OR_INVALID", `request() method: ${s.method}`);
        throw new Error(c);
      }
      if (o && !M3(o, Zn)) {
        const { message: c } = M("MISSING_OR_INVALID", `request() expiry: ${o}. Expiry must be a number (in seconds) between ${Zn.min} and ${Zn.max}`);
        throw new Error(c);
      }
    }), F(this, "isValidRespond", async (i) => {
      var r;
      if (!He(i)) {
        const { message: o } = M("MISSING_OR_INVALID", `respond() params: ${i}`);
        throw new Error(o);
      }
      const { topic: s, response: n } = i;
      try {
        await this.isValidSessionTopic(s);
      } catch (o) {
        throw (r = i?.response) != null && r.id && this.cleanupAfterResponse(i), o;
      }
      if (!F3(n)) {
        const { message: o } = M("MISSING_OR_INVALID", `respond() response: ${JSON.stringify(n)}`);
        throw new Error(o);
      }
    }), F(this, "isValidPing", async (i) => {
      if (!He(i)) {
        const { message: s } = M("MISSING_OR_INVALID", `ping() params: ${i}`);
        throw new Error(s);
      }
      const { topic: r } = i;
      await this.isValidSessionOrPairingTopic(r);
    }), F(this, "isValidEmit", async (i) => {
      if (!He(i)) {
        const { message: a } = M("MISSING_OR_INVALID", `emit() params: ${i}`);
        throw new Error(a);
      }
      const { topic: r, event: s, chainId: n } = i;
      await this.isValidSessionTopic(r);
      const { namespaces: o } = this.client.session.get(r);
      if (!Iu(o, n)) {
        const { message: a } = M("MISSING_OR_INVALID", `emit() chainId: ${n}`);
        throw new Error(a);
      }
      if (!U3(s)) {
        const { message: a } = M("MISSING_OR_INVALID", `emit() event: ${JSON.stringify(s)}`);
        throw new Error(a);
      }
      if (!N3(o, n, s.name)) {
        const { message: a } = M("MISSING_OR_INVALID", `emit() event: ${JSON.stringify(s)}`);
        throw new Error(a);
      }
    }), F(this, "isValidDisconnect", async (i) => {
      if (!He(i)) {
        const { message: s } = M("MISSING_OR_INVALID", `disconnect() params: ${i}`);
        throw new Error(s);
      }
      const { topic: r } = i;
      await this.isValidSessionOrPairingTopic(r);
    }), F(this, "isValidAuthenticate", (i) => {
      const { chains: r, uri: s, domain: n, nonce: o } = i;
      if (!Array.isArray(r) || r.length === 0)
        throw new Error("chains is required and must be a non-empty array");
      if (!ye(s, !1))
        throw new Error("uri is required parameter");
      if (!ye(n, !1))
        throw new Error("domain is required parameter");
      if (!ye(o, !1))
        throw new Error("nonce is required parameter");
      if ([...new Set(r.map((c) => As(c).namespace))].length > 1)
        throw new Error("Multi-namespace requests are not supported. Please request single namespace only.");
      const { namespace: a } = As(r[0]);
      if (a !== "eip155")
        throw new Error("Only eip155 namespace is supported for authenticated sessions. Please use .connect() for non-eip155 chains.");
    }), F(this, "getVerifyContext", async (i) => {
      const { attestationId: r, hash: s, encryptedId: n, metadata: o, transportType: a } = i, c = { verified: { verifyUrl: o.verifyUrl || Fr, validation: "UNKNOWN", origin: o.url || "" } };
      try {
        if (a === he.link_mode) {
          const h = this.getAppLinkIfEnabled(o, a);
          return c.verified.validation = h && new URL(h).origin === new URL(o.url).origin ? "VALID" : "INVALID", c;
        }
        const u = await this.client.core.verify.resolve({ attestationId: r, hash: s, encryptedId: n, verifyUrl: o.verifyUrl });
        u && (c.verified.origin = u.origin, c.verified.isScam = u.isScam, c.verified.validation = u.origin === new URL(o.url).origin ? "VALID" : "INVALID");
      } catch (u) {
        this.client.logger.warn(u);
      }
      return this.client.logger.debug(`Verify context: ${JSON.stringify(c)}`), c;
    }), F(this, "validateSessionProps", (i, r) => {
      Object.values(i).forEach((s, n) => {
        if (s == null) {
          const { message: o } = M("MISSING_OR_INVALID", `${r} must contain an existing value for each key. Received: ${s} for key ${Object.keys(i)[n]}`);
          throw new Error(o);
        }
      });
    }), F(this, "getPendingAuthRequest", (i) => {
      const r = this.client.auth.requests.get(i);
      return typeof r == "object" ? r : void 0;
    }), F(this, "addToRecentlyDeleted", (i, r) => {
      if (this.recentlyDeletedMap.set(i, r), this.recentlyDeletedMap.size >= this.recentlyDeletedLimit) {
        let s = 0;
        const n = this.recentlyDeletedLimit / 2;
        for (const o of this.recentlyDeletedMap.keys()) {
          if (s++ >= n)
            break;
          this.recentlyDeletedMap.delete(o);
        }
      }
    }), F(this, "checkRecentlyDeleted", (i) => {
      const r = this.recentlyDeletedMap.get(i);
      if (r) {
        const { message: s } = M("MISSING_OR_INVALID", `Record was recently deleted - ${r}: ${i}`);
        throw new Error(s);
      }
    }), F(this, "isLinkModeEnabled", (i, r) => {
      var s, n, o, a, c, u, h, l, f;
      return !i || r !== he.link_mode ? !1 : ((n = (s = this.client.metadata) == null ? void 0 : s.redirect) == null ? void 0 : n.linkMode) === !0 && ((a = (o = this.client.metadata) == null ? void 0 : o.redirect) == null ? void 0 : a.universal) !== void 0 && ((u = (c = this.client.metadata) == null ? void 0 : c.redirect) == null ? void 0 : u.universal) !== "" && ((h = i?.redirect) == null ? void 0 : h.universal) !== void 0 && ((l = i?.redirect) == null ? void 0 : l.universal) !== "" && ((f = i?.redirect) == null ? void 0 : f.linkMode) === !0 && this.client.core.linkModeSupportedApps.includes(i.redirect.universal) && typeof (global == null ? void 0 : global.Linking) < "u";
    }), F(this, "getAppLinkIfEnabled", (i, r) => {
      var s;
      return this.isLinkModeEnabled(i, r) ? (s = i?.redirect) == null ? void 0 : s.universal : void 0;
    }), F(this, "handleLinkModeMessage", ({ url: i }) => {
      if (!i || !i.includes("wc_ev") || !i.includes("topic"))
        return;
      const r = kc(i, "topic") || "", s = decodeURIComponent(kc(i, "wc_ev") || ""), n = this.client.session.keys.includes(r);
      n && this.client.session.update(r, { transportType: he.link_mode }), this.client.core.dispatchEnvelope({ topic: r, message: s, sessionExists: n });
    }), F(this, "registerLinkModeListeners", async () => {
      var i;
      if (ua() || ci() && (i = this.client.metadata.redirect) != null && i.linkMode) {
        const r = global == null ? void 0 : global.Linking;
        if (typeof r < "u") {
          r.addEventListener("url", this.handleLinkModeMessage, this.client.name);
          const s = await r.getInitialURL();
          s && setTimeout(() => {
            this.handleLinkModeMessage({ url: s });
          }, 50);
        }
      }
    }), F(this, "getTVFParams", (i, r, s) => {
      var n, o, a;
      if (!((n = r.request) != null && n.method))
        return {};
      const c = { correlationId: i, rpcMethods: [r.request.method], chainId: r.chainId };
      try {
        const u = this.extractTxHashesFromResult(r.request, s);
        c.txHashes = u, c.contractAddresses = this.isValidContractData(r.request.params) ? [(a = (o = r.request.params) == null ? void 0 : o[0]) == null ? void 0 : a.to] : [];
      } catch (u) {
        this.client.logger.warn("Error getting TVF params", u);
      }
      return c;
    }), F(this, "isValidContractData", (i) => {
      var r;
      if (!i)
        return !1;
      try {
        const s = i?.data || ((r = i?.[0]) == null ? void 0 : r.data);
        if (!s.startsWith("0x"))
          return !1;
        const n = s.slice(2);
        return /^[0-9a-fA-F]*$/.test(n) ? n.length % 2 === 0 : !1;
      } catch {
      }
      return !1;
    }), F(this, "extractTxHashesFromResult", (i, r) => {
      var s;
      try {
        if (!r)
          return [];
        const n = i.method, o = hS[n];
        if (n === "sui_signTransaction")
          return [a2(r.transactionBytes)];
        if (n === "near_signTransaction")
          return [Hc(r)];
        if (n === "near_signTransactions")
          return r.map((c) => Hc(c));
        if (n === "xrpl_signTransactionFor" || n === "xrpl_signTransaction")
          return [(s = r.tx_json) == null ? void 0 : s.hash];
        if (n === "polkadot_signTransaction")
          return [t_({ transaction: i.params.transactionPayload, signature: r.signature })];
        if (n === "algo_signTxn")
          return Qi(r) ? r.map((c) => Wc(c)) : [Wc(r)];
        if (n === "cosmos_signDirect")
          return [u2(r)];
        if (typeof r == "string")
          return [r];
        const a = r[o.key];
        if (Qi(a))
          return n === "solana_signAllTransactions" ? a.map((c) => o2(c)) : a;
        if (typeof a == "string")
          return [a];
      } catch (n) {
        this.client.logger.warn("Error extracting tx hashes from result", n);
      }
      return [];
    });
  }
  async processPendingMessageEvents() {
    try {
      const e = this.client.session.keys, i = this.client.core.relayer.messages.getWithoutAck(e);
      for (const [r, s] of Object.entries(i))
        for (const n of s)
          try {
            await this.onProviderMessageEvent({ topic: r, message: n, publishedAt: Date.now() });
          } catch {
            this.client.logger.warn(`Error processing pending message event for topic: ${r}, message: ${n}`);
          }
    } catch (e) {
      this.client.logger.warn("processPendingMessageEvents failed", e);
    }
  }
  isInitialized() {
    if (!this.initialized) {
      const { message: e } = M("NOT_INITIALIZED", this.name);
      throw new Error(e);
    }
  }
  async confirmOnlineStateOrThrow() {
    await this.client.core.relayer.confirmOnlineStateOrThrow();
  }
  registerRelayerEvents() {
    this.client.core.relayer.on(de.message, (e) => {
      this.onProviderMessageEvent(e);
    });
  }
  async onRelayMessage(e) {
    const { topic: i, message: r, attestation: s, transportType: n } = e, { publicKey: o } = this.client.auth.authKeys.keys.includes(Cs) ? this.client.auth.authKeys.get(Cs) : { responseTopic: void 0, publicKey: void 0 };
    try {
      const a = await this.client.core.crypto.decode(i, r, { receiverPublicKey: o, encoding: n === he.link_mode ? si : Ye });
      Ia(a) ? (this.client.core.history.set(i, a), await this.onRelayEventRequest({ topic: i, payload: a, attestation: s, transportType: n, encryptedId: at(r) })) : ln(a) ? (await this.client.core.history.resolve(a), await this.onRelayEventResponse({ topic: i, payload: a, transportType: n }), this.client.core.history.delete(i, a.id)) : await this.onRelayEventUnknownPayload({ topic: i, payload: a, transportType: n }), await this.client.core.relayer.messages.ack(i, r);
    } catch (a) {
      this.client.logger.error(a);
    }
  }
  registerExpirerEvents() {
    this.client.core.expirer.on(ot.expired, async (e) => {
      const { topic: i, id: r } = Gl(e.target);
      if (r && this.client.pendingRequest.keys.includes(r))
        return await this.deletePendingSessionRequest(r, M("EXPIRED"), !0);
      if (r && this.client.auth.requests.keys.includes(r))
        return await this.deletePendingAuthRequest(r, M("EXPIRED"), !0);
      i ? this.client.session.keys.includes(i) && (await this.deleteSession({ topic: i, expirerHasDeleted: !0 }), this.client.events.emit("session_expire", { topic: i })) : r && (await this.deleteProposal(r, !0), this.client.events.emit("proposal_expire", { id: r }));
    });
  }
  registerPairingEvents() {
    this.client.core.pairing.events.on(mi.create, (e) => this.onPairingCreated(e)), this.client.core.pairing.events.on(mi.delete, (e) => {
      this.addToRecentlyDeleted(e.topic, "pairing");
    });
  }
  isValidPairingTopic(e) {
    if (!ye(e, !1)) {
      const { message: i } = M("MISSING_OR_INVALID", `pairing topic should be a string: ${e}`);
      throw new Error(i);
    }
    if (!this.client.core.pairing.pairings.keys.includes(e)) {
      const { message: i } = M("NO_MATCHING_KEY", `pairing topic doesn't exist: ${e}`);
      throw new Error(i);
    }
    if (ei(this.client.core.pairing.pairings.get(e).expiry)) {
      const { message: i } = M("EXPIRED", `pairing topic: ${e}`);
      throw new Error(i);
    }
  }
  async isValidSessionTopic(e) {
    if (!ye(e, !1)) {
      const { message: i } = M("MISSING_OR_INVALID", `session topic should be a string: ${e}`);
      throw new Error(i);
    }
    if (this.checkRecentlyDeleted(e), !this.client.session.keys.includes(e)) {
      const { message: i } = M("NO_MATCHING_KEY", `session topic doesn't exist: ${e}`);
      throw new Error(i);
    }
    if (ei(this.client.session.get(e).expiry)) {
      await this.deleteSession({ topic: e });
      const { message: i } = M("EXPIRED", `session topic: ${e}`);
      throw new Error(i);
    }
    if (!this.client.core.crypto.keychain.has(e)) {
      const { message: i } = M("MISSING_OR_INVALID", `session topic does not exist in keychain: ${e}`);
      throw await this.deleteSession({ topic: e }), new Error(i);
    }
  }
  async isValidSessionOrPairingTopic(e) {
    if (this.checkRecentlyDeleted(e), this.client.session.keys.includes(e))
      await this.isValidSessionTopic(e);
    else if (this.client.core.pairing.pairings.keys.includes(e))
      this.isValidPairingTopic(e);
    else if (ye(e, !1)) {
      const { message: i } = M("NO_MATCHING_KEY", `session or pairing topic doesn't exist: ${e}`);
      throw new Error(i);
    } else {
      const { message: i } = M("MISSING_OR_INVALID", `session or pairing topic should be a string: ${e}`);
      throw new Error(i);
    }
  }
  async isValidProposalId(e) {
    if (!C3(e)) {
      const { message: i } = M("MISSING_OR_INVALID", `proposal id should be a number: ${e}`);
      throw new Error(i);
    }
    if (!this.client.proposal.keys.includes(e)) {
      const { message: i } = M("NO_MATCHING_KEY", `proposal id doesn't exist: ${e}`);
      throw new Error(i);
    }
    if (ei(this.client.proposal.get(e).expiryTimestamp)) {
      await this.deleteProposal(e);
      const { message: i } = M("EXPIRED", `proposal id: ${e}`);
      throw new Error(i);
    }
  }
}
class IS extends Ri {
  constructor(e, i) {
    super(e, i, aS, Da), this.core = e, this.logger = i;
  }
}
class SS extends Ri {
  constructor(e, i) {
    super(e, i, cS, Da), this.core = e, this.logger = i;
  }
}
class DS extends Ri {
  constructor(e, i) {
    super(e, i, lS, Da, (r) => r.id), this.core = e, this.logger = i;
  }
}
class AS extends Ri {
  constructor(e, i) {
    super(e, i, gS, dn, () => Cs), this.core = e, this.logger = i;
  }
}
class $S extends Ri {
  constructor(e, i) {
    super(e, i, yS, dn), this.core = e, this.logger = i;
  }
}
class OS extends Ri {
  constructor(e, i) {
    super(e, i, wS, dn, (r) => r.id), this.core = e, this.logger = i;
  }
}
var TS = Object.defineProperty, CS = (t, e, i) => e in t ? TS(t, e, { enumerable: !0, configurable: !0, writable: !0, value: i }) : t[e] = i, Qn = (t, e, i) => CS(t, typeof e != "symbol" ? e + "" : e, i);
class PS {
  constructor(e, i) {
    this.core = e, this.logger = i, Qn(this, "authKeys"), Qn(this, "pairingTopics"), Qn(this, "requests"), this.authKeys = new AS(this.core, this.logger), this.pairingTopics = new $S(this.core, this.logger), this.requests = new OS(this.core, this.logger);
  }
  async init() {
    await this.authKeys.init(), await this.pairingTopics.init(), await this.requests.init();
  }
}
var RS = Object.defineProperty, FS = (t, e, i) => e in t ? RS(t, e, { enumerable: !0, configurable: !0, writable: !0, value: i }) : t[e] = i, Q = (t, e, i) => FS(t, typeof e != "symbol" ? e + "" : e, i);
class pn extends qg {
  constructor(e) {
    super(e), Q(this, "protocol", ld), Q(this, "version", fd), Q(this, "name", Jn.name), Q(this, "metadata"), Q(this, "core"), Q(this, "logger"), Q(this, "events", new rt.EventEmitter()), Q(this, "engine"), Q(this, "session"), Q(this, "proposal"), Q(this, "pendingRequest"), Q(this, "auth"), Q(this, "signConfig"), Q(this, "on", (r, s) => this.events.on(r, s)), Q(this, "once", (r, s) => this.events.once(r, s)), Q(this, "off", (r, s) => this.events.off(r, s)), Q(this, "removeListener", (r, s) => this.events.removeListener(r, s)), Q(this, "removeAllListeners", (r) => this.events.removeAllListeners(r)), Q(this, "connect", async (r) => {
      try {
        return await this.engine.connect(r);
      } catch (s) {
        throw this.logger.error(s.message), s;
      }
    }), Q(this, "pair", async (r) => {
      try {
        return await this.engine.pair(r);
      } catch (s) {
        throw this.logger.error(s.message), s;
      }
    }), Q(this, "approve", async (r) => {
      try {
        return await this.engine.approve(r);
      } catch (s) {
        throw this.logger.error(s.message), s;
      }
    }), Q(this, "reject", async (r) => {
      try {
        return await this.engine.reject(r);
      } catch (s) {
        throw this.logger.error(s.message), s;
      }
    }), Q(this, "update", async (r) => {
      try {
        return await this.engine.update(r);
      } catch (s) {
        throw this.logger.error(s.message), s;
      }
    }), Q(this, "extend", async (r) => {
      try {
        return await this.engine.extend(r);
      } catch (s) {
        throw this.logger.error(s.message), s;
      }
    }), Q(this, "request", async (r) => {
      try {
        return await this.engine.request(r);
      } catch (s) {
        throw this.logger.error(s.message), s;
      }
    }), Q(this, "respond", async (r) => {
      try {
        return await this.engine.respond(r);
      } catch (s) {
        throw this.logger.error(s.message), s;
      }
    }), Q(this, "ping", async (r) => {
      try {
        return await this.engine.ping(r);
      } catch (s) {
        throw this.logger.error(s.message), s;
      }
    }), Q(this, "emit", async (r) => {
      try {
        return await this.engine.emit(r);
      } catch (s) {
        throw this.logger.error(s.message), s;
      }
    }), Q(this, "disconnect", async (r) => {
      try {
        return await this.engine.disconnect(r);
      } catch (s) {
        throw this.logger.error(s.message), s;
      }
    }), Q(this, "find", (r) => {
      try {
        return this.engine.find(r);
      } catch (s) {
        throw this.logger.error(s.message), s;
      }
    }), Q(this, "getPendingSessionRequests", () => {
      try {
        return this.engine.getPendingSessionRequests();
      } catch (r) {
        throw this.logger.error(r.message), r;
      }
    }), Q(this, "authenticate", async (r, s) => {
      try {
        return await this.engine.authenticate(r, s);
      } catch (n) {
        throw this.logger.error(n.message), n;
      }
    }), Q(this, "formatAuthMessage", (r) => {
      try {
        return this.engine.formatAuthMessage(r);
      } catch (s) {
        throw this.logger.error(s.message), s;
      }
    }), Q(this, "approveSessionAuthenticate", async (r) => {
      try {
        return await this.engine.approveSessionAuthenticate(r);
      } catch (s) {
        throw this.logger.error(s.message), s;
      }
    }), Q(this, "rejectSessionAuthenticate", async (r) => {
      try {
        return await this.engine.rejectSessionAuthenticate(r);
      } catch (s) {
        throw this.logger.error(s.message), s;
      }
    }), this.name = e?.name || Jn.name, this.metadata = Qb(e?.metadata), this.signConfig = e?.signConfig;
    const i = typeof e?.logger < "u" && typeof e?.logger != "string" ? e.logger : Zs(Vo({ level: e?.logger || Jn.logger }));
    this.core = e?.core || new oS(e), this.logger = je(i, this.name), this.session = new SS(this.core, this.logger), this.proposal = new IS(this.core, this.logger), this.pendingRequest = new DS(this.core, this.logger), this.engine = new xS(this), this.auth = new PS(this.core, this.logger);
  }
  static async init(e) {
    const i = new pn(e);
    return await i.initialize(), i;
  }
  get context() {
    return Qe(this.logger);
  }
  get pairing() {
    return this.core.pairing.pairings;
  }
  async initialize() {
    this.logger.trace("Initialized");
    try {
      await this.core.start(), await this.session.init(), await this.proposal.init(), await this.pendingRequest.init(), await this.auth.init(), await this.engine.init(), this.logger.info("SignClient Initialization Success");
    } catch (e) {
      throw this.logger.info("SignClient Initialization Failure"), this.logger.error(e.message), e;
    }
  }
}
const Xn = Sd(), US = {
  width: "245px",
  height: "245px",
  borderRadius: "40px",
  zIndex: "99999",
  backgroundColor: "white",
  border: "none",
  outline: "none"
}, BS = `
  <div id="argent-mobile-modal-container" style="position: relative; display: flex; justify-content: center; align-items: center">
    <iframe class="argent-iframe" allow="clipboard-write"></iframe>
  </div>
`;
class NS {
  constructor() {
    W(this, "bridgeUrl", "https://login.ready.co");
    W(this, "mobileUrl", "ready://");
    W(this, "type", "overlay");
    W(this, "wcUri");
    W(this, "overlay");
    W(this, "popupWindow");
    W(this, "closingTimeout");
    W(this, "standaloneConnectorModal");
  }
  showWalletConnectModal(e, i) {
    const r = encodeURIComponent(e), s = encodeURIComponent(window.location.href);
    this.showModal(
      {
        desktop: `${this.bridgeUrl}?wc=${r}&href=${s}&device=desktop&onlyQR=true`,
        ios: `${this.mobileUrl}app/wc?uri=${r}&href=${s}&device=mobile&onlyQR=true`,
        android: `${this.mobileUrl}app/wc?uri=${r}&href=${s}&device=mobile&onlyQR=true`
      },
      i
    );
  }
  getWalletConnectQR(e) {
    const i = encodeURIComponent(e), r = encodeURIComponent(window.location.href);
    this.getQR({
      desktop: `${this.bridgeUrl}?wc=${i}&href=${r}&device=desktop&onlyQR=true`,
      ios: `${this.mobileUrl}app/wc?uri=${i}&href=${r}&device=mobile&onlyQR=true`,
      android: `${this.mobileUrl}app/wc?uri=${i}&href=${r}&device=mobile&onlyQR=true`
    });
  }
  openMobileApp(e) {
    const i = document.createElement("button");
    i.style.display = "none", i.addEventListener("click", () => {
      window.location.href = e[Xn];
    }), i.click();
  }
  getQR(e) {
    if (["android", "ios"].includes(Xn)) {
      this.openMobileApp(e);
      return;
    }
    const i = document.createElement("div"), r = document.querySelector("#starknetkit-modal-container");
    if (r?.shadowRoot) {
      const s = r.shadowRoot.querySelector(".qr-code-slot");
      if (s) {
        s.innerHTML = BS, document.body.appendChild(i), this.overlay = i;
        const n = s.querySelector("iframe");
        n.setAttribute("src", e.desktop);
        for (const [o, a] of Object.entries(US))
          n.style[o] = a;
      } else
        throw new Error("Cannot find QR code slot");
    } else
      throw new Error("Cannot find modal");
  }
  showApprovalModal(e) {
    const i = encodeURIComponent(window.location.href), r = {
      desktop: `${this.bridgeUrl}?action=sign&device=desktop&href=${i}`,
      ios: `${this.mobileUrl}app/wc/request?href=${i}&device=mobile`,
      android: `${this.mobileUrl}app/wc/request?href=${i}&device=mobile`
    };
    if (!Od()) {
      if (this.getModal(void 0, hi.approval), ["android", "ios"].includes(Xn)) {
        this.openMobileApp(r);
        return;
      }
      return;
    }
    this.showModal(r, void 0);
  }
  closeModal({
    success: e,
    isRequest: i
  } = {
    success: !1,
    isRequest: !1
  }) {
    const r = this.standaloneConnectorModal;
    e ? (r?.$set({ layout: hi.success }), setTimeout(() => r?.$destroy(), 500)) : i ? (r?.$set({ layout: hi.requestFailure }), setTimeout(() => r?.$destroy(), 500)) : r?.$set({ layout: hi.loginFailure });
  }
  getModal(e, i = hi.qrCode) {
    this.standaloneConnectorModal = new Dd({
      target: Ad(),
      props: {
        layout: i,
        dappName: e?.dappName,
        showBackButton: !1,
        selectedWallet: e,
        callback: async (r) => {
          try {
            const s = r?.connector;
            this.standaloneConnectorModal?.$destroy(), await s?.connect();
          } catch {
            this.standaloneConnectorModal?.$set({ layout: hi.loginFailure });
          }
        }
      }
    });
  }
  showModal(e, i) {
    this.getModal(i, hi.qrCode), this.getQR(e);
  }
}
const wt = new NS(), Gs = gi.NetworkName, kS = async ({
  projectId: t,
  chainId: e,
  name: i,
  description: r,
  rpcUrl: s,
  bridgeUrl: n = LS(e),
  mobileUrl: o = MS(e),
  modalType: a = "overlay",
  url: c,
  icons: u,
  walletConnect: h,
  onlyQRCode: l,
  modalWallet: f
}, p) => {
  if (!n)
    throw new Error("bridgeUrl is required");
  if (!o)
    throw new Error("mobileUrl is required");
  wt.bridgeUrl = n, wt.mobileUrl = o, wt.type = a;
  const d = {
    projectId: t,
    metadata: {
      name: i ?? "Unknown dapp",
      description: r ?? "Unknown dapp description",
      url: c ?? "#",
      icons: u ?? [],
      ...h?.metadata
    }
  }, g = await pn.init(d), y = new uh({ nodeUrl: s }), E = new p({ client: g, chainId: e, rpcUrl: s, provider: y });
  g.on("session_event", (v) => {
  }), g.on("session_update", ({ topic: v, params: m }) => {
    const { namespaces: D } = m, I = g.session.get(v);
    E.updateSession({ ...I, namespaces: D });
  }), g.on("session_delete", () => {
  });
  try {
    const v = g.session.getAll().find(E.isValidSession);
    if (v)
      return E.updateSession(v), E;
    const m = { requiredNamespaces: E.getRequiredNamespaces() };
    Td(), await new Promise((R) => setTimeout(R, 200));
    const { uri: D, approval: I } = await g.connect(m);
    if (D) {
      l ? wt.getWalletConnectQR(D) : wt.showWalletConnectModal(D, {
        ...f,
        dappName: i || ""
      }), wt.wcUri = D;
      const R = await I();
      E.updateSession(R), wt.closeModal({ success: !0 });
    }
    return E;
  } catch {
    return console.error("@argent/login::error"), wt.closeModal(), null;
  }
}, LS = (t) => {
  if (!t)
    throw new Error(
      `Unknown or unsupported chainId (${t}), either specify a supported chain or set bridgeUrl.`
    );
  const e = parseInt(`${t}`);
  if (String(t).startsWith(Gs.SN_SEPOLIA) || e === 11155111)
    return "https://mobile-login.hydrogen.argent47.net";
  if (String(t).startsWith(Gs.SN_MAIN) || e === 1)
    return "https://login.argent.xyz";
}, MS = (t) => {
  if (!t)
    throw new Error(
      `Unknown or unsupported chainId (${t}), either specify a supported chain or set mobileUrl.`
    );
  const e = parseInt(`${t}`);
  if (String(t).startsWith(Gs.SN_SEPOLIA) || e === 11155111)
    return "argent-dev://";
  if (String(t).startsWith(Gs.SN_MAIN) || e === 1)
    return "argent://";
};
var qS = Object.defineProperty, jS = (t, e, i) => e in t ? qS(t, e, { enumerable: !0, configurable: !0, writable: !0, value: i }) : t[e] = i, pi = (t, e, i) => jS(t, typeof e != "symbol" ? e + "" : e, i);
function zS(t) {
  return typeof t < "u" && typeof t.context < "u";
}
const Dt = { init: "signer_init", uri: "signer_uri", created: "signer_created", updated: "signer_updated", deleted: "signer_deleted", event: "signer_event" };
class KS extends d_ {
  constructor(e) {
    super(), pi(this, "events", new rt.EventEmitter()), pi(this, "requiredNamespaces"), pi(this, "pending", !1), pi(this, "session"), pi(this, "opts"), pi(this, "client"), pi(this, "initializing", !1), this.requiredNamespaces = e?.requiredNamespaces || {}, this.opts = e?.client;
  }
  get connected() {
    return typeof this.session < "u";
  }
  get connecting() {
    return this.pending;
  }
  get chains() {
    return this.session ? Kl(this.session.namespaces) : Mb(this.requiredNamespaces);
  }
  get accounts() {
    return this.session ? zl(this.session.namespaces) : [];
  }
  on(e, i) {
    this.events.on(e, i);
  }
  once(e, i) {
    this.events.once(e, i);
  }
  off(e, i) {
    this.events.off(e, i);
  }
  removeListener(e, i) {
    this.events.removeListener(e, i);
  }
  async open() {
    if (this.pending)
      return new Promise((e, i) => {
        this.events.once("open", () => {
          if (this.events.once("open_error", (r) => {
            i(r);
          }), typeof this.client > "u")
            return i(new Error("Sign Client not initialized"));
          e();
        });
      });
    try {
      this.pending = !0;
      const e = await this.register(), i = e.find({ requiredNamespaces: this.requiredNamespaces });
      if (i.length)
        return this.onOpen(i[0]);
      const { uri: r, approval: s } = await e.connect({ requiredNamespaces: this.requiredNamespaces });
      this.events.emit(Dt.uri, { uri: r }), this.session = await s(), this.events.emit(Dt.created, this.session), this.onOpen();
    } catch (e) {
      throw this.events.emit("open_error", e), e;
    }
  }
  async close() {
    typeof this.session > "u" || (await (await this.register()).disconnect({ topic: this.session.topic, reason: le("USER_DISCONNECTED") }), this.onClose());
  }
  async send(e, i) {
    if (typeof this.client > "u" && (this.client = await this.register(), this.connected || await this.open()), typeof this.session > "u")
      throw new Error("Signer connection is missing session");
    this.client.request({ topic: this.session.topic, request: e, chainId: i?.chainId }).then((r) => this.events.emit("payload", Hr(e.id, r))).catch((r) => this.events.emit("payload", hn(e.id, r.message)));
  }
  async register(e = this.opts) {
    if (typeof this.client < "u")
      return this.client;
    if (this.initializing)
      return new Promise((i, r) => {
        this.events.once("register_error", (s) => {
          r(s);
        }), this.events.once(Dt.init, () => {
          if (typeof this.client > "u")
            return r(new Error("Sign Client not initialized"));
          i(this.client);
        });
      });
    if (zS(e))
      return this.client = e, this.registerEventListeners(), this.client;
    try {
      return this.initializing = !0, this.client = await pn.init(e), this.initializing = !1, this.registerEventListeners(), this.events.emit(Dt.init), this.client;
    } catch (i) {
      throw this.events.emit("register_error", i), i;
    }
  }
  onOpen(e) {
    this.pending = !1, e && (this.session = e), this.events.emit("open");
  }
  onClose() {
    this.pending = !1, this.client && (this.client = void 0), this.events.emit("close");
  }
  registerEventListeners() {
    typeof this.client < "u" && (this.client.on("session_event", (e) => {
      var i;
      this.session && ((i = this.session) == null ? void 0 : i.topic) !== e.topic || this.events.emit(Dt.event, e.params);
    }), this.client.on("session_update", (e) => {
      var i;
      typeof this.client < "u" && (this.session && ((i = this.session) == null ? void 0 : i.topic) !== e.topic || (this.session = this.client.session.get(e.topic), this.events.emit(Dt.updated, this.session)));
    }), this.client.on("session_delete", (e) => {
      var i;
      this.session && (this.session && ((i = this.session) == null ? void 0 : i.topic) !== e.topic || (this.onClose(), this.events.emit(Dt.deleted, this.session), this.session = void 0));
    }));
  }
}
class VS {
  constructor() {
    W(this, "accounts", []);
    W(this, "eventEmitter", new rt.EventEmitter());
    W(this, "updateSession", (e) => {
      if (!this.isValidSession(e))
        throw console.warn(
          "updateSession incompatible session",
          e,
          "for adapter",
          this.formatChainId(this.chainId)
        ), new Error("Invalid session");
      this.session = e;
      const i = Kl(e.namespaces, [this.namespace]);
      this.setChainIds(i);
      const r = zl(e.namespaces, [
        this.namespace
      ]);
      this.setAccounts(r);
    });
    W(this, "isValidSession", ({
      namespaces: e,
      requiredNamespaces: i
    }) => {
      const r = this.formatChainId(this.chainId);
      return i && Object.keys(i).length > 0 ? !!i[this.namespace]?.chains?.includes(r) : !!e?.[this.namespace]?.accounts.some(
        (s) => s.startsWith(r)
      );
    });
  }
  getRequiredNamespaces() {
    const e = [this.formatChainId(this.chainId)];
    return {
      [this.namespace]: { chains: e, methods: this.methods, events: this.events }
    };
  }
  isCompatibleChainId(e) {
    return typeof e == "string" ? e.startsWith(`${this.namespace}:`) : !1;
  }
  setChainIds(e) {
    const r = e.filter((s) => this.isCompatibleChainId(s)).map((s) => this.parseChainId(s)).filter((s) => s !== this.chainId);
    r.length && (this.chainId = r[0], this.eventEmitter.emit("chainChanged", this.chainId));
  }
  setChainId(e) {
    this.isCompatibleChainId(e) && (this.chainId = this.parseChainId(e), this.eventEmitter.emit("chainChanged", this.chainId));
  }
  parseAccountId(e) {
    const [i, r, s] = e.split(":");
    return { chainId: `${i}:${r}`, address: s };
  }
  getSignerConnection(e) {
    return new KS({
      requiredNamespaces: {
        [this.namespace]: {
          chains: this.rpc.chains,
          methods: this.rpc.methods,
          events: this.rpc.events
        }
      },
      client: e
    });
  }
  registerEventListeners() {
    this.rpcProvider.on("connect", () => {
      const { chains: e, accounts: i } = this.signerConnection;
      e?.length && this.setChainIds(e), i?.length && this.setAccounts(i);
    }), this.signerConnection.on(Dt.created, this.updateSession), this.signerConnection.on(Dt.updated, this.updateSession), this.signerConnection.on(Dt.event, (e) => {
      if (!this.rpc.chains.includes(e.chainId))
        return;
      const { event: i } = e;
      i.name === "accountsChanged" ? (this.accounts = i.data, this.eventEmitter.emit("accountsChanged", this.accounts)) : i.name === "chainChanged" ? this.setChainId(i.data) : this.eventEmitter.emit(i.name, i.data);
    }), this.rpcProvider.on("disconnect", () => {
      this.eventEmitter.emit("disconnect");
    });
  }
}
class ah extends $d {
  constructor(e, i, r, s) {
    super({ provider: e, address: i, signer: r }), this.wallet = s;
  }
  async execute(e, i, r = {}) {
    const s = Array.isArray(e) ? e : [e], n = i === void 0 || Array.isArray(i) ? r : i;
    return await this.wallet.wallet_requestAddInvokeTransaction({
      accountAddress: this.address,
      executionRequest: { calls: s, invocationDetails: n }
    });
  }
  async declare(e, i) {
    throw new Error("Not supported via Ready Login");
  }
  async deployAccount(e, i) {
    throw new Error("Not supported via Ready Login");
  }
}
class HS {
  constructor(e) {
    this.wallet = e;
  }
  async getPubKey() {
    throw new Error("Not supported via Ready Login");
  }
  async signMessage(e, i) {
    const { signature: r } = await this.wallet.wallet_signTypedData({
      accountAddress: i,
      typedData: e
    });
    return r;
  }
  async signTransaction(e, i, r) {
    throw new Error("Not supported via Ready Login");
  }
  async signDeployAccountTransaction(e) {
    throw new Error("Not supported via Ready Login");
  }
  async signDeclareTransaction(e) {
    throw new Error("Not supported via Ready Login");
  }
}
const WS = (t) => t.replace(/^SN_/, "SN"), GS = (t) => t.replace(/^SN/, "SN_");
class YS extends VS {
  // TODO: improve typing
  constructor({ client: i, chainId: r, rpcUrl: s, provider: n }) {
    super();
    W(this, "id", "argentMobile");
    W(this, "name", "Ready (formerly Argent)");
    W(this, "version", "0.1.0");
    W(this, "icon", "");
    W(this, "provider");
    W(this, "signer");
    W(this, "account");
    W(this, "selectedAddress", "");
    // NamespaceAdapter
    W(this, "namespace", "starknet");
    W(this, "methods", [
      "starknet_supportedSpecs",
      "starknet_signTypedData",
      "starknet_requestAddInvokeTransaction",
      "wallet_supportedSpecs",
      "wallet_signTypedData",
      "wallet_addInvokeTransaction"
    ]);
    W(this, "events", ["chainChanged", "accountsChanged"]);
    W(this, "remoteSigner");
    W(this, "signerConnection");
    W(this, "rpcProvider");
    W(this, "chainId");
    W(this, "client");
    W(this, "session");
    W(this, "rpc");
    W(this, "walletRpc");
    W(this, "handleRequest");
    // StarknetWindowObject
    W(this, "request", async (i) => {
      if (!this.session)
        throw new Error("No session");
      let r = i.type;
      (r === "wallet_addInvokeTransaction" || r === "wallet_supportedSpecs" || r === "wallet_signTypedData") && (r = r.replace("wallet_", "starknet_"));
      const s = this.handleRequest[r];
      if (s)
        return s(i.params);
      throw new Error(`Not implemented: .request() for ${i.type}`);
    });
    W(this, "on", (i, r) => {
      this.eventEmitter.on(i, r);
    });
    W(this, "off", (i, r) => {
      this.eventEmitter.off(i, r);
    });
    W(this, "handleRequestChainId", () => this.chainId === gi.NetworkName.SN_SEPOLIA ? gi.StarknetChainId.SN_SEPOLIA : gi.StarknetChainId.SN_MAIN);
    W(this, "handleRequestAccounts", () => this.accounts);
    W(this, "handleGetPermissions", async () => await this.isPreauthorized() ? ["accounts"] : []);
    W(this, "handleAddInvokeTransaction", async (i) => {
      const { calls: r } = i;
      return await this.requestWallet({
        method: "starknet_requestAddInvokeTransaction",
        params: {
          accountAddress: this.account.address,
          executionRequest: {
            // will be removed when argent mobile will support entry_point and contract_address
            calls: r?.map(({ contract_address: s, entry_point: n, ...o }) => ({
              ...o,
              contractAddress: s,
              entrypoint: n
            }))
          }
        }
      });
    });
    W(this, "handleSignTypedData", async (i) => {
      const r = {
        accountAddress: this.account.address,
        typedData: i
      }, s = await this.requestWallet({
        method: "starknet_signTypedData",
        params: r
      });
      return "signature" in s ? s.signature : s;
    });
    W(this, "handleSupportedSpecs", async () => await this.requestWallet({
      method: "starknet_supportedSpecs",
      params: {}
    }));
    this.chainId = String(r ?? gi.NetworkName.SN_MAIN), this.rpc = {
      chains: r ? [this.formatChainId(this.chainId)] : [],
      methods: this.methods,
      events: this.events
    }, this.signerConnection = this.getSignerConnection(i), this.rpcProvider = new Gf(this.signerConnection), this.client = i, this.registerEventListeners(), this.walletRpc = new Proxy({}, {
      get: (o, a) => (c) => this.requestWallet({ method: a, params: c })
    }), this.remoteSigner = new HS(this.walletRpc), this.provider = n || new uh({ nodeUrl: s }), this.account = new ah(
      this.provider,
      "",
      this.remoteSigner,
      this.walletRpc
    ), this.handleRequest = Object.freeze({
      wallet_requestChainId: this.handleRequestChainId,
      wallet_requestAccounts: this.handleRequestAccounts,
      wallet_getPermissions: this.handleGetPermissions,
      starknet_addInvokeTransaction: this.handleAddInvokeTransaction,
      starknet_signTypedData: this.handleSignTypedData,
      starknet_supportedSpecs: this.handleSupportedSpecs,
      wallet_addInvokeTransaction: this.handleAddInvokeTransaction,
      wallet_signTypedData: this.handleSignTypedData,
      wallet_supportedSpecs: this.handleSupportedSpecs
    });
  }
  getNetworkName(i) {
    if (i === "SN_SEPOLIA")
      return gi.NetworkName.SN_SEPOLIA;
    if (i === "SN_MAIN")
      return gi.NetworkName.SN_MAIN;
    throw new Error(`Unknown starknet.js network name for chainId ${i}`);
  }
  async enable() {
    return await this.rpcProvider.connect(), this.accounts;
  }
  // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  // @ts-ignore
  get isConnected() {
    return !0;
  }
  async isPreauthorized() {
    return !!this.client.session.getAll().find(this.isValidSession);
  }
  async requestWallet(i) {
    if (!this.session)
      throw new Error("No session");
    try {
      const { topic: r } = this.session, s = this.formatChainId(this.chainId);
      wt.showApprovalModal(i);
      const n = await this.client.request({ topic: r, chainId: s, request: i });
      return wt.closeModal({ success: !0 }), n;
    } catch (r) {
      throw wt.closeModal({ isRequest: !0 }), r instanceof Error || r && r.message !== void 0 ? new Error(r.message) : new Error("Unknown error on requestWallet");
    }
  }
  // NamespaceAdapter
  get isConnecting() {
    return this.signerConnection.connecting;
  }
  async disable() {
    await this.rpcProvider.disconnect();
  }
  get isWalletConnect() {
    return !0;
  }
  // NamespaceAdapter private methods
  registerEventListeners() {
    super.registerEventListeners(), this.eventEmitter.on("chainChanged", (i) => {
      throw new Error("Not implemented: chainChanged");
    });
  }
  formatChainId(i) {
    return `${this.namespace}:${WS(i)}`;
  }
  parseChainId(i) {
    return GS(i.split(":")[1]);
  }
  setAccounts(i) {
    this.accounts = i.filter(
      (n) => this.parseChainId(this.parseAccountId(n).chainId) === this.chainId
    ).map((n) => this.parseAccountId(n).address);
    const { address: r } = this.parseAccountId(i[0]), s = r.startsWith("0x") ? r : `0x${r}`;
    this.account = new ah(
      this.provider,
      s,
      this.remoteSigner,
      this.walletRpc
    ), this.eventEmitter.emit("accountsChanged", this.accounts), this.selectedAddress = s;
  }
}
const JS = async (t) => kS(t, YS), VD = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  getStarknetWindowObject: JS
}, Symbol.toStringTag, { value: "Module" }));
export {
  ww as H,
  Ic as a,
  Mr as b,
  CD as c,
  lw as d,
  hl as e,
  mw as f,
  TD as g,
  Bs as h,
  RD as i,
  FD as j,
  VD as k,
  PD as r,
  ll as t
};