(() => {
  "use strict";
  var __webpack_modules__ = {
    7007(module) {
      var R = typeof Reflect === "object" ? Reflect : null;
      var ReflectApply = R && typeof R.apply === "function" ? R.apply : function ReflectApply(target, receiver, args) {
        return Function.prototype.apply.call(target, receiver, args);
      };
      var ReflectOwnKeys;
      if (R && typeof R.ownKeys === "function") {
        ReflectOwnKeys = R.ownKeys;
      } else if (Object.getOwnPropertySymbols) {
        ReflectOwnKeys = function ReflectOwnKeys(target) {
          return Object.getOwnPropertyNames(target).concat(Object.getOwnPropertySymbols(target));
        };
      } else {
        ReflectOwnKeys = function ReflectOwnKeys(target) {
          return Object.getOwnPropertyNames(target);
        };
      }
      function ProcessEmitWarning(warning) {
        if (console && console.warn) console.warn(warning);
      }
      var NumberIsNaN = Number.isNaN || function NumberIsNaN(value) {
        return value !== value;
      };
      function EventEmitter() {
        EventEmitter.init.call(this);
      }
      module.exports = EventEmitter;
      module.exports.once = once;
      EventEmitter.EventEmitter = EventEmitter;
      EventEmitter.prototype._events = undefined;
      EventEmitter.prototype._eventsCount = 0;
      EventEmitter.prototype._maxListeners = undefined;
      var defaultMaxListeners = 10;
      function checkListener(listener) {
        if (typeof listener !== "function") {
          throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener);
        }
      }
      Object.defineProperty(EventEmitter, "defaultMaxListeners", {
        enumerable: true,
        get: function() {
          return defaultMaxListeners;
        },
        set: function(arg) {
          if (typeof arg !== "number" || arg < 0 || NumberIsNaN(arg)) {
            throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received ' + arg + ".");
          }
          defaultMaxListeners = arg;
        }
      });
      EventEmitter.init = function() {
        if (this._events === undefined || this._events === Object.getPrototypeOf(this)._events) {
          this._events = Object.create(null);
          this._eventsCount = 0;
        }
        this._maxListeners = this._maxListeners || undefined;
      };
      EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) {
        if (typeof n !== "number" || n < 0 || NumberIsNaN(n)) {
          throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received ' + n + ".");
        }
        this._maxListeners = n;
        return this;
      };
      function _getMaxListeners(that) {
        if (that._maxListeners === undefined) return EventEmitter.defaultMaxListeners;
        return that._maxListeners;
      }
      EventEmitter.prototype.getMaxListeners = function getMaxListeners() {
        return _getMaxListeners(this);
      };
      EventEmitter.prototype.emit = function emit(type) {
        var args = [];
        for (var i = 1; i < arguments.length; i++) args.push(arguments[i]);
        var doError = type === "error";
        var events = this._events;
        if (events !== undefined) doError = doError && events.error === undefined; else if (!doError) return false;
        if (doError) {
          var er;
          if (args.length > 0) er = args[0];
          if (er instanceof Error) {
            throw er;
          }
          var err = new Error("Unhandled error." + (er ? " (" + er.message + ")" : ""));
          err.context = er;
          throw err;
        }
        var handler = events[type];
        if (handler === undefined) return false;
        if (typeof handler === "function") {
          ReflectApply(handler, this, args);
        } else {
          var len = handler.length;
          var listeners = arrayClone(handler, len);
          for (var i = 0; i < len; ++i) ReflectApply(listeners[i], this, args);
        }
        return true;
      };
      function _addListener(target, type, listener, prepend) {
        var m;
        var events;
        var existing;
        checkListener(listener);
        events = target._events;
        if (events === undefined) {
          events = target._events = Object.create(null);
          target._eventsCount = 0;
        } else {
          if (events.newListener !== undefined) {
            target.emit("newListener", type, listener.listener ? listener.listener : listener);
            events = target._events;
          }
          existing = events[type];
        }
        if (existing === undefined) {
          existing = events[type] = listener;
          ++target._eventsCount;
        } else {
          if (typeof existing === "function") {
            existing = events[type] = prepend ? [ listener, existing ] : [ existing, listener ];
          } else if (prepend) {
            existing.unshift(listener);
          } else {
            existing.push(listener);
          }
          m = _getMaxListeners(target);
          if (m > 0 && existing.length > m && !existing.warned) {
            existing.warned = true;
            var w = new Error("Possible EventEmitter memory leak detected. " + existing.length + " " + String(type) + " listeners " + "added. Use emitter.setMaxListeners() to " + "increase limit");
            w.name = "MaxListenersExceededWarning";
            w.emitter = target;
            w.type = type;
            w.count = existing.length;
            ProcessEmitWarning(w);
          }
        }
        return target;
      }
      EventEmitter.prototype.addListener = function addListener(type, listener) {
        return _addListener(this, type, listener, false);
      };
      EventEmitter.prototype.on = EventEmitter.prototype.addListener;
      EventEmitter.prototype.prependListener = function prependListener(type, listener) {
        return _addListener(this, type, listener, true);
      };
      function onceWrapper() {
        if (!this.fired) {
          this.target.removeListener(this.type, this.wrapFn);
          this.fired = true;
          if (arguments.length === 0) return this.listener.call(this.target);
          return this.listener.apply(this.target, arguments);
        }
      }
      function _onceWrap(target, type, listener) {
        var state = {
          fired: false,
          wrapFn: undefined,
          target,
          type,
          listener
        };
        var wrapped = onceWrapper.bind(state);
        wrapped.listener = listener;
        state.wrapFn = wrapped;
        return wrapped;
      }
      EventEmitter.prototype.once = function once(type, listener) {
        checkListener(listener);
        this.on(type, _onceWrap(this, type, listener));
        return this;
      };
      EventEmitter.prototype.prependOnceListener = function prependOnceListener(type, listener) {
        checkListener(listener);
        this.prependListener(type, _onceWrap(this, type, listener));
        return this;
      };
      EventEmitter.prototype.removeListener = function removeListener(type, listener) {
        var list, events, position, i, originalListener;
        checkListener(listener);
        events = this._events;
        if (events === undefined) return this;
        list = events[type];
        if (list === undefined) return this;
        if (list === listener || list.listener === listener) {
          if (--this._eventsCount === 0) this._events = Object.create(null); else {
            delete events[type];
            if (events.removeListener) this.emit("removeListener", type, list.listener || listener);
          }
        } else if (typeof list !== "function") {
          position = -1;
          for (i = list.length - 1; i >= 0; i--) {
            if (list[i] === listener || list[i].listener === listener) {
              originalListener = list[i].listener;
              position = i;
              break;
            }
          }
          if (position < 0) return this;
          if (position === 0) list.shift(); else {
            spliceOne(list, position);
          }
          if (list.length === 1) events[type] = list[0];
          if (events.removeListener !== undefined) this.emit("removeListener", type, originalListener || listener);
        }
        return this;
      };
      EventEmitter.prototype.off = EventEmitter.prototype.removeListener;
      EventEmitter.prototype.removeAllListeners = function removeAllListeners(type) {
        var listeners, events, i;
        events = this._events;
        if (events === undefined) return this;
        if (events.removeListener === undefined) {
          if (arguments.length === 0) {
            this._events = Object.create(null);
            this._eventsCount = 0;
          } else if (events[type] !== undefined) {
            if (--this._eventsCount === 0) this._events = Object.create(null); else delete events[type];
          }
          return this;
        }
        if (arguments.length === 0) {
          var keys = Object.keys(events);
          var key;
          for (i = 0; i < keys.length; ++i) {
            key = keys[i];
            if (key === "removeListener") continue;
            this.removeAllListeners(key);
          }
          this.removeAllListeners("removeListener");
          this._events = Object.create(null);
          this._eventsCount = 0;
          return this;
        }
        listeners = events[type];
        if (typeof listeners === "function") {
          this.removeListener(type, listeners);
        } else if (listeners !== undefined) {
          for (i = listeners.length - 1; i >= 0; i--) {
            this.removeListener(type, listeners[i]);
          }
        }
        return this;
      };
      function _listeners(target, type, unwrap) {
        var events = target._events;
        if (events === undefined) return [];
        var evlistener = events[type];
        if (evlistener === undefined) return [];
        if (typeof evlistener === "function") return unwrap ? [ evlistener.listener || evlistener ] : [ evlistener ];
        return unwrap ? unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length);
      }
      EventEmitter.prototype.listeners = function listeners(type) {
        return _listeners(this, type, true);
      };
      EventEmitter.prototype.rawListeners = function rawListeners(type) {
        return _listeners(this, type, false);
      };
      EventEmitter.listenerCount = function(emitter, type) {
        if (typeof emitter.listenerCount === "function") {
          return emitter.listenerCount(type);
        } else {
          return listenerCount.call(emitter, type);
        }
      };
      EventEmitter.prototype.listenerCount = listenerCount;
      function listenerCount(type) {
        var events = this._events;
        if (events !== undefined) {
          var evlistener = events[type];
          if (typeof evlistener === "function") {
            return 1;
          } else if (evlistener !== undefined) {
            return evlistener.length;
          }
        }
        return 0;
      }
      EventEmitter.prototype.eventNames = function eventNames() {
        return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : [];
      };
      function arrayClone(arr, n) {
        var copy = new Array(n);
        for (var i = 0; i < n; ++i) copy[i] = arr[i];
        return copy;
      }
      function spliceOne(list, index) {
        for (;index + 1 < list.length; index++) list[index] = list[index + 1];
        list.pop();
      }
      function unwrapListeners(arr) {
        var ret = new Array(arr.length);
        for (var i = 0; i < ret.length; ++i) {
          ret[i] = arr[i].listener || arr[i];
        }
        return ret;
      }
      function once(emitter, name) {
        return new Promise((function(resolve, reject) {
          function errorListener(err) {
            emitter.removeListener(name, resolver);
            reject(err);
          }
          function resolver() {
            if (typeof emitter.removeListener === "function") {
              emitter.removeListener("error", errorListener);
            }
            resolve([].slice.call(arguments));
          }
          eventTargetAgnosticAddListener(emitter, name, resolver, {
            once: true
          });
          if (name !== "error") {
            addErrorHandlerIfEventEmitter(emitter, errorListener, {
              once: true
            });
          }
        }));
      }
      function addErrorHandlerIfEventEmitter(emitter, handler, flags) {
        if (typeof emitter.on === "function") {
          eventTargetAgnosticAddListener(emitter, "error", handler, flags);
        }
      }
      function eventTargetAgnosticAddListener(emitter, name, listener, flags) {
        if (typeof emitter.on === "function") {
          if (flags.once) {
            emitter.once(name, listener);
          } else {
            emitter.on(name, listener);
          }
        } else if (typeof emitter.addEventListener === "function") {
          emitter.addEventListener(name, (function wrapListener(arg) {
            if (flags.once) {
              emitter.removeEventListener(name, wrapListener);
            }
            listener(arg);
          }));
        } else {
          throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type ' + typeof emitter);
        }
      }
    }
  };
  var __webpack_module_cache__ = {};
  function __webpack_require__(moduleId) {
    var cachedModule = __webpack_module_cache__[moduleId];
    if (cachedModule !== undefined) {
      return cachedModule.exports;
    }
    var module = __webpack_module_cache__[moduleId] = {
      exports: {}
    };
    __webpack_modules__[moduleId](module, module.exports, __webpack_require__);
    return module.exports;
  }
  const WINDOW_PROVIDER_TARGET = "qwallet-window-provider";
  const PROVIDER_BRIDGE_TARGET = "qwallet-provider-bridge";
  const EXTERNAL_PORT_NAME = "qwallet-external";
  const INTERNAL_PORT_NAME = "qwallet-internal";
  function getType(arg) {
    return Object.prototype.toString.call(arg).slice("[object ".length, -1);
  }
  function isObject(arg) {
    return getType(arg) === "Object";
  }
  function isArray(arg) {
    return Array.isArray(arg);
  }
  function isUndefined(arg) {
    return typeof arg === "undefined";
  }
  function isString(arg) {
    return getType(arg) === "String";
  }
  function isNumber(arg) {
    return getType(arg) === "Number";
  }
  function isMessageEvent(arg) {
    return arg instanceof MessageEvent;
  }
  function isRPCRequestParamsType(arg) {
    return isObject(arg) || isArray(arg);
  }
  function isWindowResponseEvent(arg) {
    return isMessageEvent(arg) && isString(arg.origin) && !isUndefined(arg.source) && isObject(arg.data) && isString(arg.data.id) && isString(arg.data.target) && !isUndefined(arg.data.result);
  }
  function isPortResponseEvent(arg) {
    return isObject(arg) && isString(arg.id) && !isUndefined(arg.result);
  }
  const AllowedQueryParamPage = {
    signTransaction: "/sign-transaction",
    addNewChain: "/add-evm-chain",
    dappPermission: "/dapp-permission",
    signData: "/sign-data",
    personalSignData: "/personal-sign"
  };
  function isAllowedQueryParamPage(url) {
    return Object.values(AllowedQueryParamPage).includes(url);
  }
  function isQwalInternalCommunication(arg) {
    return isObject(arg) && arg.id === "qwallet";
  }
  function isQwalConfigPayload(arg) {
    return isObject(arg) && arg.method === "qwal_getConfig";
  }
  function isQwalAccountPayload(arg) {
    return isObject(arg) && arg.method === "qwal_accountChanged" && isArray(arg.address);
  }
  const EIP1193_ERROR_CODES = {
    userRejectedRequest: {
      code: 4001,
      message: "The user rejected the request."
    },
    unauthorized: {
      code: 4100,
      message: "The requested method and/or account has not been authorized by the user."
    },
    unsupportedMethod: {
      code: 4200,
      message: "The Provider does not support the requested method."
    },
    disconnected: {
      code: 4900,
      message: "The Provider is disconnected from all chains."
    },
    chainDisconnected: {
      code: 4901,
      message: "The Provider is not connected to the requested chain."
    }
  };
  class EIP1193Error extends Error {
    constructor(eip1193Error) {
      super(eip1193Error.message);
      this.eip1193Error = eip1193Error;
    }
    toJSON() {
      return this.eip1193Error;
    }
  }
  function isEIP1193ErrorCodeNumber(code) {
    return isNumber(code) && Object.values(EIP1193_ERROR_CODES).map((e => e.code)).includes(code);
  }
  function isEIP1193Error(arg) {
    return isObject(arg) && isNumber(arg.code) && isEIP1193ErrorCodeNumber(arg.code) && isString(arg.message);
  }
  var events = __webpack_require__(7007);
  class QwalWindowProvider extends events.EventEmitter {
    chainId="MISSING_ENV_VAR".WINDOW_PROVIDER_DEFAULT_CHAIN_ID ?? "0x101";
    connected=false;
    isQwal=true;
    isWeb3=true;
    requestResolvers=new Map;
    providerInfo={
      label: "Qwal",
      injectedNamespace: "qwal",
      iconURL: "TODO",
      identityFlag: "isQwal",
      checkIdentity: provider => !!provider && !!provider.isQwal
    };
    constructor(transport) {
      super();
      this.transport = transport;
      const internalListener = event => {
        let result;
        if (isWindowResponseEvent(event) && isQwalInternalCommunication(event.data)) {
          if (event.origin !== this.transport.origin || event.source !== window || event.data.target !== WINDOW_PROVIDER_TARGET) {
            return;
          }
          result = event.data.result;
        } else if (isPortResponseEvent(event) && isQwalInternalCommunication(event)) {
          result = event.result;
        } else {
          return;
        }
        if (isQwalConfigPayload(result)) {
          if (result.chainId && result.chainId !== this.chainId) {
            this.handleChainIdChange(result.chainId);
          }
        } else if (isQwalAccountPayload(result)) {
          this.handleAddressChange(result.address);
        }
      };
      this.request = this.request.bind(this);
      this.transport.addEventListener(internalListener);
      this.transport.addEventListener(this.internalBridgeListener.bind(this));
    }
    internalBridgeListener(event) {
      let id;
      let result;
      if (isWindowResponseEvent(event)) {
        if (event.origin !== this.transport.origin || event.source !== window || event.data.target !== WINDOW_PROVIDER_TARGET) {
          return;
        }
        id = event.data.id;
        result = event.data.result;
      } else if (isPortResponseEvent(event)) {
        id = event.id;
        result = event.result;
      } else {
        return;
      }
      const requestResolver = this.requestResolvers.get(id);
      if (!requestResolver) return;
      const {sendData, reject, resolve} = requestResolver;
      this.requestResolvers.delete(sendData.id);
      const {method: sentMethod} = sendData.request;
      if (isEIP1193Error(result)) {
        reject(result);
      }
      if (!this.connected) {
        this.connected = true;
        this.emit("connect", {
          chainId: this.chainId
        });
      }
      switch (sentMethod) {
       case "wallet_switchEthereumChain":
       case "wallet_addEthereumChain":
        if (result === null) {
          this.handleChainIdChange(sendData.request.params[0].chainId);
        }
        break;

       case "eth_chainId":
       case "net_version":
        if (typeof result === "string" && Number(this.chainId) !== Number(result)) {
          this.handleChainIdChange(result);
        }
        break;

       case "eth_accounts":
       case "eth_requestAccounts":
        if (Array.isArray(result) && result.length !== 0) {
          this.handleAddressChange(result);
        }
        break;

       default:
        break;
      }
      resolve(result);
    }
    async enable() {
      return this.request({
        method: "eth_requestAccounts"
      });
    }
    isConnected() {
      return this.connected;
    }
    send(methodOrRequest, paramsOrCallback) {
      if (typeof methodOrRequest === "string" && typeof paramsOrCallback !== "function") {
        return this.request({
          method: methodOrRequest,
          params: paramsOrCallback
        });
      }
      if (isObject(methodOrRequest) && typeof paramsOrCallback === "function") {
        return this.sendAsync(methodOrRequest, paramsOrCallback);
      }
      return Promise.reject(new Error("Unsupported function parameters"));
    }
    sendAsync(request, callback) {
      return this.request(request).then((response => callback(null, {
        result: response,
        id: request.id,
        jsonrpc: request.jsonrpc
      })), (error => callback(error, null)));
    }
    requestID=0n;
    request(arg) {
      const {method, params = []} = arg;
      if (typeof method !== "string") {
        return Promise.reject(new Error(`unsupported method type: ${method}`));
      }
      const sendData = {
        id: this.requestID.toString(),
        target: PROVIDER_BRIDGE_TARGET,
        request: {
          method,
          params
        }
      };
      this.requestID += 1n;
      this.transport.postMessage(sendData);
      return new Promise(((resolve, reject) => {
        this.requestResolvers.set(sendData.id, {
          resolve,
          reject,
          sendData
        });
      }));
    }
    handleChainIdChange(chainId) {
      this.chainId = chainId;
      this.emit("chainChanged", chainId);
      this.emit("networkChanged", Number(chainId).toString());
    }
    handleAddressChange(address) {
      if (this.selectedAddress !== address[0]) {
        this.selectedAddress = address[0];
        this.emit("accountsChanged", address);
      }
    }
  }
  const qwalWindowProvider = new QwalWindowProvider({
    postMessage: data => window.postMessage(data, window.location.origin),
    addEventListener: fn => window.addEventListener("message", fn, false),
    removeEventListener: fn => window.removeEventListener("message", fn, false),
    origin: window.location.origin
  });
  function setupProviderWrapper() {
    Object.defineProperty(window, "qwal", {
      value: qwalWindowProvider,
      writable: false,
      configurable: false
    });
    try {
      Object.defineProperty(window, "qevm", {
        get() {
          return qwalWindowProvider;
        },
        set(_) {},
        configurable: false
      });
    } catch {
      if (false) {}
    }
  }
  function injectProvider() {
    if (document.contentType !== "text/html") {
      return;
    }
    setupProviderWrapper();
  }
  injectProvider();
})();
//# sourceMappingURL=window-provider.js.map