import { b6 as M } from "./index-Bq4BDPab.js";
import { Q as _, t as O, I as P, E as C } from "./index.es-BcWoR40p.js";
const A = "wc", S = "ethereum_provider", T = `${A}@2:${S}:`, R = "https://rpc.walletconnect.com/v1/", v = ["eth_sendTransaction", "personal_sign"], $ = ["eth_accounts", "eth_requestAccounts", "eth_sendRawTransaction", "eth_sign", "eth_signTransaction", "eth_signTypedData", "eth_signTypedData_v3", "eth_signTypedData_v4", "eth_sendTransaction", "personal_sign", "wallet_switchEthereumChain", "wallet_addEthereumChain", "wallet_getPermissions", "wallet_requestPermissions", "wallet_registerOnboarding", "wallet_watchAsset", "wallet_scanQRCode", "wallet_sendCalls", "wallet_getCapabilities", "wallet_getCallsStatus", "wallet_showCallsStatus"], f = ["chainChanged", "accountsChanged"], j = ["chainChanged", "accountsChanged", "message", "disconnect", "connect"];
var q = Object.defineProperty, D = Object.defineProperties, N = Object.getOwnPropertyDescriptors, y = Object.getOwnPropertySymbols, Q = Object.prototype.hasOwnProperty, U = Object.prototype.propertyIsEnumerable, b = (a, s, e) => s in a ? q(a, s, { enumerable: !0, configurable: !0, writable: !0, value: e }) : a[s] = e, p = (a, s) => {
  for (var e in s || (s = {}))
    Q.call(s, e) && b(a, e, s[e]);
  if (y)
    for (var e of y(s))
      U.call(s, e) && b(a, e, s[e]);
  return a;
}, I = (a, s) => D(a, N(s));
function m(a) {
  return Number(a[0].split(":")[1]);
}
function g(a) {
  return `0x${a.toString(16)}`;
}
function L(a) {
  const { chains: s, optionalChains: e, methods: t, optionalMethods: i, events: n, optionalEvents: o, rpcMap: r } = a;
  if (!C(s))
    throw new Error("Invalid chains");
  const c = { chains: s, methods: t || v, events: n || f, rpcMap: p({}, s.length ? { [m(s)]: r[m(s)] } : {}) }, h = n == null ? void 0 : n.filter((d) => !f.includes(d)), l = t == null ? void 0 : t.filter((d) => !v.includes(d));
  if (!e && !o && !i && !(h != null && h.length) && !(l != null && l.length))
    return { required: s.length ? c : void 0 };
  const u = (h == null ? void 0 : h.length) && (l == null ? void 0 : l.length) || !e, w = { chains: [...new Set(u ? c.chains.concat(e || []) : e)], methods: [...new Set(c.methods.concat(i != null && i.length ? i : $))], events: [...new Set(c.events.concat(o != null && o.length ? o : j))], rpcMap: r };
  return { required: s.length ? c : void 0, optional: e.length ? w : void 0 };
}
class E {
  constructor() {
    this.events = new M.EventEmitter(), this.namespace = "eip155", this.accounts = [], this.chainId = 1, this.STORAGE_KEY = T, this.on = (s, e) => (this.events.on(s, e), this), this.once = (s, e) => (this.events.once(s, e), this), this.removeListener = (s, e) => (this.events.removeListener(s, e), this), this.off = (s, e) => (this.events.off(s, e), this), this.parseAccount = (s) => this.isCompatibleChainId(s) ? this.parseAccountId(s).address : s, this.signer = {}, this.rpc = {};
  }
  static async init(s) {
    const e = new E();
    return await e.initialize(s), e;
  }
  async request(s, e) {
    return await this.signer.request(s, this.formatChainId(this.chainId), e);
  }
  sendAsync(s, e, t) {
    this.signer.sendAsync(s, e, this.formatChainId(this.chainId), t);
  }
  get connected() {
    return this.signer.client ? this.signer.client.core.relayer.connected : !1;
  }
  get connecting() {
    return this.signer.client ? this.signer.client.core.relayer.connecting : !1;
  }
  async enable() {
    return this.session || await this.connect(), await this.request({ method: "eth_requestAccounts" });
  }
  async connect(s) {
    if (!this.signer.client)
      throw new Error("Provider not initialized. Call init() first");
    this.loadConnectOpts(s);
    const { required: e, optional: t } = L(this.rpc);
    try {
      const i = await new Promise(async (o, r) => {
        var c;
        this.rpc.showQrModal && ((c = this.modal) == null || c.subscribeModal((h) => {
          !h.open && !this.signer.session && (this.signer.abortPairingAttempt(), r(new Error("Connection request reset. Please try again.")));
        })), await this.signer.connect(I(p({ namespaces: p({}, e && { [this.namespace]: e }) }, t && { optionalNamespaces: { [this.namespace]: t } }), { pairingTopic: s == null ? void 0 : s.pairingTopic })).then((h) => {
          o(h);
        }).catch((h) => {
          r(new Error(h.message));
        });
      });
      if (!i)
        return;
      const n = _(i.namespaces, [this.namespace]);
      this.setChainIds(this.rpc.chains.length ? this.rpc.chains : n), this.setAccounts(n), this.events.emit("connect", { chainId: g(this.chainId) });
    } catch (i) {
      throw this.signer.logger.error(i), i;
    } finally {
      this.modal && this.modal.closeModal();
    }
  }
  async authenticate(s) {
    if (!this.signer.client)
      throw new Error("Provider not initialized. Call init() first");
    this.loadConnectOpts({ chains: s == null ? void 0 : s.chains });
    try {
      const e = await new Promise(async (i, n) => {
        var o;
        this.rpc.showQrModal && ((o = this.modal) == null || o.subscribeModal((r) => {
          !r.open && !this.signer.session && (this.signer.abortPairingAttempt(), n(new Error("Connection request reset. Please try again.")));
        })), await this.signer.authenticate(I(p({}, s), { chains: this.rpc.chains })).then((r) => {
          i(r);
        }).catch((r) => {
          n(new Error(r.message));
        });
      }), t = e.session;
      if (t) {
        const i = _(t.namespaces, [this.namespace]);
        this.setChainIds(this.rpc.chains.length ? this.rpc.chains : i), this.setAccounts(i), this.events.emit("connect", { chainId: g(this.chainId) });
      }
      return e;
    } catch (e) {
      throw this.signer.logger.error(e), e;
    } finally {
      this.modal && this.modal.closeModal();
    }
  }
  async disconnect() {
    this.session && await this.signer.disconnect(), this.reset();
  }
  get isWalletConnect() {
    return !0;
  }
  get session() {
    return this.signer.session;
  }
  registerEventListeners() {
    this.signer.on("session_event", (s) => {
      const { params: e } = s, { event: t } = e;
      t.name === "accountsChanged" ? (this.accounts = this.parseAccounts(t.data), this.events.emit("accountsChanged", this.accounts)) : t.name === "chainChanged" ? this.setChainId(this.formatChainId(t.data)) : this.events.emit(t.name, t.data), this.events.emit("session_event", s);
    }), this.signer.on("chainChanged", (s) => {
      const e = parseInt(s);
      this.chainId = e, this.events.emit("chainChanged", g(this.chainId)), this.persist();
    }), this.signer.on("session_update", (s) => {
      this.events.emit("session_update", s);
    }), this.signer.on("session_delete", (s) => {
      this.reset(), this.events.emit("session_delete", s), this.events.emit("disconnect", I(p({}, O("USER_DISCONNECTED")), { data: s.topic, name: "USER_DISCONNECTED" }));
    }), this.signer.on("display_uri", (s) => {
      var e, t;
      this.rpc.showQrModal && ((e = this.modal) == null || e.closeModal(), (t = this.modal) == null || t.openModal({ uri: s })), this.events.emit("display_uri", s);
    });
  }
  switchEthereumChain(s) {
    this.request({ method: "wallet_switchEthereumChain", params: [{ chainId: s.toString(16) }] });
  }
  isCompatibleChainId(s) {
    return typeof s == "string" ? s.startsWith(`${this.namespace}:`) : !1;
  }
  formatChainId(s) {
    return `${this.namespace}:${s}`;
  }
  parseChainId(s) {
    return Number(s.split(":")[1]);
  }
  setChainIds(s) {
    const e = s.filter((t) => this.isCompatibleChainId(t)).map((t) => this.parseChainId(t));
    e.length && (this.chainId = e[0], this.events.emit("chainChanged", g(this.chainId)), this.persist());
  }
  setChainId(s) {
    if (this.isCompatibleChainId(s)) {
      const e = this.parseChainId(s);
      this.chainId = e, this.switchEthereumChain(e);
    }
  }
  parseAccountId(s) {
    const [e, t, i] = s.split(":");
    return { chainId: `${e}:${t}`, address: i };
  }
  setAccounts(s) {
    this.accounts = s.filter((e) => this.parseChainId(this.parseAccountId(e).chainId) === this.chainId).map((e) => this.parseAccountId(e).address), this.events.emit("accountsChanged", this.accounts);
  }
  getRpcConfig(s) {
    var e, t;
    const i = (e = s == null ? void 0 : s.chains) != null ? e : [], n = (t = s == null ? void 0 : s.optionalChains) != null ? t : [], o = i.concat(n);
    if (!o.length)
      throw new Error("No chains specified in either `chains` or `optionalChains`");
    const r = i.length ? (s == null ? void 0 : s.methods) || v : [], c = i.length ? (s == null ? void 0 : s.events) || f : [], h = (s == null ? void 0 : s.optionalMethods) || [], l = (s == null ? void 0 : s.optionalEvents) || [], u = (s == null ? void 0 : s.rpcMap) || this.buildRpcMap(o, s.projectId), w = (s == null ? void 0 : s.qrModalOptions) || void 0;
    return { chains: i == null ? void 0 : i.map((d) => this.formatChainId(d)), optionalChains: n.map((d) => this.formatChainId(d)), methods: r, events: c, optionalMethods: h, optionalEvents: l, rpcMap: u, showQrModal: !!(s != null && s.showQrModal), qrModalOptions: w, projectId: s.projectId, metadata: s.metadata };
  }
  buildRpcMap(s, e) {
    const t = {};
    return s.forEach((i) => {
      t[i] = this.getRpcUrl(i, e);
    }), t;
  }
  async initialize(s) {
    if (this.rpc = this.getRpcConfig(s), this.chainId = this.rpc.chains.length ? m(this.rpc.chains) : m(this.rpc.optionalChains), this.signer = await P.init({ projectId: this.rpc.projectId, metadata: this.rpc.metadata, disableProviderPing: s.disableProviderPing, relayUrl: s.relayUrl, storageOptions: s.storageOptions, customStoragePrefix: s.customStoragePrefix, telemetryEnabled: s.telemetryEnabled }), this.registerEventListeners(), await this.loadPersistedSession(), this.rpc.showQrModal) {
      let e;
      try {
        const { WalletConnectModal: t } = await import("./index-DW4vCBHU.js").then((i) => i.i);
        e = t;
      } catch {
        throw new Error("To use QR modal, please install @walletconnect/modal package");
      }
      if (e)
        try {
          this.modal = new e(p({ projectId: this.rpc.projectId }, this.rpc.qrModalOptions));
        } catch (t) {
          throw this.signer.logger.error(t), new Error("Could not generate WalletConnectModal Instance");
        }
    }
  }
  loadConnectOpts(s) {
    if (!s)
      return;
    const { chains: e, optionalChains: t, rpcMap: i } = s;
    e && C(e) && (this.rpc.chains = e.map((n) => this.formatChainId(n)), e.forEach((n) => {
      this.rpc.rpcMap[n] = (i == null ? void 0 : i[n]) || this.getRpcUrl(n);
    })), t && C(t) && (this.rpc.optionalChains = [], this.rpc.optionalChains = t == null ? void 0 : t.map((n) => this.formatChainId(n)), t.forEach((n) => {
      this.rpc.rpcMap[n] = (i == null ? void 0 : i[n]) || this.getRpcUrl(n);
    }));
  }
  getRpcUrl(s, e) {
    var t;
    return ((t = this.rpc.rpcMap) == null ? void 0 : t[s]) || `${R}?chainId=eip155:${s}&projectId=${e || this.rpc.projectId}`;
  }
  async loadPersistedSession() {
    if (this.session)
      try {
        const s = await this.signer.client.core.storage.getItem(`${this.STORAGE_KEY}/chainId`), e = this.session.namespaces[`${this.namespace}:${s}`] ? this.session.namespaces[`${this.namespace}:${s}`] : this.session.namespaces[this.namespace];
        this.setChainIds(s ? [this.formatChainId(s)] : e == null ? void 0 : e.accounts), this.setAccounts(e == null ? void 0 : e.accounts);
      } catch (s) {
        this.signer.logger.error("Failed to load persisted session, clearing state..."), this.signer.logger.error(s), await this.disconnect().catch((e) => this.signer.logger.warn(e));
      }
  }
  reset() {
    this.chainId = 1, this.accounts = [];
  }
  persist() {
    this.session && this.signer.client.core.storage.setItem(`${this.STORAGE_KEY}/chainId`, this.chainId);
  }
  parseAccounts(s) {
    return typeof s == "string" || s instanceof String ? [this.parseAccount(s)] : s.map((e) => this.parseAccount(e));
  }
}
const W = E;
export {
  W as EthereumProvider,
  j as OPTIONAL_EVENTS,
  $ as OPTIONAL_METHODS,
  f as REQUIRED_EVENTS,
  v as REQUIRED_METHODS,
  E as default
};
