UNPKG

@particle-network/auth-connectors

Version:
542 lines (532 loc) 18.4 kB
"use strict"; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __hasOwnProp = Object.prototype.hasOwnProperty; var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // src/index.ts var src_exports = {}; __export(src_exports, { auth: () => auth, authWalletConnectors: () => authWalletConnectors, version: () => version }); module.exports = __toCommonJS(src_exports); // src/store.ts var import_auth_core2 = require("@particle-network/auth-core"); var import_authkit = require("@particle-network/authkit"); var import_connector_core3 = require("@particle-network/connector-core"); var import_vanilla = require("zustand/vanilla"); // src/getClient.ts var import_viem = require("viem"); var clients = /* @__PURE__ */ new Map(); function getPublicClient(chain) { { const client2 = clients.get(chain.id); if (client2) return client2; } const client = (0, import_viem.createPublicClient)({ chain, transport: (0, import_viem.http)() }); clients.set(chain.id, client); return client; } // src/getConnection.ts var import_web3 = require("@solana/web3.js"); var clients2 = /* @__PURE__ */ new Map(); function getConnection(chain, commitmentOrConfig) { { const client2 = clients2.get(chain.id); if (client2) return client2; } const client = new import_web3.Connection(chain.rpcUrls.default.http[0], commitmentOrConfig); clients2.set(chain.id, client); return client; } // src/particleEvm.ts var import_connector_core = require("@particle-network/connector-core"); particleEvm.type = "particleAuth"; function particleEvm() { let accountsChanged; let chainChanged; let disconnect; return (0, import_connector_core.createConnector)((config) => ({ get icon() { return "https://static.particle.network/logo-small.png"; }, get id() { return "particleEVM"; }, get name() { return "Particle Auth"; }, type: particleEvm.type, async connect(options) { var _a; const { chainId, isReconnecting } = options; const provider = await this.getProvider(); if (!provider) throw new import_connector_core.ProviderNotFoundError(); if (options.phone && !options.code) { throw new Error("Paramers error, need code."); } if (options.email && !options.code) { throw new Error("Paramers error, need code."); } if (options.provider && !options.thirdpartyCode) { throw new Error("Paramers error, need thirdpartyCode."); } let accounts = []; accounts = await this.getAccounts().catch(() => []); try { if (!(accounts == null ? void 0 : accounts.length) && !isReconnecting) { accounts = await provider.connect({ ...options, chain: chainId ? config.chains.filter(import_connector_core.isEVMChain).find((chain) => chain.id === chainId) : void 0 }); } if (!accountsChanged) { accountsChanged = this.onAccountsChanged.bind(this); provider.on("accountsChanged", accountsChanged); } if (!chainChanged) { chainChanged = this.onChainChanged.bind(this); provider.on("chainChanged", chainChanged); } if (!disconnect) { disconnect = this.onDisconnect.bind(this); provider.on("disconnect", disconnect); } let currentChainId = await this.getChainId(); if (chainId && currentChainId !== chainId) { const chain = await this.switchChain({ chainId }).catch((error) => { if (error.code === import_connector_core.UserRejectedRequestError.code) throw error; return { id: currentChainId }; }); currentChainId = (_a = chain == null ? void 0 : chain.id) != null ? _a : currentChainId; } return { accounts, chainId: currentChainId }; } catch (err) { const error = err; if (error.code === import_connector_core.UserRejectedRequestError.code) throw new import_connector_core.UserRejectedRequestError(error); throw error; } }, async disconnect() { const provider = await this.getProvider(); if (!provider) throw new import_connector_core.ProviderNotFoundError(); if (chainChanged) { provider.removeListener("chainChanged", chainChanged); chainChanged = void 0; } if (disconnect) { provider.removeListener("disconnect", disconnect); disconnect = void 0; } await provider.disconnect(); }, async getAccounts() { const provider = await this.getProvider(); if (!provider) throw new import_connector_core.ProviderNotFoundError(); const accounts = await provider.request({ method: "eth_accounts" }); return accounts; }, async getChainId() { const provider = await this.getProvider(); if (!provider) throw new import_connector_core.ProviderNotFoundError(); const hexChainId = await provider.request({ method: "eth_chainId" }); return Number(hexChainId); }, async getProvider() { var _a; if (typeof window === "undefined") return void 0; const provider = (_a = window.particle) == null ? void 0 : _a.ethereum; return provider; }, async isAuthorized() { try { const provider = await this.getProvider(); if (!provider) { throw new import_connector_core.ProviderNotFoundError(); } if (provider.isSocialConnecting) { const timeout = 3e4; await Promise.race([ ...typeof window !== "undefined" ? [ new Promise( (resolve) => window.addEventListener("particle:socialConnectCompleted", () => resolve(true), { once: true }) ) ] : [], new Promise((resolve) => setTimeout(() => resolve(true), timeout)) ]); } const accounts = await this.getAccounts(); return !!accounts.length; } catch { return false; } }, async switchChain({ chainId }) { const provider = await this.getProvider(); if (!provider) throw new import_connector_core.ProviderNotFoundError(); const chain = config.chains.filter(import_connector_core.isEVMChain).find((x) => x.id === chainId); if (!chain) throw new import_connector_core.SwitchChainError(new import_connector_core.ChainNotConfiguredError()); try { await Promise.all([ provider.request({ method: "wallet_switchEthereumChain", params: [{ chainId: (0, import_connector_core.numberToHex)(chainId) }] }).then(async () => { const currentChainId = await this.getChainId(); if (currentChainId === chainId) config.emitter.emit("change", { chainId }); }), new Promise( (resolve) => config.emitter.once("change", ({ chainId: currentChainId }) => { if (currentChainId === chainId) resolve(); }) ) ]); return chain; } catch (err) { const error = err; if (error.code === import_connector_core.UserRejectedRequestError.code) throw new import_connector_core.UserRejectedRequestError(error); throw new import_connector_core.SwitchChainError(error); } }, async onAccountsChanged(accounts) { if (accounts.length === 0) this.onDisconnect(); else config.emitter.emit("change", { accounts }); }, onChainChanged(chain) { const chainId = Number(chain); config.emitter.emit("change", { chainId }); }, async onDisconnect() { const provider = await this.getProvider(); config.emitter.emit("disconnect"); if (provider) { if (chainChanged) { provider.removeListener("chainChanged", chainChanged); chainChanged = void 0; } if (disconnect) { provider.removeListener("disconnect", disconnect); disconnect = void 0; } } }, isInstalled() { return true; } })); } // src/particleSolana.ts var import_connector_core2 = require("@particle-network/connector-core"); particleSolana.type = "particleAuth"; function particleSolana() { let accountsChanged; let chainChanged; let disconnect; return (0, import_connector_core2.createConnector)((config) => ({ get icon() { return "https://static.particle.network/logo-small.png"; }, get id() { return "particleSolana"; }, get name() { return "Particle Auth"; }, type: particleSolana.type, async connect(options) { var _a; const { chainId, isReconnecting } = options; const provider = await this.getProvider(); if (!provider) throw new import_connector_core2.ProviderNotFoundError(); if (options.phone && !options.code) { throw new Error("Paramers error, need code."); } if (options.email && !options.code) { throw new Error("Paramers error, need code."); } if (options.provider && !options.thirdpartyCode) { throw new Error("Paramers error, need thirdpartyCode."); } let accounts = []; accounts = await this.getAccounts().catch(() => []); try { if (!isReconnecting) { await provider.connect({ ...options, chain: chainId ? config.chains.filter(import_connector_core2.isSolanaChain).find((chain) => chain.id === chainId) : void 0 }); accounts = [provider.selectedAddress]; } else { if (accounts.length && !provider.isConnected) { await provider.connect(); } } if (!accountsChanged) { accountsChanged = this.onAccountsChanged.bind(this); provider.on("accountsChanged", accountsChanged); } if (!chainChanged) { chainChanged = this.onChainChanged.bind(this); provider.on("chainChanged", chainChanged); } if (!disconnect) { disconnect = this.onDisconnect.bind(this); provider.on("disconnect", disconnect); } let currentChainId = await this.getChainId(); if (chainId && currentChainId !== chainId) { const chain = await this.switchChain({ chainId }).catch((error) => { if (error.code === import_connector_core2.UserRejectedRequestError.code) throw error; return { id: currentChainId }; }); currentChainId = (_a = chain == null ? void 0 : chain.id) != null ? _a : currentChainId; } return { accounts, chainId: currentChainId }; } catch (err) { const error = err; if (error.code === import_connector_core2.UserRejectedRequestError.code) throw new import_connector_core2.UserRejectedRequestError(error); throw error; } }, async disconnect() { const provider = await this.getProvider(); if (!provider) throw new import_connector_core2.ProviderNotFoundError(); if (chainChanged) { provider.removeListener("chainChanged", chainChanged); chainChanged = void 0; } if (disconnect) { provider.removeListener("disconnect", disconnect); disconnect = void 0; } await provider.disconnect(); }, async getAccounts() { const provider = await this.getProvider(); if (!provider) throw new import_connector_core2.ProviderNotFoundError(); if (provider.selectedAddress) { return [provider.selectedAddress]; } return []; }, async getChainId() { const provider = await this.getProvider(); if (!provider) throw new import_connector_core2.ProviderNotFoundError(); if (config.chains.find((chain) => chain.id === provider.chainId)) { return provider.chainId; } const chainId = config.chains[0].id; await this.switchChain({ chainId }); return chainId; }, async getProvider() { var _a; if (typeof window === "undefined") return void 0; const provider = (_a = window.particle) == null ? void 0 : _a.solana; return provider; }, async isAuthorized() { try { const provider = await this.getProvider(); if (!provider) { throw new import_connector_core2.ProviderNotFoundError(); } if (provider.isSocialConnecting) { const timeout = 3e4; await Promise.race([ ...typeof window !== "undefined" ? [ new Promise( (resolve) => window.addEventListener("particle:socialConnectCompleted", () => resolve(true), { once: true }) ) ] : [], new Promise((resolve) => setTimeout(() => resolve(true), timeout)) ]); } const accounts = await this.getAccounts(); return !!accounts.length; } catch { return false; } }, async switchChain({ chainId }) { const provider = await this.getProvider(); if (!provider) throw new import_connector_core2.ProviderNotFoundError(); const chain = config.chains.filter(import_connector_core2.isSolanaChain).find((x) => x.id === chainId); if (!chain) throw new import_connector_core2.SwitchChainError(new import_connector_core2.ChainNotConfiguredError()); try { await provider.switchChain(chainId); return chain; } catch (err) { const error = err; if (error.code === import_connector_core2.UserRejectedRequestError.code) throw new import_connector_core2.UserRejectedRequestError(error); throw new import_connector_core2.SwitchChainError(error); } }, async onAccountsChanged(accounts) { if (accounts.length === 0) this.onDisconnect(); else config.emitter.emit("change", { accounts }); }, onChainChanged(chain) { const chainId = Number(chain); config.emitter.emit("change", { chainId }); }, async onDisconnect() { const provider = await this.getProvider(); config.emitter.emit("disconnect"); if (provider) { if (chainChanged) { provider.removeListener("chainChanged", chainChanged); chainChanged = void 0; } if (disconnect) { provider.removeListener("disconnect", disconnect); disconnect = void 0; } } }, isInstalled() { return true; } })); } // src/types.ts var import_auth_core = require("@particle-network/auth-core"); var auth = { getCloudflareTurnstileResponse: import_auth_core.getCloudflareTurnstileResponse, getConnectCaptcha: import_auth_core.getConnectCaptcha, getLatestAuthType: import_auth_core.getLatestAuthType }; // src/store.ts authWalletConnectors.type = "particleAuth"; function authWalletConnectors(parameters = {}) { const { authTypes, fiatCoin, promptSettingConfig, overrides, language } = parameters; if (authTypes && authTypes.length === 0) { throw new Error("authTypes cannot be empty."); } const supportAuthTypes = authTypes || Object.values(import_auth_core2.AuthType); return (0, import_connector_core3.createWalletConnector)((options) => { const { chains: _chains, storage, projectId, clientKey, appId } = options; const chains = (0, import_vanilla.createStore)(() => _chains); function setup(connectorFn) { var _a; const emitter = (0, import_connector_core3.createEmitter)(); const result = connectorFn({ emitter, chains: _chains, storage }); const connector = { ...result, emitter, uid: emitter.uid, chainType: result.id.toLowerCase().includes("evm") ? "evm" : "solana", walletConnectorType: authWalletConnectors.type }; (_a = connector.setup) == null ? void 0 : _a.call(connector); return connector; } const storeData = []; if (_chains.some(import_connector_core3.isEVMChain)) { storeData.push(particleEvm()); } if (_chains.some(import_connector_core3.isSolanaChain)) { storeData.push(particleSolana()); } const connectors = (0, import_vanilla.createStore)(() => storeData.map(setup)); function getClient(chainId) { const chain = chains.getState().find((chain2) => chain2.id === chainId); if (!chain) { throw new import_connector_core3.ChainNotConfiguredError(); } if ((0, import_connector_core3.isEVMChain)(chain)) { return getPublicClient(chain); } return getConnection(chain); } return { get type() { return authWalletConnectors.type; }, get chains() { return chains.getState(); }, get connectors() { return connectors.getState(); }, store: connectors, getClient, supportAuthTypes, authOptions: { projectId, clientKey, appId, authTypes: supportAuthTypes, fiatCoin, language, promptSettingConfig, supportEIP6963: false, customStyle: { zIndex: 21475e5, ...overrides == null ? void 0 : overrides.customStyle }, wallet: false, chains: _chains }, AuthCoreContextProvider: import_authkit.AuthCoreContextProvider, _internal: { connectors: { setup } }, auth }; }); } // src/version.ts var version = "2.1.1"; //# sourceMappingURL=index.cjs.map