import { e as Nt } from "./events-CZ4TZ_a9.js";
import { l as N, C as G, t as Dt, y as Lt, P as Z, M as Mt, D as $t, F as Rt, G as kt, w as Ne } from "./en_US-FEVFXARA-CAUNLpGa.js";
const xt = () => "9.1.0", Ht = (e) => e.toString(16).padStart(2, "0"), Ut = (e) => {
  const t = new Uint8Array(e / 2);
  return window.crypto.getRandomValues(t), Array.from(t, Ht).join("");
}, jt = () => typeof window < "u" ? Ut(10) : (/* @__PURE__ */ new Date()).getTime().toString(36);
class re {
}
re.makeRequest = (e, t) => ({
  id: jt(),
  method: e,
  params: t,
  env: {
    sdkVersion: xt()
  }
});
re.makeResponse = (e, t, n) => ({
  id: e,
  success: !0,
  version: n,
  data: t
});
re.makeErrorResponse = (e, t, n) => ({
  id: e,
  success: !1,
  error: t,
  version: n
});
var w;
(function(e) {
  e.sendTransactions = "sendTransactions", e.rpcCall = "rpcCall", e.getChainInfo = "getChainInfo", e.getSafeInfo = "getSafeInfo", e.getTxBySafeTxHash = "getTxBySafeTxHash", e.getSafeBalances = "getSafeBalances", e.signMessage = "signMessage", e.signTypedMessage = "signTypedMessage", e.getEnvironmentInfo = "getEnvironmentInfo", e.getOffChainSignature = "getOffChainSignature", e.requestAddressBook = "requestAddressBook", e.wallet_getPermissions = "wallet_getPermissions", e.wallet_requestPermissions = "wallet_requestPermissions";
})(w || (w = {}));
var be;
(function(e) {
  e.requestAddressBook = "requestAddressBook";
})(be || (be = {}));
class zt {
  constructor(t = null, n = !1) {
    this.allowedOrigins = null, this.callbacks = /* @__PURE__ */ new Map(), this.debugMode = !1, this.isServer = typeof window > "u", this.isValidMessage = ({ origin: s, data: r, source: i }) => {
      const a = !r, c = !this.isServer && i === window.parent, d = typeof r.version < "u" && parseInt(r.version.split(".")[0]), l = typeof d == "number" && d >= 1;
      let h = !0;
      return Array.isArray(this.allowedOrigins) && (h = this.allowedOrigins.find((g) => g.test(s)) !== void 0), !a && c && l && h;
    }, this.logIncomingMessage = (s) => {
    }, this.onParentMessage = (s) => {
      this.isValidMessage(s) && (this.debugMode && this.logIncomingMessage(s), this.handleIncomingMessage(s.data));
    }, this.handleIncomingMessage = (s) => {
      const { id: r } = s, i = this.callbacks.get(r);
      i && (i(s), this.callbacks.delete(r));
    }, this.send = (s, r) => {
      const i = re.makeRequest(s, r);
      if (this.isServer)
        throw new Error("Window doesn't exist");
      return window.parent.postMessage(i, "*"), new Promise((a, c) => {
        this.callbacks.set(i.id, (d) => {
          if (!d.success) {
            c(new Error(d.error));
            return;
          }
          a(d);
        });
      });
    }, this.allowedOrigins = t, this.debugMode = n, this.isServer || window.addEventListener("message", this.onParentMessage);
  }
}
const qe = (e) => typeof e == "object" && e != null && "domain" in e && "types" in e && "message" in e;
var Ve = {}, k = {}, D = {}, Ee = { exports: {} };
(function(e, t) {
  var n = typeof self < "u" ? self : N, s = function() {
    function i() {
      this.fetch = !1, this.DOMException = n.DOMException;
    }
    return i.prototype = n, new i();
  }();
  (function(i) {
    (function(a) {
      var c = {
        searchParams: "URLSearchParams" in i,
        iterable: "Symbol" in i && "iterator" in Symbol,
        blob: "FileReader" in i && "Blob" in i && function() {
          try {
            return new Blob(), !0;
          } catch {
            return !1;
          }
        }(),
        formData: "FormData" in i,
        arrayBuffer: "ArrayBuffer" in i
      };
      function d(o) {
        return o && DataView.prototype.isPrototypeOf(o);
      }
      if (c.arrayBuffer)
        var l = [
          "[object Int8Array]",
          "[object Uint8Array]",
          "[object Uint8ClampedArray]",
          "[object Int16Array]",
          "[object Uint16Array]",
          "[object Int32Array]",
          "[object Uint32Array]",
          "[object Float32Array]",
          "[object Float64Array]"
        ], h = ArrayBuffer.isView || function(o) {
          return o && l.indexOf(Object.prototype.toString.call(o)) > -1;
        };
      function g(o) {
        if (typeof o != "string" && (o = String(o)), /[^a-z0-9\-#$%&'*+.^_`|~]/i.test(o))
          throw new TypeError("Invalid character in header field name");
        return o.toLowerCase();
      }
      function I(o) {
        return typeof o != "string" && (o = String(o)), o;
      }
      function T(o) {
        var u = {
          next: function() {
            var f = o.shift();
            return { done: f === void 0, value: f };
          }
        };
        return c.iterable && (u[Symbol.iterator] = function() {
          return u;
        }), u;
      }
      function m(o) {
        this.map = {}, o instanceof m ? o.forEach(function(u, f) {
          this.append(f, u);
        }, this) : Array.isArray(o) ? o.forEach(function(u) {
          this.append(u[0], u[1]);
        }, this) : o && Object.getOwnPropertyNames(o).forEach(function(u) {
          this.append(u, o[u]);
        }, this);
      }
      m.prototype.append = function(o, u) {
        o = g(o), u = I(u);
        var f = this.map[o];
        this.map[o] = f ? f + ", " + u : u;
      }, m.prototype.delete = function(o) {
        delete this.map[g(o)];
      }, m.prototype.get = function(o) {
        return o = g(o), this.has(o) ? this.map[o] : null;
      }, m.prototype.has = function(o) {
        return this.map.hasOwnProperty(g(o));
      }, m.prototype.set = function(o, u) {
        this.map[g(o)] = I(u);
      }, m.prototype.forEach = function(o, u) {
        for (var f in this.map)
          this.map.hasOwnProperty(f) && o.call(u, this.map[f], f, this);
      }, m.prototype.keys = function() {
        var o = [];
        return this.forEach(function(u, f) {
          o.push(f);
        }), T(o);
      }, m.prototype.values = function() {
        var o = [];
        return this.forEach(function(u) {
          o.push(u);
        }), T(o);
      }, m.prototype.entries = function() {
        var o = [];
        return this.forEach(function(u, f) {
          o.push([f, u]);
        }), T(o);
      }, c.iterable && (m.prototype[Symbol.iterator] = m.prototype.entries);
      function R(o) {
        if (o.bodyUsed)
          return Promise.reject(new TypeError("Already read"));
        o.bodyUsed = !0;
      }
      function v(o) {
        return new Promise(function(u, f) {
          o.onload = function() {
            u(o.result);
          }, o.onerror = function() {
            f(o.error);
          };
        });
      }
      function H(o) {
        var u = new FileReader(), f = v(u);
        return u.readAsArrayBuffer(o), f;
      }
      function ce(o) {
        var u = new FileReader(), f = v(u);
        return u.readAsText(o), f;
      }
      function ue(o) {
        for (var u = new Uint8Array(o), f = new Array(u.length), p = 0; p < u.length; p++)
          f[p] = String.fromCharCode(u[p]);
        return f.join("");
      }
      function Q(o) {
        if (o.slice)
          return o.slice(0);
        var u = new Uint8Array(o.byteLength);
        return u.set(new Uint8Array(o)), u.buffer;
      }
      function J() {
        return this.bodyUsed = !1, this._initBody = function(o) {
          this._bodyInit = o, o ? typeof o == "string" ? this._bodyText = o : c.blob && Blob.prototype.isPrototypeOf(o) ? this._bodyBlob = o : c.formData && FormData.prototype.isPrototypeOf(o) ? this._bodyFormData = o : c.searchParams && URLSearchParams.prototype.isPrototypeOf(o) ? this._bodyText = o.toString() : c.arrayBuffer && c.blob && d(o) ? (this._bodyArrayBuffer = Q(o.buffer), this._bodyInit = new Blob([this._bodyArrayBuffer])) : c.arrayBuffer && (ArrayBuffer.prototype.isPrototypeOf(o) || h(o)) ? this._bodyArrayBuffer = Q(o) : this._bodyText = o = Object.prototype.toString.call(o) : this._bodyText = "", this.headers.get("content-type") || (typeof o == "string" ? this.headers.set("content-type", "text/plain;charset=UTF-8") : this._bodyBlob && this._bodyBlob.type ? this.headers.set("content-type", this._bodyBlob.type) : c.searchParams && URLSearchParams.prototype.isPrototypeOf(o) && this.headers.set("content-type", "application/x-www-form-urlencoded;charset=UTF-8"));
        }, c.blob && (this.blob = function() {
          var o = R(this);
          if (o)
            return o;
          if (this._bodyBlob)
            return Promise.resolve(this._bodyBlob);
          if (this._bodyArrayBuffer)
            return Promise.resolve(new Blob([this._bodyArrayBuffer]));
          if (this._bodyFormData)
            throw new Error("could not read FormData body as blob");
          return Promise.resolve(new Blob([this._bodyText]));
        }, this.arrayBuffer = function() {
          return this._bodyArrayBuffer ? R(this) || Promise.resolve(this._bodyArrayBuffer) : this.blob().then(H);
        }), this.text = function() {
          var o = R(this);
          if (o)
            return o;
          if (this._bodyBlob)
            return ce(this._bodyBlob);
          if (this._bodyArrayBuffer)
            return Promise.resolve(ue(this._bodyArrayBuffer));
          if (this._bodyFormData)
            throw new Error("could not read FormData body as text");
          return Promise.resolve(this._bodyText);
        }, c.formData && (this.formData = function() {
          return this.text().then(le);
        }), this.json = function() {
          return this.text().then(JSON.parse);
        }, this;
      }
      var fe = ["DELETE", "GET", "HEAD", "OPTIONS", "POST", "PUT"];
      function de(o) {
        var u = o.toUpperCase();
        return fe.indexOf(u) > -1 ? u : o;
      }
      function P(o, u) {
        u = u || {};
        var f = u.body;
        if (o instanceof P) {
          if (o.bodyUsed)
            throw new TypeError("Already read");
          this.url = o.url, this.credentials = o.credentials, u.headers || (this.headers = new m(o.headers)), this.method = o.method, this.mode = o.mode, this.signal = o.signal, !f && o._bodyInit != null && (f = o._bodyInit, o.bodyUsed = !0);
        } else
          this.url = String(o);
        if (this.credentials = u.credentials || this.credentials || "same-origin", (u.headers || !this.headers) && (this.headers = new m(u.headers)), this.method = de(u.method || this.method || "GET"), this.mode = u.mode || this.mode || null, this.signal = u.signal || this.signal, this.referrer = null, (this.method === "GET" || this.method === "HEAD") && f)
          throw new TypeError("Body not allowed for GET or HEAD requests");
        this._initBody(f);
      }
      P.prototype.clone = function() {
        return new P(this, { body: this._bodyInit });
      };
      function le(o) {
        var u = new FormData();
        return o.trim().split("&").forEach(function(f) {
          if (f) {
            var p = f.split("="), b = p.shift().replace(/\+/g, " "), y = p.join("=").replace(/\+/g, " ");
            u.append(decodeURIComponent(b), decodeURIComponent(y));
          }
        }), u;
      }
      function he(o) {
        var u = new m(), f = o.replace(/\r?\n[\t ]+/g, " ");
        return f.split(/\r?\n/).forEach(function(p) {
          var b = p.split(":"), y = b.shift().trim();
          if (y) {
            var Y = b.join(":").trim();
            u.append(y, Y);
          }
        }), u;
      }
      J.call(P.prototype);
      function S(o, u) {
        u || (u = {}), this.type = "default", this.status = u.status === void 0 ? 200 : u.status, this.ok = this.status >= 200 && this.status < 300, this.statusText = "statusText" in u ? u.statusText : "OK", this.headers = new m(u.headers), this.url = u.url || "", this._initBody(o);
      }
      J.call(S.prototype), S.prototype.clone = function() {
        return new S(this._bodyInit, {
          status: this.status,
          statusText: this.statusText,
          headers: new m(this.headers),
          url: this.url
        });
      }, S.error = function() {
        var o = new S(null, { status: 0, statusText: "" });
        return o.type = "error", o;
      };
      var ge = [301, 302, 303, 307, 308];
      S.redirect = function(o, u) {
        if (ge.indexOf(u) === -1)
          throw new RangeError("Invalid status code");
        return new S(null, { status: u, headers: { location: o } });
      }, a.DOMException = i.DOMException;
      try {
        new a.DOMException();
      } catch {
        a.DOMException = function(u, f) {
          this.message = u, this.name = f;
          var p = Error(u);
          this.stack = p.stack;
        }, a.DOMException.prototype = Object.create(Error.prototype), a.DOMException.prototype.constructor = a.DOMException;
      }
      function U(o, u) {
        return new Promise(function(f, p) {
          var b = new P(o, u);
          if (b.signal && b.signal.aborted)
            return p(new a.DOMException("Aborted", "AbortError"));
          var y = new XMLHttpRequest();
          function Y() {
            y.abort();
          }
          y.onload = function() {
            var j = {
              status: y.status,
              statusText: y.statusText,
              headers: he(y.getAllResponseHeaders() || "")
            };
            j.url = "responseURL" in y ? y.responseURL : j.headers.get("X-Request-URL");
            var pe = "response" in y ? y.response : y.responseText;
            f(new S(pe, j));
          }, y.onerror = function() {
            p(new TypeError("Network request failed"));
          }, y.ontimeout = function() {
            p(new TypeError("Network request failed"));
          }, y.onabort = function() {
            p(new a.DOMException("Aborted", "AbortError"));
          }, y.open(b.method, b.url, !0), b.credentials === "include" ? y.withCredentials = !0 : b.credentials === "omit" && (y.withCredentials = !1), "responseType" in y && c.blob && (y.responseType = "blob"), b.headers.forEach(function(j, pe) {
            y.setRequestHeader(pe, j);
          }), b.signal && (b.signal.addEventListener("abort", Y), y.onreadystatechange = function() {
            y.readyState === 4 && b.signal.removeEventListener("abort", Y);
          }), y.send(typeof b._bodyInit > "u" ? null : b._bodyInit);
        });
      }
      return U.polyfill = !0, i.fetch || (i.fetch = U, i.Headers = m, i.Request = P, i.Response = S), a.Headers = m, a.Request = P, a.Response = S, a.fetch = U, Object.defineProperty(a, "__esModule", { value: !0 }), a;
    })({});
  })(s), s.fetch.ponyfill = !0, delete s.fetch.polyfill;
  var r = s;
  t = r.fetch, t.default = r.fetch, t.fetch = r.fetch, t.Headers = r.Headers, t.Request = r.Request, t.Response = r.Response, e.exports = t;
})(Ee, Ee.exports);
var Ft = Ee.exports, Gt = N && N.__awaiter || function(e, t, n, s) {
  function r(i) {
    return i instanceof n ? i : new n(function(a) {
      a(i);
    });
  }
  return new (n || (n = Promise))(function(i, a) {
    function c(h) {
      try {
        l(s.next(h));
      } catch (g) {
        a(g);
      }
    }
    function d(h) {
      try {
        l(s.throw(h));
      } catch (g) {
        a(g);
      }
    }
    function l(h) {
      h.done ? i(h.value) : r(h.value).then(c, d);
    }
    l((s = s.apply(e, t || [])).next());
  });
}, qt = N && N.__importDefault || function(e) {
  return e && e.__esModule ? e : { default: e };
};
Object.defineProperty(D, "__esModule", { value: !0 });
D.fetchData = D.stringifyQuery = D.insertParams = void 0;
const Vt = qt(Ft), Wt = (e) => typeof e == "object" && e !== null && "code" in e && "message" in e;
function Kt(e, t, n) {
  return e.replace(new RegExp(`\\{${t}\\}`, "g"), n);
}
function Xt(e, t) {
  return t ? Object.keys(t).reduce((n, s) => Kt(n, s, String(t[s])), e) : e;
}
D.insertParams = Xt;
function Qt(e) {
  if (!e)
    return "";
  const t = new URLSearchParams();
  Object.keys(e).forEach((s) => {
    e[s] != null && t.append(s, String(e[s]));
  });
  const n = t.toString();
  return n ? `?${n}` : "";
}
D.stringifyQuery = Qt;
function Jt(e, t) {
  return Gt(this, void 0, void 0, function* () {
    let n;
    t != null && (n = {
      method: "POST",
      body: typeof t == "string" ? t : JSON.stringify(t),
      headers: { "Content-Type": "application/json" }
    });
    const s = yield (0, Vt.default)(e, n);
    let r;
    try {
      r = yield s.json();
    } catch {
      if (s.headers && s.headers.get("content-length") !== "0")
        throw new Error(`Invalid response content: ${s.statusText}`);
    }
    if (!s.ok) {
      const i = Wt(r) ? `${r.code}: ${r.message}` : s.statusText;
      throw new Error(i);
    }
    return r;
  });
}
D.fetchData = Jt;
Object.defineProperty(k, "__esModule", { value: !0 });
k.getEndpoint = k.postEndpoint = void 0;
const q = D;
function We(e, t, n, s) {
  const r = (0, q.insertParams)(t, n), i = (0, q.stringifyQuery)(s);
  return `${e}${r}${i}`;
}
function Yt(e, t, n) {
  const s = We(e, t, n == null ? void 0 : n.path, n == null ? void 0 : n.query);
  return (0, q.fetchData)(s, n == null ? void 0 : n.body);
}
k.postEndpoint = Yt;
function Zt(e, t, n, s) {
  if (s)
    return (0, q.fetchData)(s);
  const r = We(e, t, n == null ? void 0 : n.path, n == null ? void 0 : n.query);
  return (0, q.fetchData)(r);
}
k.getEndpoint = Zt;
var ie = {};
Object.defineProperty(ie, "__esModule", { value: !0 });
ie.DEFAULT_BASE_URL = void 0;
ie.DEFAULT_BASE_URL = "https://safe-client.safe.global";
var Ke = {};
(function(e) {
  Object.defineProperty(e, "__esModule", { value: !0 }), e.ImplementationVersionState = void 0, function(t) {
    t.UP_TO_DATE = "UP_TO_DATE", t.OUTDATED = "OUTDATED", t.UNKNOWN = "UNKNOWN";
  }(e.ImplementationVersionState || (e.ImplementationVersionState = {}));
})(Ke);
var Xe = {};
(function(e) {
  Object.defineProperty(e, "__esModule", { value: !0 }), e.SafeAppSocialPlatforms = e.SafeAppFeatures = e.SafeAppAccessPolicyTypes = void 0, function(t) {
    t.NoRestrictions = "NO_RESTRICTIONS", t.DomainAllowlist = "DOMAIN_ALLOWLIST";
  }(e.SafeAppAccessPolicyTypes || (e.SafeAppAccessPolicyTypes = {})), function(t) {
    t.BATCHED_TRANSACTIONS = "BATCHED_TRANSACTIONS";
  }(e.SafeAppFeatures || (e.SafeAppFeatures = {})), function(t) {
    t.TWITTER = "TWITTER", t.GITHUB = "GITHUB", t.DISCORD = "DISCORD";
  }(e.SafeAppSocialPlatforms || (e.SafeAppSocialPlatforms = {}));
})(Xe);
var Qe = {};
(function(e) {
  Object.defineProperty(e, "__esModule", { value: !0 }), e.LabelValue = e.DetailedExecutionInfoType = e.TransactionListItemType = e.ConflictType = e.TransactionInfoType = e.SettingsInfoType = e.TransactionTokenType = e.TransferDirection = e.TransactionStatus = e.Operation = void 0, function(t) {
    t[t.CALL = 0] = "CALL", t[t.DELEGATE = 1] = "DELEGATE";
  }(e.Operation || (e.Operation = {})), function(t) {
    t.AWAITING_CONFIRMATIONS = "AWAITING_CONFIRMATIONS", t.AWAITING_EXECUTION = "AWAITING_EXECUTION", t.CANCELLED = "CANCELLED", t.FAILED = "FAILED", t.SUCCESS = "SUCCESS";
  }(e.TransactionStatus || (e.TransactionStatus = {})), function(t) {
    t.INCOMING = "INCOMING", t.OUTGOING = "OUTGOING", t.UNKNOWN = "UNKNOWN";
  }(e.TransferDirection || (e.TransferDirection = {})), function(t) {
    t.ERC20 = "ERC20", t.ERC721 = "ERC721", t.NATIVE_COIN = "NATIVE_COIN";
  }(e.TransactionTokenType || (e.TransactionTokenType = {})), function(t) {
    t.SET_FALLBACK_HANDLER = "SET_FALLBACK_HANDLER", t.ADD_OWNER = "ADD_OWNER", t.REMOVE_OWNER = "REMOVE_OWNER", t.SWAP_OWNER = "SWAP_OWNER", t.CHANGE_THRESHOLD = "CHANGE_THRESHOLD", t.CHANGE_IMPLEMENTATION = "CHANGE_IMPLEMENTATION", t.ENABLE_MODULE = "ENABLE_MODULE", t.DISABLE_MODULE = "DISABLE_MODULE", t.SET_GUARD = "SET_GUARD", t.DELETE_GUARD = "DELETE_GUARD";
  }(e.SettingsInfoType || (e.SettingsInfoType = {})), function(t) {
    t.TRANSFER = "Transfer", t.SETTINGS_CHANGE = "SettingsChange", t.CUSTOM = "Custom", t.CREATION = "Creation";
  }(e.TransactionInfoType || (e.TransactionInfoType = {})), function(t) {
    t.NONE = "None", t.HAS_NEXT = "HasNext", t.END = "End";
  }(e.ConflictType || (e.ConflictType = {})), function(t) {
    t.TRANSACTION = "TRANSACTION", t.LABEL = "LABEL", t.CONFLICT_HEADER = "CONFLICT_HEADER", t.DATE_LABEL = "DATE_LABEL";
  }(e.TransactionListItemType || (e.TransactionListItemType = {})), function(t) {
    t.MULTISIG = "MULTISIG", t.MODULE = "MODULE";
  }(e.DetailedExecutionInfoType || (e.DetailedExecutionInfoType = {})), function(t) {
    t.Queued = "Queued", t.Next = "Next";
  }(e.LabelValue || (e.LabelValue = {}));
})(Qe);
var Je = {};
(function(e) {
  Object.defineProperty(e, "__esModule", { value: !0 }), e.FEATURES = e.GAS_PRICE_TYPE = e.RPC_AUTHENTICATION = void 0, function(t) {
    t.API_KEY_PATH = "API_KEY_PATH", t.NO_AUTHENTICATION = "NO_AUTHENTICATION", t.UNKNOWN = "UNKNOWN";
  }(e.RPC_AUTHENTICATION || (e.RPC_AUTHENTICATION = {})), function(t) {
    t.ORACLE = "ORACLE", t.FIXED = "FIXED", t.UNKNOWN = "UNKNOWN";
  }(e.GAS_PRICE_TYPE || (e.GAS_PRICE_TYPE = {})), function(t) {
    t.ERC721 = "ERC721", t.SAFE_APPS = "SAFE_APPS", t.CONTRACT_INTERACTION = "CONTRACT_INTERACTION", t.DOMAIN_LOOKUP = "DOMAIN_LOOKUP", t.SPENDING_LIMIT = "SPENDING_LIMIT", t.EIP1559 = "EIP1559", t.SAFE_TX_GAS_OPTIONAL = "SAFE_TX_GAS_OPTIONAL", t.TX_SIMULATION = "TX_SIMULATION", t.EIP1271 = "EIP1271";
  }(e.FEATURES || (e.FEATURES = {}));
})(Je);
var Ye = {};
(function(e) {
  Object.defineProperty(e, "__esModule", { value: !0 }), e.TokenType = void 0, function(t) {
    t.ERC20 = "ERC20", t.ERC721 = "ERC721", t.NATIVE_TOKEN = "NATIVE_TOKEN";
  }(e.TokenType || (e.TokenType = {}));
})(Ye);
var Ze = {};
Object.defineProperty(Ze, "__esModule", { value: !0 });
var et = {};
Object.defineProperty(et, "__esModule", { value: !0 });
var tt = {};
(function(e) {
  Object.defineProperty(e, "__esModule", { value: !0 }), e.SafeMessageStatus = e.SafeMessageListItemType = void 0, function(t) {
    t.DATE_LABEL = "DATE_LABEL", t.MESSAGE = "MESSAGE";
  }(e.SafeMessageListItemType || (e.SafeMessageListItemType = {})), function(t) {
    t.NEEDS_CONFIRMATION = "NEEDS_CONFIRMATION", t.CONFIRMED = "CONFIRMED";
  }(e.SafeMessageStatus || (e.SafeMessageStatus = {}));
})(tt);
(function(e) {
  var t = N && N.__createBinding || (Object.create ? function(o, u, f, p) {
    p === void 0 && (p = f);
    var b = Object.getOwnPropertyDescriptor(u, f);
    (!b || ("get" in b ? !u.__esModule : b.writable || b.configurable)) && (b = { enumerable: !0, get: function() {
      return u[f];
    } }), Object.defineProperty(o, p, b);
  } : function(o, u, f, p) {
    p === void 0 && (p = f), o[p] = u[f];
  }), n = N && N.__exportStar || function(o, u) {
    for (var f in o) f !== "default" && !Object.prototype.hasOwnProperty.call(u, f) && t(u, o, f);
  };
  Object.defineProperty(e, "__esModule", { value: !0 }), e.confirmSafeMessage = e.proposeSafeMessage = e.getSafeMessage = e.getSafeMessages = e.getDecodedData = e.getMasterCopies = e.getSafeApps = e.getChainConfig = e.getChainsConfig = e.proposeTransaction = e.postSafeGasEstimation = e.getTransactionDetails = e.getTransactionQueue = e.getTransactionHistory = e.getCollectiblesPage = e.getCollectibles = e.getOwnedSafes = e.getFiatCurrencies = e.getBalances = e.getMultisigTransactions = e.getModuleTransactions = e.getIncomingTransfers = e.getSafeInfo = e.setBaseUrl = void 0;
  const s = k, r = ie;
  n(Ke, e), n(Xe, e), n(Qe, e), n(Je, e), n(Ye, e), n(Ze, e), n(et, e), n(tt, e);
  let i = r.DEFAULT_BASE_URL;
  const a = (o) => {
    i = o;
  };
  e.setBaseUrl = a;
  function c(o, u) {
    return (0, s.getEndpoint)(i, "/v1/chains/{chainId}/safes/{address}", { path: { chainId: o, address: u } });
  }
  e.getSafeInfo = c;
  function d(o, u, f, p) {
    return (0, s.getEndpoint)(i, "/v1/chains/{chainId}/safes/{address}/incoming-transfers/", {
      path: { chainId: o, address: u },
      query: f
    }, p);
  }
  e.getIncomingTransfers = d;
  function l(o, u, f, p) {
    return (0, s.getEndpoint)(i, "/v1/chains/{chainId}/safes/{address}/module-transactions/", {
      path: { chainId: o, address: u },
      query: f
    }, p);
  }
  e.getModuleTransactions = l;
  function h(o, u, f, p) {
    return (0, s.getEndpoint)(i, "/v1/chains/{chainId}/safes/{address}/multisig-transactions/", {
      path: { chainId: o, address: u },
      query: f
    }, p);
  }
  e.getMultisigTransactions = h;
  function g(o, u, f = "usd", p = {}) {
    return (0, s.getEndpoint)(i, "/v1/chains/{chainId}/safes/{address}/balances/{currency}", {
      path: { chainId: o, address: u, currency: f },
      query: p
    });
  }
  e.getBalances = g;
  function I() {
    return (0, s.getEndpoint)(i, "/v1/balances/supported-fiat-codes");
  }
  e.getFiatCurrencies = I;
  function T(o, u) {
    return (0, s.getEndpoint)(i, "/v1/chains/{chainId}/owners/{address}/safes", { path: { chainId: o, address: u } });
  }
  e.getOwnedSafes = T;
  function m(o, u, f = {}) {
    return (0, s.getEndpoint)(i, "/v1/chains/{chainId}/safes/{address}/collectibles", {
      path: { chainId: o, address: u },
      query: f
    });
  }
  e.getCollectibles = m;
  function R(o, u, f = {}, p) {
    return (0, s.getEndpoint)(i, "/v2/chains/{chainId}/safes/{address}/collectibles", { path: { chainId: o, address: u }, query: f }, p);
  }
  e.getCollectiblesPage = R;
  function v(o, u, f) {
    return (0, s.getEndpoint)(i, "/v1/chains/{chainId}/safes/{safe_address}/transactions/history", { path: { chainId: o, safe_address: u }, query: {} }, f);
  }
  e.getTransactionHistory = v;
  function H(o, u, f, p) {
    return (0, s.getEndpoint)(i, "/v1/chains/{chainId}/safes/{safe_address}/transactions/queued", { path: { chainId: o, safe_address: u }, query: { trusted: p } }, f);
  }
  e.getTransactionQueue = H;
  function ce(o, u) {
    return (0, s.getEndpoint)(i, "/v1/chains/{chainId}/transactions/{transactionId}", {
      path: { chainId: o, transactionId: u }
    });
  }
  e.getTransactionDetails = ce;
  function ue(o, u, f) {
    return (0, s.postEndpoint)(i, "/v2/chains/{chainId}/safes/{safe_address}/multisig-transactions/estimations", {
      path: { chainId: o, safe_address: u },
      body: f
    });
  }
  e.postSafeGasEstimation = ue;
  function Q(o, u, f) {
    return (0, s.postEndpoint)(i, "/v1/chains/{chainId}/transactions/{safe_address}/propose", {
      path: { chainId: o, safe_address: u },
      body: f
    });
  }
  e.proposeTransaction = Q;
  function J(o) {
    return (0, s.getEndpoint)(i, "/v1/chains", {
      query: o
    });
  }
  e.getChainsConfig = J;
  function fe(o) {
    return (0, s.getEndpoint)(i, "/v1/chains/{chainId}", {
      path: { chainId: o }
    });
  }
  e.getChainConfig = fe;
  function de(o, u = {}) {
    return (0, s.getEndpoint)(i, "/v1/chains/{chainId}/safe-apps", {
      path: { chainId: o },
      query: u
    });
  }
  e.getSafeApps = de;
  function P(o) {
    return (0, s.getEndpoint)(i, "/v1/chains/{chainId}/about/master-copies", {
      path: { chainId: o }
    });
  }
  e.getMasterCopies = P;
  function le(o, u) {
    return (0, s.postEndpoint)(i, "/v1/chains/{chainId}/data-decoder", {
      path: { chainId: o },
      body: { data: u }
    });
  }
  e.getDecodedData = le;
  function he(o, u, f) {
    return (0, s.getEndpoint)(i, "/v1/chains/{chainId}/safes/{safe_address}/messages", { path: { chainId: o, safe_address: u }, query: {} }, f);
  }
  e.getSafeMessages = he;
  function S(o, u) {
    return (0, s.getEndpoint)(i, "/v1/chains/{chainId}/messages/{message_hash}", {
      path: { chainId: o, message_hash: u }
    });
  }
  e.getSafeMessage = S;
  function ge(o, u, f) {
    return (0, s.postEndpoint)(i, "/v1/chains/{chainId}/safes/{safe_address}/messages", {
      path: { chainId: o, safe_address: u },
      body: f
    });
  }
  e.proposeSafeMessage = ge;
  function U(o, u, f) {
    return (0, s.postEndpoint)(i, "/v1/chains/{chainId}/messages/{message_hash}/signatures", {
      path: { chainId: o, message_hash: u },
      body: f
    });
  }
  e.confirmSafeMessage = U;
})(Ve);
class en {
  constructor(t) {
    this.communicator = t;
  }
  async getBySafeTxHash(t) {
    if (!t)
      throw new Error("Invalid safeTxHash");
    return (await this.communicator.send(w.getTxBySafeTxHash, { safeTxHash: t })).data;
  }
  async signMessage(t) {
    const n = {
      message: t
    };
    return (await this.communicator.send(w.signMessage, n)).data;
  }
  async signTypedMessage(t) {
    if (!qe(t))
      throw new Error("Invalid typed data");
    return (await this.communicator.send(w.signTypedMessage, { typedData: t })).data;
  }
  async send({ txs: t, params: n }) {
    if (!t || !t.length)
      throw new Error("No transactions were passed");
    const s = {
      txs: t,
      params: n
    };
    return (await this.communicator.send(w.sendTransactions, s)).data;
  }
}
const A = {
  eth_call: "eth_call",
  eth_gasPrice: "eth_gasPrice",
  eth_getLogs: "eth_getLogs",
  eth_getBalance: "eth_getBalance",
  eth_getCode: "eth_getCode",
  eth_getBlockByHash: "eth_getBlockByHash",
  eth_getBlockByNumber: "eth_getBlockByNumber",
  eth_getStorageAt: "eth_getStorageAt",
  eth_getTransactionByHash: "eth_getTransactionByHash",
  eth_getTransactionReceipt: "eth_getTransactionReceipt",
  eth_getTransactionCount: "eth_getTransactionCount",
  eth_estimateGas: "eth_estimateGas",
  safe_setSettings: "safe_setSettings"
}, C = {
  defaultBlockParam: (e = "latest") => e,
  returnFullTxObjectParam: (e = !1) => e,
  blockNumberToHex: (e) => Number.isInteger(e) ? `0x${e.toString(16)}` : e
};
class tn {
  constructor(t) {
    this.communicator = t, this.call = this.buildRequest({
      call: A.eth_call,
      formatters: [null, C.defaultBlockParam]
    }), this.getBalance = this.buildRequest({
      call: A.eth_getBalance,
      formatters: [null, C.defaultBlockParam]
    }), this.getCode = this.buildRequest({
      call: A.eth_getCode,
      formatters: [null, C.defaultBlockParam]
    }), this.getStorageAt = this.buildRequest({
      call: A.eth_getStorageAt,
      formatters: [null, C.blockNumberToHex, C.defaultBlockParam]
    }), this.getPastLogs = this.buildRequest({
      call: A.eth_getLogs
    }), this.getBlockByHash = this.buildRequest({
      call: A.eth_getBlockByHash,
      formatters: [null, C.returnFullTxObjectParam]
    }), this.getBlockByNumber = this.buildRequest({
      call: A.eth_getBlockByNumber,
      formatters: [C.blockNumberToHex, C.returnFullTxObjectParam]
    }), this.getTransactionByHash = this.buildRequest({
      call: A.eth_getTransactionByHash
    }), this.getTransactionReceipt = this.buildRequest({
      call: A.eth_getTransactionReceipt
    }), this.getTransactionCount = this.buildRequest({
      call: A.eth_getTransactionCount,
      formatters: [null, C.defaultBlockParam]
    }), this.getGasPrice = this.buildRequest({
      call: A.eth_gasPrice
    }), this.getEstimateGas = (n) => this.buildRequest({
      call: A.eth_estimateGas
    })([n]), this.setSafeSettings = this.buildRequest({
      call: A.safe_setSettings
    });
  }
  buildRequest(t) {
    const { call: n, formatters: s } = t;
    return async (r) => {
      s && Array.isArray(r) && s.forEach((c, d) => {
        c && (r[d] = c(r[d]));
      });
      const i = {
        call: n,
        params: r || []
      };
      return (await this.communicator.send(w.rpcCall, i)).data;
    };
  }
}
function nn(e, t) {
  const n = e.exec(t);
  return n == null ? void 0 : n.groups;
}
const De = /^tuple(?<array>(\[(\d*)\])*)$/;
function we(e) {
  let t = e.type;
  if (De.test(e.type) && "components" in e) {
    t = "(";
    const n = e.components.length;
    for (let r = 0; r < n; r++) {
      const i = e.components[r];
      t += we(i), r < n - 1 && (t += ", ");
    }
    const s = nn(De, e.type);
    return t += `)${(s == null ? void 0 : s.array) ?? ""}`, we({
      ...e,
      type: t
    });
  }
  return "indexed" in e && e.indexed && (t = `${t} indexed`), e.name ? `${t} ${e.name}` : t;
}
function z(e) {
  let t = "";
  const n = e.length;
  for (let s = 0; s < n; s++) {
    const r = e[s];
    t += we(r), s !== n - 1 && (t += ", ");
  }
  return t;
}
function sn(e) {
  return e.type === "function" ? `function ${e.name}(${z(e.inputs)})${e.stateMutability && e.stateMutability !== "nonpayable" ? ` ${e.stateMutability}` : ""}${e.outputs.length ? ` returns (${z(e.outputs)})` : ""}` : e.type === "event" ? `event ${e.name}(${z(e.inputs)})` : e.type === "error" ? `error ${e.name}(${z(e.inputs)})` : e.type === "constructor" ? `constructor(${z(e.inputs)})${e.stateMutability === "payable" ? " payable" : ""}` : e.type === "fallback" ? "fallback()" : "receive() external payable";
}
function Ae(e, { includeName: t = !1 } = {}) {
  if (e.type !== "function" && e.type !== "event" && e.type !== "error")
    throw new hn(e.type);
  return `${e.name}(${nt(e.inputs, { includeName: t })})`;
}
function nt(e, { includeName: t = !1 } = {}) {
  return e ? e.map((n) => rn(n, { includeName: t })).join(t ? ", " : ",") : "";
}
function rn(e, { includeName: t }) {
  return e.type.startsWith("tuple") ? `(${nt(e.components, { includeName: t })})${e.type.slice(5)}` : e.type + (t && e.name ? ` ${e.name}` : "");
}
function K(e, { strict: t = !0 } = {}) {
  return !e || typeof e != "string" ? !1 : t ? /^0x[0-9a-fA-F]*$/.test(e) : e.startsWith("0x");
}
function _(e) {
  return K(e, { strict: !1 }) ? Math.ceil((e.length - 2) / 2) : e.length;
}
const st = "2.19.2";
let ee = {
  getDocsUrl: ({ docsBaseUrl: e, docsPath: t = "", docsSlug: n }) => t ? `${e ?? "https://viem.sh"}${t}${n ? `#${n}` : ""}` : void 0,
  version: st
};
class E extends Error {
  constructor(t, n = {}) {
    var c;
    const s = (() => {
      var d;
      return n.cause instanceof E ? n.cause.details : (d = n.cause) != null && d.message ? n.cause.message : n.details;
    })(), r = n.cause instanceof E && n.cause.docsPath || n.docsPath, i = (c = ee.getDocsUrl) == null ? void 0 : c.call(ee, { ...n, docsPath: r }), a = [
      t || "An error occurred.",
      "",
      ...n.metaMessages ? [...n.metaMessages, ""] : [],
      ...i ? [`Docs: ${i}`] : [],
      ...s ? [`Details: ${s}`] : [],
      `Version: ${ee.version}`
    ].join(`
`);
    super(a, n.cause ? { cause: n.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 = s, this.docsPath = r, this.metaMessages = n.metaMessages, this.name = n.name ?? this.name, this.shortMessage = t, this.version = st;
  }
  walk(t) {
    return rt(this, t);
  }
}
function rt(e, t) {
  return t != null && t(e) ? e : e && typeof e == "object" && "cause" in e ? rt(e.cause, t) : t ? null : e;
}
class on extends E {
  constructor({ expectedLength: t, givenLength: n, type: s }) {
    super([
      `ABI encoding array length mismatch for type ${s}.`,
      `Expected length: ${t}`,
      `Given length: ${n}`
    ].join(`
`), { name: "AbiEncodingArrayLengthMismatchError" });
  }
}
class an extends E {
  constructor({ expectedSize: t, value: n }) {
    super(`Size of bytes "${n}" (bytes${_(n)}) does not match expected size (bytes${t}).`, { name: "AbiEncodingBytesSizeMismatchError" });
  }
}
class cn extends E {
  constructor({ expectedLength: t, givenLength: n }) {
    super([
      "ABI encoding params/values length mismatch.",
      `Expected length (params): ${t}`,
      `Given length (values): ${n}`
    ].join(`
`), { name: "AbiEncodingLengthMismatchError" });
  }
}
class Le extends E {
  constructor(t, { docsPath: n } = {}) {
    super([
      `Function ${t ? `"${t}" ` : ""}not found on ABI.`,
      "Make sure you are using the correct ABI and that the function exists on it."
    ].join(`
`), {
      docsPath: n,
      name: "AbiFunctionNotFoundError"
    });
  }
}
class un extends E {
  constructor(t, n) {
    super("Found ambiguous types in overloaded ABI items.", {
      metaMessages: [
        `\`${t.type}\` in \`${Ae(t.abiItem)}\`, and`,
        `\`${n.type}\` in \`${Ae(n.abiItem)}\``,
        "",
        "These types encode differently and cannot be distinguished at runtime.",
        "Remove one of the ambiguous items in the ABI."
      ],
      name: "AbiItemAmbiguityError"
    });
  }
}
class fn extends E {
  constructor({ expectedSize: t, givenSize: n }) {
    super(`Expected bytes${t}, got bytes${n}.`, {
      name: "BytesSizeMismatchError"
    });
  }
}
class dn extends E {
  constructor(t, { docsPath: n }) {
    super([
      `Type "${t}" is not a valid encoding type.`,
      "Please provide a valid ABI type."
    ].join(`
`), { docsPath: n, name: "InvalidAbiEncodingType" });
  }
}
class ln extends E {
  constructor(t) {
    super([`Value "${t}" is not a valid array.`].join(`
`), {
      name: "InvalidArrayError"
    });
  }
}
class hn extends E {
  constructor(t) {
    super([
      `"${t}" is not a valid definition type.`,
      'Valid types: "function", "event", "error"'
    ].join(`
`), { name: "InvalidDefinitionTypeError" });
  }
}
class it extends E {
  constructor({ offset: t, position: n, size: s }) {
    super(`Slice ${n === "start" ? "starting" : "ending"} at offset "${t}" is out-of-bounds (size: ${s}).`, { name: "SliceOffsetOutOfBoundsError" });
  }
}
class ot extends E {
  constructor({ size: t, targetSize: n, type: s }) {
    super(`${s.charAt(0).toUpperCase()}${s.slice(1).toLowerCase()} size (${t}) exceeds padding size (${n}).`, { name: "SizeExceedsPaddingSizeError" });
  }
}
function x(e, { dir: t, size: n = 32 } = {}) {
  return typeof e == "string" ? L(e, { dir: t, size: n }) : gn(e, { dir: t, size: n });
}
function L(e, { dir: t, size: n = 32 } = {}) {
  if (n === null)
    return e;
  const s = e.replace("0x", "");
  if (s.length > n * 2)
    throw new ot({
      size: Math.ceil(s.length / 2),
      targetSize: n,
      type: "hex"
    });
  return `0x${s[t === "right" ? "padEnd" : "padStart"](n * 2, "0")}`;
}
function gn(e, { dir: t, size: n = 32 } = {}) {
  if (n === null)
    return e;
  if (e.length > n)
    throw new ot({
      size: e.length,
      targetSize: n,
      type: "bytes"
    });
  const s = new Uint8Array(n);
  for (let r = 0; r < n; r++) {
    const i = t === "right";
    s[i ? r : n - r - 1] = e[i ? r : e.length - r - 1];
  }
  return s;
}
class pn extends E {
  constructor({ max: t, min: n, signed: s, size: r, value: i }) {
    super(`Number "${i}" is not in safe ${r ? `${r * 8}-bit ${s ? "signed" : "unsigned"} ` : ""}integer range ${t ? `(${n} to ${t})` : `(above ${n})`}`, { name: "IntegerOutOfRangeError" });
  }
}
class yn extends E {
  constructor({ givenSize: t, maxSize: n }) {
    super(`Size cannot exceed ${n} bytes. Given size: ${t} bytes.`, { name: "SizeOverflowError" });
  }
}
function X(e, { size: t }) {
  if (_(e) > t)
    throw new yn({
      givenSize: _(e),
      maxSize: t
    });
}
const mn = /* @__PURE__ */ Array.from({ length: 256 }, (e, t) => t.toString(16).padStart(2, "0"));
function Se(e, t = {}) {
  return typeof e == "number" || typeof e == "bigint" ? $(e, t) : typeof e == "string" ? se(e, t) : typeof e == "boolean" ? at(e, t) : Ie(e, t);
}
function at(e, t = {}) {
  const n = `0x${Number(e)}`;
  return typeof t.size == "number" ? (X(n, { size: t.size }), x(n, { size: t.size })) : n;
}
function Ie(e, t = {}) {
  let n = "";
  for (let r = 0; r < e.length; r++)
    n += mn[e[r]];
  const s = `0x${n}`;
  return typeof t.size == "number" ? (X(s, { size: t.size }), x(s, { dir: "right", size: t.size })) : s;
}
function $(e, t = {}) {
  const { signed: n, size: s } = t, r = BigInt(e);
  let i;
  s ? n ? i = (1n << BigInt(s) * 8n - 1n) - 1n : i = 2n ** (BigInt(s) * 8n) - 1n : typeof e == "number" && (i = BigInt(Number.MAX_SAFE_INTEGER));
  const a = typeof i == "bigint" && n ? -i - 1n : 0;
  if (i && r > i || r < a) {
    const d = typeof e == "bigint" ? "n" : "";
    throw new pn({
      max: i ? `${i}${d}` : void 0,
      min: `${a}${d}`,
      signed: n,
      size: s,
      value: `${e}${d}`
    });
  }
  const c = `0x${(n && r < 0 ? (1n << BigInt(s * 8)) + BigInt(r) : r).toString(16)}`;
  return s ? x(c, { size: s }) : c;
}
const bn = /* @__PURE__ */ new TextEncoder();
function se(e, t = {}) {
  const n = bn.encode(e);
  return Ie(n, t);
}
const En = /* @__PURE__ */ new TextEncoder();
function ct(e, t = {}) {
  return typeof e == "number" || typeof e == "bigint" ? An(e, t) : typeof e == "boolean" ? wn(e, t) : K(e) ? ut(e, t) : ft(e, t);
}
function wn(e, t = {}) {
  const n = new Uint8Array(1);
  return n[0] = Number(e), typeof t.size == "number" ? (X(n, { size: t.size }), x(n, { size: t.size })) : n;
}
const B = {
  zero: 48,
  nine: 57,
  A: 65,
  F: 70,
  a: 97,
  f: 102
};
function Me(e) {
  if (e >= B.zero && e <= B.nine)
    return e - B.zero;
  if (e >= B.A && e <= B.F)
    return e - (B.A - 10);
  if (e >= B.a && e <= B.f)
    return e - (B.a - 10);
}
function ut(e, t = {}) {
  let n = e;
  t.size && (X(n, { size: t.size }), n = x(n, { dir: "right", size: t.size }));
  let s = n.slice(2);
  s.length % 2 && (s = `0${s}`);
  const r = s.length / 2, i = new Uint8Array(r);
  for (let a = 0, c = 0; a < r; a++) {
    const d = Me(s.charCodeAt(c++)), l = Me(s.charCodeAt(c++));
    if (d === void 0 || l === void 0)
      throw new E(`Invalid byte sequence ("${s[c - 2]}${s[c - 1]}" in "${s}").`);
    i[a] = d * 16 + l;
  }
  return i;
}
function An(e, t) {
  const n = $(e, t);
  return ut(n);
}
function ft(e, t = {}) {
  const n = En.encode(e);
  return typeof t.size == "number" ? (X(n, { size: t.size }), x(n, { dir: "right", size: t.size })) : n;
}
function $e(e) {
  if (!Number.isSafeInteger(e) || e < 0)
    throw new Error(`positive integer expected, not ${e}`);
}
function _n(e) {
  return e instanceof Uint8Array || e != null && typeof e == "object" && e.constructor.name === "Uint8Array";
}
function ve(e, ...t) {
  if (!_n(e))
    throw new Error("Uint8Array expected");
  if (t.length > 0 && !t.includes(e.length))
    throw new Error(`Uint8Array expected of length ${t}, not of length=${e.length}`);
}
function Re(e, t = !0) {
  if (e.destroyed)
    throw new Error("Hash instance has been destroyed");
  if (t && e.finished)
    throw new Error("Hash#digest() has already been called");
}
function Tn(e, t) {
  ve(e);
  const n = t.outputLen;
  if (e.length < n)
    throw new Error(`digestInto() expects output buffer of length at least ${n}`);
}
const te = /* @__PURE__ */ BigInt(2 ** 32 - 1), ke = /* @__PURE__ */ BigInt(32);
function Sn(e, t = !1) {
  return t ? { h: Number(e & te), l: Number(e >> ke & te) } : { h: Number(e >> ke & te) | 0, l: Number(e & te) | 0 };
}
function In(e, t = !1) {
  let n = new Uint32Array(e.length), s = new Uint32Array(e.length);
  for (let r = 0; r < e.length; r++) {
    const { h: i, l: a } = Sn(e[r], t);
    [n[r], s[r]] = [i, a];
  }
  return [n, s];
}
const vn = (e, t, n) => e << n | t >>> 32 - n, On = (e, t, n) => t << n | e >>> 32 - n, Pn = (e, t, n) => t << n - 32 | e >>> 64 - n, Cn = (e, t, n) => e << n - 32 | t >>> 64 - n;
/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */
const Bn = (e) => new Uint32Array(e.buffer, e.byteOffset, Math.floor(e.byteLength / 4)), xe = new Uint8Array(new Uint32Array([287454020]).buffer)[0] === 68, Nn = (e) => e << 24 & 4278190080 | e << 8 & 16711680 | e >>> 8 & 65280 | e >>> 24 & 255;
function He(e) {
  for (let t = 0; t < e.length; t++)
    e[t] = Nn(e[t]);
}
function Dn(e) {
  if (typeof e != "string")
    throw new Error(`utf8ToBytes expected string, got ${typeof e}`);
  return new Uint8Array(new TextEncoder().encode(e));
}
function dt(e) {
  return typeof e == "string" && (e = Dn(e)), ve(e), e;
}
class Ln {
  // Safe version that clones internal state
  clone() {
    return this._cloneInto();
  }
}
function Mn(e) {
  const t = (s) => e().update(dt(s)).digest(), n = e();
  return t.outputLen = n.outputLen, t.blockLen = n.blockLen, t.create = () => e(), t;
}
const lt = [], ht = [], gt = [], $n = /* @__PURE__ */ BigInt(0), F = /* @__PURE__ */ BigInt(1), Rn = /* @__PURE__ */ BigInt(2), kn = /* @__PURE__ */ BigInt(7), xn = /* @__PURE__ */ BigInt(256), Hn = /* @__PURE__ */ BigInt(113);
for (let e = 0, t = F, n = 1, s = 0; e < 24; e++) {
  [n, s] = [s, (2 * n + 3 * s) % 5], lt.push(2 * (5 * s + n)), ht.push((e + 1) * (e + 2) / 2 % 64);
  let r = $n;
  for (let i = 0; i < 7; i++)
    t = (t << F ^ (t >> kn) * Hn) % xn, t & Rn && (r ^= F << (F << /* @__PURE__ */ BigInt(i)) - F);
  gt.push(r);
}
const [Un, jn] = /* @__PURE__ */ In(gt, !0), Ue = (e, t, n) => n > 32 ? Pn(e, t, n) : vn(e, t, n), je = (e, t, n) => n > 32 ? Cn(e, t, n) : On(e, t, n);
function zn(e, t = 24) {
  const n = new Uint32Array(10);
  for (let s = 24 - t; s < 24; s++) {
    for (let a = 0; a < 10; a++)
      n[a] = e[a] ^ e[a + 10] ^ e[a + 20] ^ e[a + 30] ^ e[a + 40];
    for (let a = 0; a < 10; a += 2) {
      const c = (a + 8) % 10, d = (a + 2) % 10, l = n[d], h = n[d + 1], g = Ue(l, h, 1) ^ n[c], I = je(l, h, 1) ^ n[c + 1];
      for (let T = 0; T < 50; T += 10)
        e[a + T] ^= g, e[a + T + 1] ^= I;
    }
    let r = e[2], i = e[3];
    for (let a = 0; a < 24; a++) {
      const c = ht[a], d = Ue(r, i, c), l = je(r, i, c), h = lt[a];
      r = e[h], i = e[h + 1], e[h] = d, e[h + 1] = l;
    }
    for (let a = 0; a < 50; a += 10) {
      for (let c = 0; c < 10; c++)
        n[c] = e[a + c];
      for (let c = 0; c < 10; c++)
        e[a + c] ^= ~n[(c + 2) % 10] & n[(c + 4) % 10];
    }
    e[0] ^= Un[s], e[1] ^= jn[s];
  }
  n.fill(0);
}
class Oe extends Ln {
  // NOTE: we accept arguments in bytes instead of bits here.
  constructor(t, n, s, r = !1, i = 24) {
    if (super(), this.blockLen = t, this.suffix = n, this.outputLen = s, this.enableXOF = r, this.rounds = i, this.pos = 0, this.posOut = 0, this.finished = !1, this.destroyed = !1, $e(s), 0 >= this.blockLen || this.blockLen >= 200)
      throw new Error("Sha3 supports only keccak-f1600 function");
    this.state = new Uint8Array(200), this.state32 = Bn(this.state);
  }
  keccak() {
    xe || He(this.state32), zn(this.state32, this.rounds), xe || He(this.state32), this.posOut = 0, this.pos = 0;
  }
  update(t) {
    Re(this);
    const { blockLen: n, state: s } = this;
    t = dt(t);
    const r = t.length;
    for (let i = 0; i < r; ) {
      const a = Math.min(n - this.pos, r - i);
      for (let c = 0; c < a; c++)
        s[this.pos++] ^= t[i++];
      this.pos === n && this.keccak();
    }
    return this;
  }
  finish() {
    if (this.finished)
      return;
    this.finished = !0;
    const { state: t, suffix: n, pos: s, blockLen: r } = this;
    t[s] ^= n, n & 128 && s === r - 1 && this.keccak(), t[r - 1] ^= 128, this.keccak();
  }
  writeInto(t) {
    Re(this, !1), ve(t), this.finish();
    const n = this.state, { blockLen: s } = this;
    for (let r = 0, i = t.length; r < i; ) {
      this.posOut >= s && this.keccak();
      const a = Math.min(s - this.posOut, i - r);
      t.set(n.subarray(this.posOut, this.posOut + a), r), this.posOut += a, r += a;
    }
    return t;
  }
  xofInto(t) {
    if (!this.enableXOF)
      throw new Error("XOF is not possible for this instance");
    return this.writeInto(t);
  }
  xof(t) {
    return $e(t), this.xofInto(new Uint8Array(t));
  }
  digestInto(t) {
    if (Tn(t, this), this.finished)
      throw new Error("digest() was already called");
    return this.writeInto(t), this.destroy(), t;
  }
  digest() {
    return this.digestInto(new Uint8Array(this.outputLen));
  }
  destroy() {
    this.destroyed = !0, this.state.fill(0);
  }
  _cloneInto(t) {
    const { blockLen: n, suffix: s, outputLen: r, rounds: i, enableXOF: a } = this;
    return t || (t = new Oe(n, s, r, a, i)), t.state32.set(this.state32), t.pos = this.pos, t.posOut = this.posOut, t.finished = this.finished, t.rounds = i, t.suffix = s, t.outputLen = r, t.enableXOF = a, t.destroyed = this.destroyed, t;
  }
}
const Fn = (e, t, n) => Mn(() => new Oe(t, e, n)), Gn = /* @__PURE__ */ Fn(1, 136, 256 / 8);
function O(e, t) {
  const n = t || "hex", s = Gn(K(e, { strict: !1 }) ? ct(e) : e);
  return n === "bytes" ? s : Se(s);
}
const qn = (e) => O(ct(e));
function Vn(e) {
  return qn(e);
}
function Wn(e) {
  let t = !0, n = "", s = 0, r = "", i = !1;
  for (let a = 0; a < e.length; a++) {
    const c = e[a];
    if (["(", ")", ","].includes(c) && (t = !0), c === "(" && s++, c === ")" && s--, !!t) {
      if (s === 0) {
        if (c === " " && ["event", "function", ""].includes(r))
          r = "";
        else if (r += c, c === ")") {
          i = !0;
          break;
        }
        continue;
      }
      if (c === " ") {
        e[a - 1] !== "," && n !== "," && n !== ",(" && (n = "", t = !1);
        continue;
      }
      r += c, n += c;
    }
  }
  if (!i)
    throw new E("Unable to normalize signature.");
  return r;
}
const Kn = (e) => {
  const t = typeof e == "string" ? e : sn(e);
  return Wn(t);
};
function pt(e) {
  return Vn(Kn(e));
}
const Xn = pt;
class yt extends E {
  constructor({ address: t }) {
    super(`Address "${t}" is invalid.`, {
      metaMessages: [
        "- Address must be a hex value of 20 bytes (40 hex characters).",
        "- Address must match its checksum counterpart."
      ],
      name: "InvalidAddressError"
    });
  }
}
class mt extends Map {
  constructor(t) {
    super(), Object.defineProperty(this, "maxSize", {
      enumerable: !0,
      configurable: !0,
      writable: !0,
      value: void 0
    }), this.maxSize = t;
  }
  set(t, n) {
    return super.set(t, n), this.maxSize && this.size > this.maxSize && this.delete(this.keys().next().value), this;
  }
}
const ye = /* @__PURE__ */ new mt(8192);
function Qn(e, t) {
  if (ye.has(`${e}.${t}`))
    return ye.get(`${e}.${t}`);
  const n = e.substring(2).toLowerCase(), s = O(ft(n), "bytes"), r = n.split("");
  for (let a = 0; a < 40; a += 2)
    s[a >> 1] >> 4 >= 8 && r[a] && (r[a] = r[a].toUpperCase()), (s[a >> 1] & 15) >= 8 && r[a + 1] && (r[a + 1] = r[a + 1].toUpperCase());
  const i = `0x${r.join("")}`;
  return ye.set(`${e}.${t}`, i), i;
}
const Jn = /^0x[a-fA-F0-9]{40}$/, me = /* @__PURE__ */ new mt(8192);
function V(e, t) {
  const { strict: n = !0 } = t ?? {}, s = `${e}.${n}`;
  if (me.has(s))
    return me.get(s);
  const r = Jn.test(e) ? e.toLowerCase() === e ? !0 : n ? Qn(e) === e : !0 : !1;
  return me.set(s, r), r;
}
function M(e) {
  return typeof e[0] == "string" ? bt(e) : Yn(e);
}
function Yn(e) {
  let t = 0;
  for (const r of e)
    t += r.length;
  const n = new Uint8Array(t);
  let s = 0;
  for (const r of e)
    n.set(r, s), s += r.length;
  return n;
}
function bt(e) {
  return `0x${e.reduce((t, n) => t + n.replace("0x", ""), "")}`;
}
function Et(e, t, n, { strict: s } = {}) {
  return K(e, { strict: !1 }) ? es(e, t, n, {
    strict: s
  }) : Zn(e, t, n, {
    strict: s
  });
}
function wt(e, t) {
  if (typeof t == "number" && t > 0 && t > _(e) - 1)
    throw new it({
      offset: t,
      position: "start",
      size: _(e)
    });
}
function At(e, t, n) {
  if (typeof t == "number" && typeof n == "number" && _(e) !== n - t)
    throw new it({
      offset: n,
      position: "end",
      size: _(e)
    });
}
function Zn(e, t, n, { strict: s } = {}) {
  wt(e, t);
  const r = e.slice(t, n);
  return s && At(r, t, n), r;
}
function es(e, t, n, { strict: s } = {}) {
  wt(e, t);
  const r = `0x${e.replace("0x", "").slice((t ?? 0) * 2, (n ?? e.length) * 2)}`;
  return s && At(r, t, n), r;
}
function Pe(e, t) {
  if (e.length !== t.length)
    throw new cn({
      expectedLength: e.length,
      givenLength: t.length
    });
  const n = ts({
    params: e,
    values: t
  }), s = Be(n);
  return s.length === 0 ? "0x" : s;
}
function ts({ params: e, values: t }) {
  const n = [];
  for (let s = 0; s < e.length; s++)
    n.push(Ce({ param: e[s], value: t[s] }));
  return n;
}
function Ce({ param: e, value: t }) {
  const n = us(e.type);
  if (n) {
    const [s, r] = n;
    return ss(t, { length: s, param: { ...e, type: r } });
  }
  if (e.type === "tuple")
    return cs(t, {
      param: e
    });
  if (e.type === "address")
    return ns(t);
  if (e.type === "bool")
    return is(t);
  if (e.type.startsWith("uint") || e.type.startsWith("int")) {
    const s = e.type.startsWith("int");
    return os(t, { signed: s });
  }
  if (e.type.startsWith("bytes"))
    return rs(t, { param: e });
  if (e.type === "string")
    return as(t);
  throw new dn(e.type, {
    docsPath: "/docs/contract/encodeAbiParameters"
  });
}
function Be(e) {
  let t = 0;
  for (let i = 0; i < e.length; i++) {
    const { dynamic: a, encoded: c } = e[i];
    a ? t += 32 : t += _(c);
  }
  const n = [], s = [];
  let r = 0;
  for (let i = 0; i < e.length; i++) {
    const { dynamic: a, encoded: c } = e[i];
    a ? (n.push($(t + r, { size: 32 })), s.push(c), r += _(c)) : n.push(c);
  }
  return M([...n, ...s]);
}
function ns(e) {
  if (!V(e))
    throw new yt({ address: e });
  return { dynamic: !1, encoded: L(e.toLowerCase()) };
}
function ss(e, { length: t, param: n }) {
  const s = t === null;
  if (!Array.isArray(e))
    throw new ln(e);
  if (!s && e.length !== t)
    throw new on({
      expectedLength: t,
      givenLength: e.length,
      type: `${n.type}[${t}]`
    });
  let r = !1;
  const i = [];
  for (let a = 0; a < e.length; a++) {
    const c = Ce({ param: n, value: e[a] });
    c.dynamic && (r = !0), i.push(c);
  }
  if (s || r) {
    const a = Be(i);
    if (s) {
      const c = $(i.length, { size: 32 });
      return {
        dynamic: !0,
        encoded: i.length > 0 ? M([c, a]) : c
      };
    }
    if (r)
      return { dynamic: !0, encoded: a };
  }
  return {
    dynamic: !1,
    encoded: M(i.map(({ encoded: a }) => a))
  };
}
function rs(e, { param: t }) {
  const [, n] = t.type.split("bytes"), s = _(e);
  if (!n) {
    let r = e;
    return s % 32 !== 0 && (r = L(r, {
      dir: "right",
      size: Math.ceil((e.length - 2) / 2 / 32) * 32
    })), {
      dynamic: !0,
      encoded: M([L($(s, { size: 32 })), r])
    };
  }
  if (s !== Number.parseInt(n))
    throw new an({
      expectedSize: Number.parseInt(n),
      value: e
    });
  return { dynamic: !1, encoded: L(e, { dir: "right" }) };
}
function is(e) {
  if (typeof e != "boolean")
    throw new E(`Invalid boolean value: "${e}" (type: ${typeof e}). Expected: \`true\` or \`false\`.`);
  return { dynamic: !1, encoded: L(at(e)) };
}
function os(e, { signed: t }) {
  return {
    dynamic: !1,
    encoded: $(e, {
      size: 32,
      signed: t
    })
  };
}
function as(e) {
  const t = se(e), n = Math.ceil(_(t) / 32), s = [];
  for (let r = 0; r < n; r++)
    s.push(L(Et(t, r * 32, (r + 1) * 32), {
      dir: "right"
    }));
  return {
    dynamic: !0,
    encoded: M([
      L($(_(t), { size: 32 })),
      ...s
    ])
  };
}
function cs(e, { param: t }) {
  let n = !1;
  const s = [];
  for (let r = 0; r < t.components.length; r++) {
    const i = t.components[r], a = Array.isArray(e) ? r : i.name, c = Ce({
      param: i,
      value: e[a]
    });
    s.push(c), c.dynamic && (n = !0);
  }
  return {
    dynamic: n,
    encoded: n ? Be(s) : M(s.map(({ encoded: r }) => r))
  };
}
function us(e) {
  const t = e.match(/^(.*)\[(\d+)?\]$/);
  return t ? (
    // Return `null` if the array is dynamic.
    [t[2] ? Number(t[2]) : null, t[1]]
  ) : void 0;
}
const _t = (e) => Et(pt(e), 0, 4);
function fs(e) {
  const { abi: t, args: n = [], name: s } = e, r = K(s, { strict: !1 }), i = t.filter((c) => r ? c.type === "function" ? _t(c) === s : c.type === "event" ? Xn(c) === s : !1 : "name" in c && c.name === s);
  if (i.length === 0)
    return;
  if (i.length === 1)
    return i[0];
  let a;
  for (const c of i) {
    if (!("inputs" in c))
      continue;
    if (!n || n.length === 0) {
      if (!c.inputs || c.inputs.length === 0)
        return c;
      continue;
    }
    if (!c.inputs || c.inputs.length === 0 || c.inputs.length !== n.length)
      continue;
    if (n.every((l, h) => {
      const g = "inputs" in c && c.inputs[h];
      return g ? _e(l, g) : !1;
    })) {
      if (a && "inputs" in a && a.inputs) {
        const l = Tt(c.inputs, a.inputs, n);
        if (l)
          throw new un({
            abiItem: c,
            type: l[0]
          }, {
            abiItem: a,
            type: l[1]
          });
      }
      a = c;
    }
  }
  return a || i[0];
}
function _e(e, t) {
  const n = typeof e, s = t.type;
  switch (s) {
    case "address":
      return V(e, { strict: !1 });
    case "bool":
      return n === "boolean";
    case "function":
      return n === "string";
    case "string":
      return n === "string";
    default:
      return s === "tuple" && "components" in t ? Object.values(t.components).every((r, i) => _e(Object.values(e)[i], r)) : /^u?int(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/.test(s) ? n === "number" || n === "bigint" : /^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/.test(s) ? n === "string" || e instanceof Uint8Array : /[a-z]+[1-9]{0,3}(\[[0-9]{0,}\])+$/.test(s) ? Array.isArray(e) && e.every((r) => _e(r, {
        ...t,
        // Pop off `[]` or `[M]` from end of type
        type: s.replace(/(\[[0-9]{0,}\])$/, "")
      })) : !1;
  }
}
function Tt(e, t, n) {
  for (const s in e) {
    const r = e[s], i = t[s];
    if (r.type === "tuple" && i.type === "tuple" && "components" in r && "components" in i)
      return Tt(r.components, i.components, n[s]);
    const a = [r.type, i.type];
    if (a.includes("address") && a.includes("bytes20") ? !0 : a.includes("address") && a.includes("string") ? V(n[s], { strict: !1 }) : a.includes("address") && a.includes("bytes") ? V(n[s], { strict: !1 }) : !1)
      return a;
  }
}
const ze = "/docs/contract/encodeFunctionData";
function ds(e) {
  const { abi: t, args: n, functionName: s } = e;
  let r = t[0];
  if (s) {
    const i = fs({
      abi: t,
      args: n,
      name: s
    });
    if (!i)
      throw new Le(s, { docsPath: ze });
    r = i;
  }
  if (r.type !== "function")
    throw new Le(void 0, { docsPath: ze });
  return {
    abi: [r],
    functionName: _t(Ae(r))
  };
}
function Fe(e) {
  const { args: t } = e, { abi: n, functionName: s } = (() => {
    var c;
    return e.abi.length === 1 && ((c = e.functionName) != null && c.startsWith("0x")) ? e : ds(e);
  })(), r = n[0], i = s, a = "inputs" in r && r.inputs ? Pe(r.inputs, t ?? []) : void 0;
  return bt([i, a ?? "0x"]);
}
const ls = /^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/, hs = /^(u?int)(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/;
function gs(e) {
  const { domain: t = {}, message: n, primaryType: s } = e, r = {
    EIP712Domain: Es({ domain: t }),
    ...e.types
  };
  bs({
    domain: t,
    message: n,
    primaryType: s,
    types: r
  });
  const i = ["0x1901"];
  return t && i.push(ps({
    domain: t,
    types: r
  })), s !== "EIP712Domain" && i.push(St({
    data: n,
    primaryType: s,
    types: r
  })), O(M(i));
}
function ps({ domain: e, types: t }) {
  return St({
    data: e,
    primaryType: "EIP712Domain",
    types: t
  });
}
function St({ data: e, primaryType: t, types: n }) {
  const s = It({
    data: e,
    primaryType: t,
    types: n
  });
  return O(s);
}
function It({ data: e, primaryType: t, types: n }) {
  const s = [{ type: "bytes32" }], r = [ys({ primaryType: t, types: n })];
  for (const i of n[t]) {
    const [a, c] = Ot({
      types: n,
      name: i.name,
      type: i.type,
      value: e[i.name]
    });
    s.push(a), r.push(c);
  }
  return Pe(s, r);
}
function ys({ primaryType: e, types: t }) {
  const n = Se(ms({ primaryType: e, types: t }));
  return O(n);
}
function ms({ primaryType: e, types: t }) {
  let n = "";
  const s = vt({ primaryType: e, types: t });
  s.delete(e);
  const r = [e, ...Array.from(s).sort()];
  for (const i of r)
    n += `${i}(${t[i].map(({ name: a, type: c }) => `${c} ${a}`).join(",")})`;
  return n;
}
function vt({ primaryType: e, types: t }, n = /* @__PURE__ */ new Set()) {
  const s = e.match(/^\w*/u), r = s == null ? void 0 : s[0];
  if (n.has(r) || t[r] === void 0)
    return n;
  n.add(r);
  for (const i of t[r])
    vt({ primaryType: i.type, types: t }, n);
  return n;
}
function Ot({ types: e, name: t, type: n, value: s }) {
  if (e[n] !== void 0)
    return [
      { type: "bytes32" },
      O(It({ data: s, primaryType: n, types: e }))
    ];
  if (n === "bytes")
    return s = `0x${(s.length % 2 ? "0" : "") + s.slice(2)}`, [{ type: "bytes32" }, O(s)];
  if (n === "string")
    return [{ type: "bytes32" }, O(Se(s))];
  if (n.lastIndexOf("]") === n.length - 1) {
    const r = n.slice(0, n.lastIndexOf("[")), i = s.map((a) => Ot({
      name: t,
      type: r,
      types: e,
      value: a
    }));
    return [
      { type: "bytes32" },
      O(Pe(i.map(([a]) => a), i.map(([, a]) => a)))
    ];
  }
  return [{ type: n }, s];
}
function bs(e) {
  const { domain: t, message: n, primaryType: s, types: r } = e, i = (a, c) => {
    for (const d of a) {
      const { name: l, type: h } = d, g = c[l], I = h.match(hs);
      if (I && (typeof g == "number" || typeof g == "bigint")) {
        const [R, v, H] = I;
        $(g, {
          signed: v === "int",
          size: Number.parseInt(H) / 8
        });
      }
      if (h === "address" && typeof g == "string" && !V(g))
        throw new yt({ address: g });
      const T = h.match(ls);
      if (T) {
        const [R, v] = T;
        if (v && _(g) !== Number.parseInt(v))
          throw new fn({
            expectedSize: Number.parseInt(v),
            givenSize: _(g)
          });
      }
      const m = r[h];
      m && i(m, g);
    }
  };
  r.EIP712Domain && t && i(r.EIP712Domain, t), s !== "EIP712Domain" && i(r[s], n);
}
function Es({ domain: e }) {
  return [
    typeof (e == null ? void 0 : e.name) == "string" && { name: "name", type: "string" },
    (e == null ? void 0 : e.version) && { name: "version", type: "string" },
    typeof (e == null ? void 0 : e.chainId) == "number" && {
      name: "chainId",
      type: "uint256"
    },
    (e == null ? void 0 : e.verifyingContract) && {
      name: "verifyingContract",
      type: "address"
    },
    (e == null ? void 0 : e.salt) && { name: "salt", type: "bytes32" }
  ].filter(Boolean);
}
const ws = `Ethereum Signed Message:
`;
function As(e) {
  const t = typeof e == "string" ? se(e) : typeof e.raw == "string" ? e.raw : Ie(e.raw), n = se(`${ws}${_(t)}`);
  return M([n, t]);
}
function _s(e, t) {
  return O(As(e), t);
}
const Ts = "0x1626ba7e", Ss = "0x20c13b0b", Te = 4001;
class W extends Error {
  constructor(t, n, s) {
    super(t), this.code = n, this.data = s, Object.setPrototypeOf(this, W.prototype);
  }
}
class Pt {
  constructor(t) {
    this.communicator = t;
  }
  async getPermissions() {
    return (await this.communicator.send(w.wallet_getPermissions, void 0)).data;
  }
  async requestPermissions(t) {
    if (!this.isPermissionRequestValid(t))
      throw new W("Permissions request is invalid", Te);
    try {
      return (await this.communicator.send(w.wallet_requestPermissions, t)).data;
    } catch {
      throw new W("Permissions rejected", Te);
    }
  }
  isPermissionRequestValid(t) {
    return t.every((n) => typeof n == "object" ? Object.keys(n).every((s) => !!Object.values(be).includes(s)) : !1);
  }
}
const Ge = (e, t) => t.some((n) => n.parentCapability === e), Is = () => (e, t, n) => {
  const s = n.value;
  return n.value = async function() {
    const r = new Pt(this.communicator);
    let i = await r.getPermissions();
    if (Ge(t, i) || (i = await r.requestPermissions([{ [t]: {} }])), !Ge(t, i))
      throw new W("Permissions rejected", Te);
    return s.apply(this);
  }, n;
};
var vs = function(e, t, n, s) {
  var r = arguments.length, i = r < 3 ? t : s === null ? s = Object.getOwnPropertyDescriptor(t, n) : s, a;
  if (typeof Reflect == "object" && typeof Reflect.decorate == "function") i = Reflect.decorate(e, t, n, s);
  else for (var c = e.length - 1; c >= 0; c--) (a = e[c]) && (i = (r < 3 ? a(i) : r > 3 ? a(t, n, i) : a(t, n)) || i);
  return r > 3 && i && Object.defineProperty(t, n, i), i;
};
class Ct {
  constructor(t) {
    this.communicator = t;
  }
  async getChainInfo() {
    return (await this.communicator.send(w.getChainInfo, void 0)).data;
  }
  async getInfo() {
    return (await this.communicator.send(w.getSafeInfo, void 0)).data;
  }
  // There is a possibility that this method will change because we may add pagination to the endpoint
  async experimental_getBalances({ currency: t = "usd" } = {}) {
    return (await this.communicator.send(w.getSafeBalances, {
      currency: t
    })).data;
  }
  async check1271Signature(t, n = "0x") {
    const s = await this.getInfo(), r = Fe({
      abi: [
        {
          constant: !1,
          inputs: [
            {
              name: "_dataHash",
              type: "bytes32"
            },
            {
              name: "_signature",
              type: "bytes"
            }
          ],
          name: "isValidSignature",
          outputs: [
            {
              name: "",
              type: "bytes4"
            }
          ],
          payable: !1,
          stateMutability: "nonpayable",
          type: "function"
        }
      ],
      functionName: "isValidSignature",
      args: [t, n]
    }), i = {
      call: A.eth_call,
      params: [
        {
          to: s.safeAddress,
          data: r
        },
        "latest"
      ]
    };
    try {
      return (await this.communicator.send(w.rpcCall, i)).data.slice(0, 10).toLowerCase() === Ts;
    } catch {
      return !1;
    }
  }
  async check1271SignatureBytes(t, n = "0x") {
    const s = await this.getInfo(), r = Fe({
      abi: [
        {
          constant: !1,
          inputs: [
            {
              name: "_data",
              type: "bytes"
            },
            {
              name: "_signature",
              type: "bytes"
            }
          ],
          name: "isValidSignature",
          outputs: [
            {
              name: "",
              type: "bytes4"
            }
          ],
          payable: !1,
          stateMutability: "nonpayable",
          type: "function"
        }
      ],
      functionName: "isValidSignature",
      args: [t, n]
    }), i = {
      call: A.eth_call,
      params: [
        {
          to: s.safeAddress,
          data: r
        },
        "latest"
      ]
    };
    try {
      return (await this.communicator.send(w.rpcCall, i)).data.slice(0, 10).toLowerCase() === Ss;
    } catch {
      return !1;
    }
  }
  calculateMessageHash(t) {
    return _s(t);
  }
  calculateTypedMessageHash(t) {
    const n = typeof t.domain.chainId == "object" ? t.domain.chainId.toNumber() : Number(t.domain.chainId);
    let s = t.primaryType;
    if (!s) {
      const r = Object.values(t.types), i = Object.keys(t.types).filter((a) => r.every((c) => c.every(({ type: d }) => d.replace("[", "").replace("]", "") !== a)));
      if (i.length === 0 || i.length > 1)
        throw new Error("Please specify primaryType");
      s = i[0];
    }
    return gs({
      message: t.message,
      domain: {
        ...t.domain,
        chainId: n,
        verifyingContract: t.domain.verifyingContract,
        salt: t.domain.salt
      },
      types: t.types,
      primaryType: s
    });
  }
  async getOffChainSignature(t) {
    return (await this.communicator.send(w.getOffChainSignature, t)).data;
  }
  async isMessageSigned(t, n = "0x") {
    let s;
    if (typeof t == "string" && (s = async () => {
      const r = this.calculateMessageHash(t);
      return await this.isMessageHashSigned(r, n);
    }), qe(t) && (s = async () => {
      const r = this.calculateTypedMessageHash(t);
      return await this.isMessageHashSigned(r, n);
    }), s)
      return await s();
    throw new Error("Invalid message type");
  }
  async isMessageHashSigned(t, n = "0x") {
    const s = [this.check1271Signature.bind(this), this.check1271SignatureBytes.bind(this)];
    for (const r of s)
      if (await r(t, n))
        return !0;
    return !1;
  }
  async getEnvironmentInfo() {
    return (await this.communicator.send(w.getEnvironmentInfo, void 0)).data;
  }
  async requestAddressBook() {
    return (await this.communicator.send(w.requestAddressBook, void 0)).data;
  }
}
vs([
  Is()
], Ct.prototype, "requestAddressBook", null);
class Os {
  constructor(t = {}) {
    const { allowedDomains: n = null, debug: s = !1 } = t;
    this.communicator = new zt(n, s), this.eth = new tn(this.communicator), this.txs = new en(this.communicator), this.safe = new Ct(this.communicator), this.wallet = new Pt(this.communicator);
  }
}
var Bt = {}, oe = {}, ae = {};
Object.defineProperty(ae, "__esModule", { value: !0 });
ae.getLowerCase = void 0;
function Ps(e) {
  return e && e.toLowerCase();
}
ae.getLowerCase = Ps;
Object.defineProperty(oe, "__esModule", { value: !0 });
oe.SafeAppProvider = void 0;
const Cs = Nt, ne = ae;
class Bs extends Cs.EventEmitter {
  constructor(t, n) {
    super(), this.submittedTxs = /* @__PURE__ */ new Map(), this.safe = t, this.sdk = n;
  }
  async connect() {
    this.emit("connect", { chainId: this.chainId });
  }
  async disconnect() {
  }
  get chainId() {
    return this.safe.chainId;
  }
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  async request(t) {
    const { method: n, params: s = [] } = t;
    switch (n) {
      case "eth_accounts":
        return [this.safe.safeAddress];
      case "net_version":
      case "eth_chainId":
        return `0x${this.chainId.toString(16)}`;
      case "personal_sign": {
        const [d, l] = s;
        if (this.safe.safeAddress.toLowerCase() !== l.toLowerCase())
          throw new Error("The address or message hash is invalid");
        const h = await this.sdk.txs.signMessage(d);
        return ("signature" in h ? h.signature : void 0) || "0x";
      }
      case "eth_sign": {
        const [d, l] = s;
        if (this.safe.safeAddress.toLowerCase() !== d.toLowerCase() || !l.startsWith("0x"))
          throw new Error("The address or message hash is invalid");
        const h = await this.sdk.txs.signMessage(l);
        return ("signature" in h ? h.signature : void 0) || "0x";
      }
      case "eth_signTypedData":
      case "eth_signTypedData_v4": {
        const [d, l] = s, h = typeof l == "string" ? JSON.parse(l) : l;
        if (this.safe.safeAddress.toLowerCase() !== d.toLowerCase())
          throw new Error("The address is invalid");
        const g = await this.sdk.txs.signTypedMessage(h);
        return ("signature" in g ? g.signature : void 0) || "0x";
      }
      case "eth_sendTransaction":
        const r = {
          ...s[0],
          value: s[0].value || "0",
          data: s[0].data || "0x"
        };
        typeof r.gas == "string" && r.gas.startsWith("0x") && (r.gas = parseInt(r.gas, 16));
        const i = await this.sdk.txs.send({
          txs: [r],
          params: { safeTxGas: r.gas }
        });
        return this.submittedTxs.set(i.safeTxHash, {
          from: this.safe.safeAddress,
          hash: i.safeTxHash,
          gas: 0,
          gasPrice: "0x00",
          nonce: 0,
          input: r.data,
          value: r.value,
          to: r.to,
          blockHash: null,
          blockNumber: null,
          transactionIndex: null
        }), i.safeTxHash;
      case "eth_blockNumber":
        return (await this.sdk.eth.getBlockByNumber(["latest"])).number;
      case "eth_getBalance":
        return this.sdk.eth.getBalance([(0, ne.getLowerCase)(s[0]), s[1]]);
      case "eth_getCode":
        return this.sdk.eth.getCode([(0, ne.getLowerCase)(s[0]), s[1]]);
      case "eth_getTransactionCount":
        return this.sdk.eth.getTransactionCount([(0, ne.getLowerCase)(s[0]), s[1]]);
      case "eth_getStorageAt":
        return this.sdk.eth.getStorageAt([(0, ne.getLowerCase)(s[0]), s[1], s[2]]);
      case "eth_getBlockByNumber":
        return this.sdk.eth.getBlockByNumber([s[0], s[1]]);
      case "eth_getBlockByHash":
        return this.sdk.eth.getBlockByHash([s[0], s[1]]);
      case "eth_getTransactionByHash":
        let c = s[0];
        try {
          c = (await this.sdk.txs.getBySafeTxHash(c)).txHash || c;
        } catch {
        }
        return this.submittedTxs.has(c) ? this.submittedTxs.get(c) : this.sdk.eth.getTransactionByHash([c]).then((d) => (d && (d.hash = s[0]), d));
      case "eth_getTransactionReceipt": {
        let d = s[0];
        try {
          d = (await this.sdk.txs.getBySafeTxHash(d)).txHash || d;
        } catch {
        }
        return this.sdk.eth.getTransactionReceipt([d]).then((l) => (l && (l.transactionHash = s[0]), l));
      }
      case "eth_estimateGas":
        return this.sdk.eth.getEstimateGas(s[0]);
      case "eth_call":
        return this.sdk.eth.call([s[0], s[1]]);
      case "eth_getLogs":
        return this.sdk.eth.getPastLogs([s[0]]);
      case "eth_gasPrice":
        return this.sdk.eth.getGasPrice();
      case "wallet_getPermissions":
        return this.sdk.wallet.getPermissions();
      case "wallet_requestPermissions":
        return this.sdk.wallet.requestPermissions(s[0]);
      case "safe_setSettings":
        return this.sdk.eth.setSafeSettings([s[0]]);
      default:
        throw Error(`"${t.method}" not implemented`);
    }
  }
  // this method is needed for ethers v4
  // https://github.com/ethers-io/ethers.js/blob/427e16826eb15d52d25c4f01027f8db22b74b76c/src.ts/providers/web3-provider.ts#L41-L55
  send(t, n) {
    t || n("Undefined request"), this.request(t).then((s) => n(null, { jsonrpc: "2.0", id: t.id, result: s })).catch((s) => n(s, null));
  }
}
oe.SafeAppProvider = Bs;
(function(e) {
  Object.defineProperty(e, "__esModule", { value: !0 }), e.SafeAppProvider = void 0;
  var t = oe;
  Object.defineProperty(e, "SafeAppProvider", { enumerable: !0, get: function() {
    return t.SafeAppProvider;
  } });
})(Bt);
function Ns(e = {}) {
  const { shimDisconnect: t = !1 } = e;
  let n, s;
  return Dt((r) => {
    const i = new Lt([]), a = new Os();
    return {
      id: G.id,
      name: G.name,
      type: G.type,
      async connect() {
        var h;
        const c = await this.getProvider();
        if (!c) throw new Z();
        const d = await this.getAccounts(), l = await this.getChainId();
        return i.next(
          Mt.fromNullable(r.chains.find((g) => g.id === l)).map((g) => [g]).orDefault([])
        ), s || (s = this.onDisconnect.bind(this), c.on("disconnect", s)), t && await ((h = r.storage) == null ? void 0 : h.removeItem("safe.disconnected")), { accounts: d, chainId: l };
      },
      async disconnect() {
        var d;
        const c = await this.getProvider();
        if (!c) throw new Z();
        s && (c.removeListener("disconnect", s), s = void 0), t && await ((d = r.storage) == null ? void 0 : d.setItem("safe.disconnected", !0));
      },
      async getAccounts() {
        const c = await this.getProvider();
        if (!c) throw new Z();
        return (await c.request({ method: "eth_accounts" })).map(
          $t
        );
      },
      async getProvider() {
        if (Rt()) {
          if (!n) {
            const c = await kt(() => a.safe.getInfo(), {
              timeout: 10
            });
            if (!c) throw new Error("Could not load Safe information");
            n = new Bt.SafeAppProvider(c, a);
          }
          return n;
        }
      },
      async getChainId() {
        const c = await this.getProvider();
        if (!c) throw new Z();
        return Number(c.chainId);
      },
      async isAuthorized() {
        var c;
        try {
          return t && // If shim exists in storage, connector is disconnected
          await ((c = r.storage) == null ? void 0 : c.getItem("safe.disconnected")) ? !1 : !!(await this.getAccounts()).length;
        } catch {
          return !1;
        }
      },
      onAccountsChanged() {
      },
      onChainChanged() {
      },
      onDisconnect() {
        r.emitter.emit("disconnect");
      },
      $filteredChains: i,
      getTxStatus(c) {
        return Ne(() => a.txs.getBySafeTxHash(c)).mapLeft(
          () => new Error("Could not get transaction status")
        );
      },
      txStatus: Ve.TransactionStatus,
      sendTransactions(c) {
        return Ne(() => a.txs.send(c)).mapLeft(
          () => new Error("Could not send transactions")
        );
      }
    };
  });
}
const Ms = () => ({
  groupName: "Ledger Live",
  wallets: [
    () => ({
      id: G.id,
      name: G.name,
      iconUrl: "",
      iconBackground: "#fff",
      createConnector: () => Ns({ shimDisconnect: !0 })
    })
  ]
});
export {
  Ms as safeConnector
};
//# sourceMappingURL=safe-connector-D2aYGJo7.js.map
