/******/ (() => { // webpackBootstrap
/******/ 	"use strict";
/******/ 	// The require scope
/******/ 	var __webpack_require__ = {};
/******/ 	
/************************************************************************/
/******/ 	/* webpack/runtime/compat get default export */
/******/ 	(() => {
/******/ 		// getDefaultExport function for compatibility with non-harmony modules
/******/ 		__webpack_require__.n = (module) => {
/******/ 			var getter = module && module.__esModule ?
/******/ 				() => (module['default']) :
/******/ 				() => (module);
/******/ 			__webpack_require__.d(getter, { a: getter });
/******/ 			return getter;
/******/ 		};
/******/ 	})();
/******/ 	
/******/ 	/* webpack/runtime/define property getters */
/******/ 	(() => {
/******/ 		// define getter functions for harmony exports
/******/ 		__webpack_require__.d = (exports, definition) => {
/******/ 			for(var key in definition) {
/******/ 				if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {
/******/ 					Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });
/******/ 				}
/******/ 			}
/******/ 		};
/******/ 	})();
/******/ 	
/******/ 	/* webpack/runtime/hasOwnProperty shorthand */
/******/ 	(() => {
/******/ 		__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))
/******/ 	})();
/******/ 	
/******/ 	/* webpack/runtime/make namespace object */
/******/ 	(() => {
/******/ 		// define __esModule on exports
/******/ 		__webpack_require__.r = (exports) => {
/******/ 			if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/ 				Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/ 			}
/******/ 			Object.defineProperty(exports, '__esModule', { value: true });
/******/ 		};
/******/ 	})();
/******/ 	
/************************************************************************/
var __webpack_exports__ = {};
// ESM COMPAT FLAG
__webpack_require__.r(__webpack_exports__);

// EXPORTS
__webpack_require__.d(__webpack_exports__, {
  WalletServicesPlugin: () => (/* reexport */ WalletServicesPlugin)
});

;// CONCATENATED MODULE: external "@babel/runtime/helpers/objectSpread2"
const objectSpread2_namespaceObject = require("@babel/runtime/helpers/objectSpread2");
var objectSpread2_default = /*#__PURE__*/__webpack_require__.n(objectSpread2_namespaceObject);
;// CONCATENATED MODULE: external "@babel/runtime/helpers/defineProperty"
const defineProperty_namespaceObject = require("@babel/runtime/helpers/defineProperty");
var defineProperty_default = /*#__PURE__*/__webpack_require__.n(defineProperty_namespaceObject);
;// CONCATENATED MODULE: external "@web3auth/base"
const base_namespaceObject = require("@web3auth/base");
;// CONCATENATED MODULE: external "@web3auth/base-plugin"
const base_plugin_namespaceObject = require("@web3auth/base-plugin");
;// CONCATENATED MODULE: external "@web3auth/ws-embed"
const ws_embed_namespaceObject = require("@web3auth/ws-embed");
var ws_embed_default = /*#__PURE__*/__webpack_require__.n(ws_embed_namespaceObject);
;// CONCATENATED MODULE: external "loglevel"
const external_loglevel_namespaceObject = require("loglevel");
var external_loglevel_default = /*#__PURE__*/__webpack_require__.n(external_loglevel_namespaceObject);
;// CONCATENATED MODULE: ./src/errors.ts


class WalletServicesPluginError extends base_namespaceObject.Web3AuthError {
  constructor(code, message) {
    // takes care of stack and proto
    super(code, message);

    // Set name explicitly as minification can mangle class names
    Object.defineProperty(this, "name", {
      value: "WalletServicesPluginError"
    });
  }
  static fromCode(code) {
    let extraMessage = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : "";
    return new WalletServicesPluginError(code, `${WalletServicesPluginError.messages[code]}${extraMessage}`);
  }
  static notInitialized() {
    let extraMessage = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : "";
    return WalletServicesPluginError.fromCode(5210, extraMessage);
  }
  static unsupportedAdapter() {
    let extraMessage = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : "";
    return WalletServicesPluginError.fromCode(5211, extraMessage);
  }
  static providerRequired() {
    let extraMessage = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : "";
    return WalletServicesPluginError.fromCode(5212, extraMessage);
  }
  static web3authRequired() {
    let extraMessage = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : "";
    return WalletServicesPluginError.fromCode(5213, extraMessage);
  }
  static web3AuthNotConnected() {
    let extraMessage = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : "";
    return WalletServicesPluginError.fromCode(5214, extraMessage);
  }
  static alreadyInitialized() {
    let extraMessage = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : "";
    return WalletServicesPluginError.fromCode(5216, extraMessage);
  }
  static unsupportedChainNamespace() {
    let extraMessage = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : "";
    return WalletServicesPluginError.fromCode(5218, extraMessage);
  }
  static differentWeb3authNetwork() {
    let extraMessage = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : "";
    return WalletServicesPluginError.fromCode(5219, extraMessage);
  }
}
defineProperty_default()(WalletServicesPluginError, "messages", {
  5210: "Wallet Services Plugin is not initialized",
  5211: "Web3Auth is connected to unsupported adapter. Wallet services connector plugin requires web3auth connected to openlogin adapter.",
  5212: "Provider is required..",
  5213: "Web3Auth instance is required while initialization.",
  5214: "Web3Auth is not connected.",
  5216: "Plugin is already initialized",
  5218: "Unsupported chain namespace.",
  5219: "Plugin network different than web3auth instance network."
});
;// CONCATENATED MODULE: ./src/plugin.ts







class WalletServicesPlugin {
  constructor() {
    let options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
    defineProperty_default()(this, "name", "WALLET_SERVICES_PLUGIN");
    defineProperty_default()(this, "SUPPORTED_ADAPTERS", [base_namespaceObject.WALLET_ADAPTERS.OPENLOGIN]);
    defineProperty_default()(this, "pluginNamespace", base_plugin_namespaceObject.PLUGIN_NAMESPACES.EIP155);
    defineProperty_default()(this, "wsEmbedInstance", void 0);
    defineProperty_default()(this, "provider", null);
    defineProperty_default()(this, "web3auth", null);
    defineProperty_default()(this, "isInitialized", false);
    defineProperty_default()(this, "walletInitOptions", null);
    const {
      wsEmbedOpts,
      walletInitOptions
    } = options;
    // we fake these checks here and get them from web3auth instance
    this.wsEmbedInstance = new (ws_embed_default())(wsEmbedOpts || {});
    this.walletInitOptions = walletInitOptions || {};
  }
  get proxyProvider() {
    return this.wsEmbedInstance.provider ? this.wsEmbedInstance.provider : null;
  }
  async initWithWeb3Auth(web3auth) {
    var _this$web3auth$coreOp;
    if (this.isInitialized) return;
    if (!web3auth) throw WalletServicesPluginError.web3authRequired();
    if (web3auth.provider && web3auth.connectedAdapterName !== base_namespaceObject.WALLET_ADAPTERS.OPENLOGIN) throw WalletServicesPluginError.unsupportedAdapter();
    if (web3auth.coreOptions.chainConfig.chainNamespace !== this.pluginNamespace) throw WalletServicesPluginError.unsupportedChainNamespace();
    // Not connected yet to openlogin
    if (web3auth.provider) {
      this.provider = web3auth.provider;
    }
    this.web3auth = web3auth;
    // get whitelabel from openlogin adapter
    const {
      options
    } = this.web3auth.walletAdapters[this.web3auth.connectedAdapterName].openloginInstance || {};
    const {
      logoDark,
      logoLight
    } = options.whiteLabel || {};
    if (!logoDark || !logoLight) throw new Error("logoDark and logoLight are required in whiteLabel config");
    this.wsEmbedInstance.web3AuthClientId = this.web3auth.coreOptions.clientId;
    this.wsEmbedInstance.web3AuthNetwork = this.web3auth.coreOptions.web3AuthNetwork;
    this.subscribeToWeb3AuthNoModalEvents(web3auth);
    const connectedChainConfig = web3auth.coreOptions.chainConfig;
    await this.wsEmbedInstance.init(objectSpread2_default()(objectSpread2_default()({}, this.walletInitOptions || {}), {}, {
      chainConfig: connectedChainConfig,
      buildEnv: options === null || options === void 0 ? void 0 : options.buildEnv,
      enableLogging: (_this$web3auth$coreOp = this.web3auth.coreOptions) === null || _this$web3auth$coreOp === void 0 ? void 0 : _this$web3auth$coreOp.enableLogging,
      whiteLabel: options.whiteLabel
    }));
    this.isInitialized = true;
  }
  initWithProvider() {
    throw new Error("Method not implemented.");
  }
  async connect() {
    var _this$web3auth;
    // if web3auth is being used and connected to unsupported adapter throw error
    if (this.web3auth && this.web3auth.connectedAdapterName !== base_namespaceObject.WALLET_ADAPTERS.OPENLOGIN) throw WalletServicesPluginError.unsupportedAdapter();
    const {
      connectedAdapterName
    } = this.web3auth;
    if (!this.isInitialized) throw WalletServicesPluginError.notInitialized();
    // Not connected yet to openlogin
    let sessionId = null;
    let sessionNamespace = "";
    if ((_this$web3auth = this.web3auth) !== null && _this$web3auth !== void 0 && _this$web3auth.provider) {
      const {
        openloginInstance
      } = this.web3auth.walletAdapters[connectedAdapterName];
      sessionId = openloginInstance.sessionId;
      sessionNamespace = this.web3auth.walletAdapters[connectedAdapterName].openloginInstance.sessionNamespace;
    } else if (this.web3auth) {
      throw WalletServicesPluginError.web3AuthNotConnected();
    } else {
      throw WalletServicesPluginError.providerRequired();
    }
    if (!sessionId) {
      throw WalletServicesPluginError.web3AuthNotConnected();
    }
    try {
      var _this$walletInitOptio;
      await this.wsEmbedInstance.loginWithSessionId({
        sessionId,
        sessionNamespace
      });
      if ((_this$walletInitOptio = this.walletInitOptions) !== null && _this$walletInitOptio !== void 0 && (_this$walletInitOptio = _this$walletInitOptio.whiteLabel) !== null && _this$walletInitOptio !== void 0 && _this$walletInitOptio.showWidgetButton) this.wsEmbedInstance.showTorusButton();
      this.subscribeToProviderEvents(this.provider);
      this.subscribeToWalletEvents();
    } catch (error) {
      external_loglevel_default().error(error);
    }
  }
  async showWalletConnectScanner() {
    if (!this.wsEmbedInstance.isLoggedIn) throw WalletServicesPluginError.web3AuthNotConnected();
    await this.wsEmbedInstance.showWalletConnectScanner();
  }
  async showCheckout() {
    if (!this.wsEmbedInstance.isLoggedIn) throw WalletServicesPluginError.web3AuthNotConnected();
    await this.wsEmbedInstance.showCheckout();
  }
  async showWalletUi() {
    if (!this.wsEmbedInstance.isLoggedIn) throw WalletServicesPluginError.web3AuthNotConnected();
    await this.wsEmbedInstance.showWalletUi();
  }
  async disconnect() {
    var _this$web3auth2;
    // if web3auth is being used and connected to unsupported adapter throw error
    if (((_this$web3auth2 = this.web3auth) === null || _this$web3auth2 === void 0 ? void 0 : _this$web3auth2.connectedAdapterName) !== base_namespaceObject.WALLET_ADAPTERS.OPENLOGIN) throw WalletServicesPluginError.unsupportedAdapter();
    if (this.wsEmbedInstance.isLoggedIn) {
      await this.wsEmbedInstance.logout();
    } else {
      throw new Error("Torus Wallet plugin is not connected");
    }
  }
  subscribeToWalletEvents() {
    var _this$wsEmbedInstance,
      _this = this;
    (_this$wsEmbedInstance = this.wsEmbedInstance) === null || _this$wsEmbedInstance === void 0 || _this$wsEmbedInstance.provider.on("accountsChanged", function () {
      let accounts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
      if (accounts.length === 0) {
        var _this$web3auth3, _this$web3auth4;
        _this.wsEmbedInstance.hideTorusButton();
        if (((_this$web3auth3 = _this.web3auth) === null || _this$web3auth3 === void 0 ? void 0 : _this$web3auth3.status) === base_namespaceObject.ADAPTER_STATUS.CONNECTED) (_this$web3auth4 = _this.web3auth) === null || _this$web3auth4 === void 0 || _this$web3auth4.logout();
      }
    });
  }
  subscribeToProviderEvents(provider) {
    var _this2 = this;
    provider.on("accountsChanged", function () {
      let data = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {
        accounts: []
      };
      _this2.setSelectedAddress(data.accounts[0]);
    });
    provider.on("chainChanged", chainId => {
      this.setChainID(parseInt(chainId, 16));
    });
    provider.on("disconnect", () => {
      this.wsEmbedInstance.hideTorusButton();
    });
    provider.on("connect", () => {
      var _this$walletInitOptio2;
      if ((_this$walletInitOptio2 = this.walletInitOptions) !== null && _this$walletInitOptio2 !== void 0 && _this$walletInitOptio2.whiteLabel.showWidgetButton) this.wsEmbedInstance.showTorusButton();
    });
  }
  subscribeToWeb3AuthNoModalEvents(web3Auth) {
    web3Auth.on(base_namespaceObject.ADAPTER_EVENTS.CONNECTED, async () => {
      if (web3Auth.connectedAdapterName !== base_namespaceObject.WALLET_ADAPTERS.OPENLOGIN) {
        external_loglevel_default().warn(`${web3Auth.connectedAdapterName} is not compatible with wallet services connector plugin`);
        return;
      }
      this.provider = web3Auth.provider;
      if (!this.provider) throw WalletServicesPluginError.web3AuthNotConnected();
      this.subscribeToProviderEvents(this.provider);
    });
    web3Auth.on(base_namespaceObject.ADAPTER_EVENTS.DISCONNECTED, async () => {
      this.provider = null;
      if (this.wsEmbedInstance.isLoggedIn) {
        await this.wsEmbedInstance.logout();
      }
      this.wsEmbedInstance.hideTorusButton();
    });
  }
  async sessionConfig() {
    if (!this.provider) throw WalletServicesPluginError.web3AuthNotConnected();
    const [accounts, chainId, chainConfig] = await Promise.all([this.provider.request({
      method: "eth_accounts"
    }), this.provider.request({
      method: "eth_chainId"
    }), this.provider.request({
      method: "eth_provider_config"
    })]);
    return {
      chainId: parseInt(chainId, 16),
      accounts: accounts,
      chainConfig: chainConfig
    };
  }
  async walletServicesSessionConfig() {
    if (!this.wsEmbedInstance.provider) throw WalletServicesPluginError.web3AuthNotConnected();
    const [accounts, chainId] = await Promise.all([this.wsEmbedInstance.provider.request({
      method: "eth_accounts"
    }), this.wsEmbedInstance.provider.request({
      method: "eth_chainId"
    })]);
    return {
      chainId: parseInt(chainId, 16),
      accounts: accounts
    };
  }
  async setSelectedAddress(address) {
    var _walletServicesSessio;
    if (!this.web3auth.connected) throw WalletServicesPluginError.web3AuthNotConnected();
    const walletServicesSessionConfig = await this.walletServicesSessionConfig();
    if (address !== ((_walletServicesSessio = walletServicesSessionConfig.accounts) === null || _walletServicesSessio === void 0 ? void 0 : _walletServicesSessio[0])) {
      const {
        sessionId,
        sessionNamespace
      } = this.web3auth.walletAdapters[this.web3auth.connectedAdapterName].openloginInstance;
      await this.wsEmbedInstance.loginWithSessionId({
        sessionId,
        sessionNamespace
      });
    }
  }
  async setChainID(chainId) {
    const [sessionConfig, walletServicesSessionConfig] = await Promise.all([this.sessionConfig(), this.walletServicesSessionConfig()]);
    const {
      chainConfig
    } = sessionConfig || {};
    if (chainId !== walletServicesSessionConfig.chainId && chainConfig) {
      var _this$wsEmbedInstance2, _this$wsEmbedInstance3;
      await ((_this$wsEmbedInstance2 = this.wsEmbedInstance.provider) === null || _this$wsEmbedInstance2 === void 0 ? void 0 : _this$wsEmbedInstance2.request({
        method: "wallet_addEthereumChain",
        params: [{
          chainId: chainConfig.chainId,
          chainName: chainConfig.displayName,
          rpcUrls: [chainConfig.rpcTarget],
          blockExplorerUrls: [chainConfig.blockExplorerUrl],
          nativeCurrency: {
            name: chainConfig.tickerName,
            symbol: chainConfig.ticker,
            decimals: chainConfig.decimals || 18
          },
          iconUrls: [chainConfig.logo]
        }]
      }));
      await ((_this$wsEmbedInstance3 = this.wsEmbedInstance.provider) === null || _this$wsEmbedInstance3 === void 0 ? void 0 : _this$wsEmbedInstance3.request({
        method: "wallet_switchEthereumChain",
        params: [{
          chainId: chainConfig.chainId
        }]
      }));
    }
  }
}
;// CONCATENATED MODULE: ./src/index.ts

module.exports = __webpack_exports__;
/******/ })()
;
//# sourceMappingURL=walletServicesPlugin.cjs.js.map