@human.tech/waap-sdk 1.0.1 → 1.0.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -1
- package/dist/index.d.ts +3 -2
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/index.modern.mjs +1 -1
- package/dist/index.modern.mjs.map +1 -1
- package/dist/index.module.js +1 -1
- package/dist/index.module.js.map +1 -1
- package/dist/index.umd.js +1 -1
- package/dist/index.umd.js.map +1 -1
- package/dist/lib/WalletMessageManager.d.ts +1 -1
- package/dist/lib/provider/EthereumProvider.d.ts +3 -2
- package/dist/lib/provider/EthereumProviderExtension.d.ts +1 -1
- package/dist/lib/provider/requests.d.ts +1 -1
- package/dist/lib/provider/types.d.ts +2 -1
- package/dist/lib/provider/utils.d.ts +1 -1
- package/dist/ui/WaapComponent.d.ts +37 -0
- package/dist/ui/index.d.ts +4 -10
- package/package.json +7 -7
- package/src/global.d.ts +17 -0
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sources":["../src/lib/WalletMessageManager.ts","../src/lib/UIMessageManager.ts","../src/lib/provider/requests.ts","../src/lib/provider/utils.ts","../src/lib/WalletConnect.ts","../src/lib/provider/EthereumProvider.ts","../src/ui/index.ts","../src/lib/provider/EthereumProviderExtension.ts"],"sourcesContent":["/**\n * WalletMessageManager handles messages between the wallet (in the Silk iframe)\n * and the wallet SDK (in the top frame). It is used by EthereumProvider\n * to communicate with the wallet.\n */\nimport {\n SilkRequest,\n SilkResponse,\n SILK_MESSAGE_TYPE,\n SILK_METHOD,\n SILK_NOTIFICATION,\n SilkNotificationData,\n generateMessageId\n} from '@silk-wallet/silk-interface-core'\n\nimport {\n silkWalletAppOrigin2,\n silkWalletAppOrigin2Staging\n} from '@silk-wallet/silk-constants'\n\ntype PostSilkRequestArgs = {\n method: keyof typeof SILK_METHOD\n params: any[]\n interactionRequired: boolean\n}\n\n/**\n * Listener interface for WalletMessageManager\n */\ninterface MessageListenerConfig {\n handleResponse: (response: SilkResponse) => void\n handleRequest: (request: SilkRequest) => void\n onReceiveConnectNotif?: () => void\n onAccountChanged?: (newAccount: string) => void\n}\n\nclass WalletMessageManager {\n private iframeWindow: Window | null = null\n private walletOrigin: string\n\n constructor(iframeWindow: Window, useStaging: boolean) {\n this.iframeWindow = iframeWindow\n this.walletOrigin = useStaging\n ? silkWalletAppOrigin2Staging\n : silkWalletAppOrigin2\n }\n\n /**\n * Post a Silk notification to the given iframeWindow\n */\n postSilkNotification(data: SilkNotificationData) {\n this.iframeWindow!.postMessage(\n {\n target: 'silk' as const,\n messageType: SILK_MESSAGE_TYPE.notification,\n data\n },\n this.walletOrigin\n )\n }\n\n postReadyNotification() {\n this.postSilkNotification(SILK_NOTIFICATION.ready)\n }\n\n postConnectNotification() {\n this.postSilkNotification(SILK_NOTIFICATION.connect)\n }\n\n /**\n * Post a 'ready' notification to the iframe, and wait\n * for the iframe to respond with a 'ready' notification.\n */\n pingIframe() {\n return new Promise<void>((resolve, reject) => {\n setTimeout(() => reject('Wallet ping timed out.'), 10000)\n const eventHandler = (event: MessageEvent) => {\n if (\n event.data.target === 'silk' &&\n event.data.messageType === SILK_MESSAGE_TYPE.notification &&\n event.data.data === SILK_NOTIFICATION.ready\n ) {\n window.removeEventListener('message', eventHandler)\n resolve()\n }\n }\n window.addEventListener('message', eventHandler)\n this.postReadyNotification()\n })\n }\n\n /**\n * Post a SilkRequest to the iframeWindow. Don't wait for a response.\n */\n async postSilkRequest(req: PostSilkRequestArgs) {\n const baseRequest = {\n ...req,\n target: 'silk' as const,\n messageType: SILK_MESSAGE_TYPE.request as const\n }\n const id = await generateMessageId(baseRequest)\n this.iframeWindow!.postMessage({ ...baseRequest, id }, this.walletOrigin)\n return id\n }\n\n /**\n * Add a message listener to the window in which this is called (which should be the top frame).\n * It handles all messages from the Silk iframe posted to the top frame.\n * @param config - Configuration that includes callbacks for handling specific messages.\n */\n addListener(config: MessageListenerConfig) {\n const {\n handleResponse,\n handleRequest,\n onReceiveConnectNotif,\n onAccountChanged\n } = config\n\n window.addEventListener('message', (event) => {\n // Note: It is extremely important that NODE_ENV be set properly in production\n try {\n const origin =\n typeof process !== 'undefined' &&\n process.env &&\n process.env.NODE_ENV === 'test'\n ? 'http://127.0.0.1:3000'\n : event.origin\n\n if (origin !== this.walletOrigin) {\n return\n }\n } catch (error) {\n if (event.origin !== this.walletOrigin) {\n return\n }\n }\n\n if (event.data?.messageType === SILK_MESSAGE_TYPE.request) {\n handleRequest(event.data as SilkRequest)\n } else if (event.data?.messageType === SILK_MESSAGE_TYPE.response) {\n handleResponse(event.data as SilkResponse)\n } else if (event.data?.messageType === SILK_MESSAGE_TYPE.notification) {\n if (event.data?.data === SILK_NOTIFICATION.connect) {\n onReceiveConnectNotif?.()\n } else if (\n event.data?.data?.type === SILK_NOTIFICATION.account_changed &&\n onAccountChanged\n ) {\n onAccountChanged(event.data.data.account)\n }\n }\n })\n }\n}\n\nexport { WalletMessageManager, PostSilkRequestArgs }\nexport default WalletMessageManager\n","/**\n * UIMessageManager emits events whose intended recipient is the UI\n * of the silk-wallet-sdk. It is used by EthereumProvider to\n * communicate with the UI.\n *\n * Note that the UI part of silk-wallet-sdk is not the Silk\n * website but rather the actual iframe tag that gets embedded\n * in the host site.\n */\nimport { EventEmitter } from \"events\";\n\nenum UI_EVENT_NAMES {\n show_modal = \"show_modal\",\n hide_modal = \"hide_modal\",\n}\n\nclass UIMessageManager extends EventEmitter {\n constructor() {\n super();\n }\n}\n\nexport { UI_EVENT_NAMES, UIMessageManager };\nexport default UIMessageManager;\n","import { EventEmitter } from 'events'\nimport { JSON_RPC_METHOD, SilkResponse } from '@silk-wallet/silk-interface-core'\nimport { rpcMethodRequiresUI } from '@silk-wallet/silk-constants'\nimport WalletMessageManager from '../WalletMessageManager.js'\nimport { RequestArguments } from './types.js'\n\n/**\n * Send request to wallet in iframe, and upon receiving the wallet's response\n * or error, hide modal and return wallet's response or throw wallet's error.\n */\nasync function handleWalletRequestAndResponse(\n args: RequestArguments,\n interactionRequired: boolean,\n walletMessageManager: WalletMessageManager,\n internalProviderEventEmitter: EventEmitter\n) {\n const method = args.method as JSON_RPC_METHOD\n const params = args.params as any[]\n\n // Send request to wallet in iframe\n const id = await walletMessageManager.postSilkRequest({\n method,\n params,\n interactionRequired\n })\n // Return wallet's response\n return new Promise((resolve, reject) => {\n // setTimeout(() => reject(\"Request timed out\"), 60 * 1000);\n internalProviderEventEmitter.once(id, (response: SilkResponse) => {\n // We check for error first because some RPC methods return null if they are successful\n if (response.error) reject(response.error)\n else resolve(response.data)\n })\n })\n}\n\nexport { rpcMethodRequiresUI, handleWalletRequestAndResponse }\n","import { CustomConfig } from '@silk-wallet/silk-interface-core'\n\nexport function isMetaMask(provider: any) {\n if (!provider?.isMetaMask) return false\n // Brave tries to make itself look like MetaMask\n // Could also try RPC `web3_clientVersion` if following is unreliable\n // if (provider.isBraveWallet && !provider._events && !provider._state) {\n // return false\n // }\n if (provider.isApexWallet) return false\n if (provider.isAvalanche) return false\n if (provider.isBitKeep) return false\n if (provider.isBlockWallet) return false\n if (provider.isMathWallet) return false\n if (provider.isOkxWallet || provider.isOKExWallet) return false\n if (provider.isOneInchIOSWallet || provider.isOneInchAndroidWallet) {\n return false\n }\n if (provider.isOpera) return false\n if (provider.isPortal) return false\n if (provider.isRabby) return false\n if (provider.isDefiant) return false\n if (provider.isTokenPocket) return false\n if (provider.isTokenary) return false\n if (provider.isZerion) return false\n return true\n}\n\nexport function isSafeTransaction(params?: unknown[] | object): boolean {\n try {\n if (!params || !Array.isArray(params)) return false\n\n // For eth_signTypedData_v4, params[1] contains the typed data\n const typedData = JSON.parse(\n typeof params[1] === 'string' ? params[1] : JSON.stringify(params[1])\n )\n\n // Check if it's a Safe transaction by verifying:\n // 1. Primary type is 'SafeTx'\n // 2. Has verifyingContract in domain (Safe address)\n // 3. Has required SafeTx fields in message\n return (\n typedData.primaryType === 'SafeTx' &&\n typedData.domain?.verifyingContract !== undefined &&\n typedData.message &&\n 'to' in typedData.message &&\n 'value' in typedData.message &&\n 'safeTxGas' in typedData.message &&\n 'baseGas' in typedData.message &&\n 'gasPrice' in typedData.message &&\n 'nonce' in typedData.message\n )\n } catch {\n return false\n }\n}\n\nexport const defaultConfig: CustomConfig = {\n styles: {\n darkMode: false\n }\n}\n","import { EthersAdapter } from '@reown/appkit-adapter-ethers'\n\nexport class SilkWalletConnect {\n private static instance: any = null\n private static projectId: string | undefined = undefined\n // Ethereum, Optimism, Gnosis, Polygon, Base, Avalanche, Arbitrum, Celo, Base Sepolia, Sepolia\n private static chains: number[] = [\n 1, 10, 100, 137, 8453, 43114, 42161, 42220, 84532, 11155111\n ]\n // private static optionalChains: AppKitNetwork[]\n\n /**\n * Set the WalletConnect project ID programmatically\n * Use this if environment variables aren't working in your setup\n *\n * @param id - The WalletConnect project ID to use\n */\n static setProjectId(id: string) {\n this.projectId = id\n }\n\n // /**\n // * Set the optional chains to use for WalletConnect\n // *\n // * @param chains - The optional chains to use (number[])\n // */\n // static setOptionalChains(chains: AppKitNetwork[]) {\n // SilkWalletConnect.optionalChains = chains\n // }\n\n static getProjectIdFromEnv() {\n try {\n // Check if process and process.env exist.\n if (typeof process !== 'undefined' && process.env) {\n // List of common env variable names to check\n return (\n process.env.NEXT_PUBLIC_WALLET_CONNECT_PROJECT_ID ||\n process.env.VITE_WALLET_CONNECT_PROJECT_ID ||\n process.env.REACT_APP_WALLET_CONNECT_PROJECT_ID ||\n process.env.WALLET_CONNECT_PROJECT_ID\n ) // Generic fallback\n }\n } catch (error) {\n // Silently fail if process is not defined.\n // This is expected in a pure browser environment.\n return undefined\n }\n return undefined\n }\n\n static async getInstance() {\n // Skip initialization if not in browser environment\n if (typeof window === 'undefined' || typeof document === 'undefined') {\n return null\n }\n // Dynamically import AppKit only in browser environment\n const { createAppKit } = await import('@reown/appkit')\n const {\n mainnet,\n sepolia,\n optimism,\n arbitrum,\n optimismGoerli,\n polygon,\n gnosis,\n avalanche,\n aurora,\n fantom,\n base,\n celo\n } = await import('@reown/appkit/networks')\n\n try {\n // // 2. Create your application's metadata object\n const metadata = {\n name: 'Human Wallet',\n description:\n 'Silk lets you create human keys for web3 wallets that are recoverable with private identity proofs and secured by zero trust protocols.',\n url: window.location.origin, // origin must match your domain & subdomain\n icons: [\n 'https://imagedelivery.net/_aTEfDRm7z3tKgu9JhfeKA/f11f5753-616a-4aa0-2aee-9b75befea700/sm'\n ]\n }\n\n // // Check for project ID in multiple places, in order of precedence\n const projectId = this.projectId || this.getProjectIdFromEnv()\n\n if (!projectId) {\n console.error(\n 'WalletConnect project ID not found. Please set it using one of these methods:\\n' +\n '1. Pass walletConnectProjectId when calling initSilk\\n' +\n '2. Call SilkWalletConnect.setProjectId(\"your-project-id\")\\n' +\n '3. Set WALLET_CONNECT_PROJECT_ID (NEXT_PUBLIC_WALLET_CONNECT_PROJECT_ID for Next projects) environment variable'\n )\n return null\n }\n\n // Set it again in case it comes from env\n this.projectId = projectId\n\n if (!this.instance) {\n this.instance = createAppKit({\n adapters: [new EthersAdapter()],\n projectId,\n metadata,\n networks: [\n // @ts-ignore\n mainnet,\n sepolia,\n arbitrum,\n optimism,\n polygon,\n gnosis,\n avalanche,\n aurora,\n fantom,\n base,\n celo\n ],\n features: {\n socials: false,\n email: false\n }\n })\n }\n\n return this.instance\n } catch (error) {\n console.error('Error importing or initializing WalletConnect:', error)\n return null\n }\n }\n\n static async listenToAccountChangeEvent() {\n await new Promise<void>((resolve) => {\n const unsubscribe = this.instance.subscribeAccount(\n (accountState: any) => {\n if (accountState?.isConnected) {\n resolve()\n }\n }\n )\n })\n }\n\n /**\n * Wait for WalletConnect to be properly initialized and connected\n * @returns Promise<boolean> - true if connected, false if timeout reached\n */\n static async waitForReadyAndCheckConnection(): Promise<boolean> {\n if (!this.instance) {\n return false\n }\n\n let isConnected = false\n let attempts = 0\n const maxAttempts = 15 // Maximum 15 attempts\n\n while (!isConnected && attempts < maxAttempts) {\n // Use shorter delays initially, then longer ones\n const delay = attempts < 5 ? 500 : 1000 // 500ms for first 5 attempts, then 1s\n await new Promise((resolve) => setTimeout(resolve, delay))\n\n isConnected = this.instance.getIsConnectedState()\n attempts++\n console.log(\n `WalletConnect connection check attempt ${attempts}: ${isConnected}`\n )\n }\n\n return isConnected\n }\n\n /**\n * Check if WalletConnect is currently connected (immediate check, no waiting)\n * @returns boolean - true if connected, false otherwise\n */\n static isConnected(): boolean {\n return this.instance?.getIsConnectedState() ?? false\n }\n\n /**\n * Get the wallet provider from the WalletConnect instance\n * @returns The wallet provider or null if not available\n */\n static getWalletProvider(): any {\n return this.instance?.getWalletProvider() ?? null\n }\n}\n","/**\n * A Ethereum provder API (from EIP 1193) for Silk.\n * https://eips.ethereum.org/EIPS/eip-1193\n */\n\n/**\n * Resources:\n * - EIP-2255: Wallet Permissions System: https://eips.ethereum.org/EIPS/eip-2255\n */\nimport { EventEmitter } from 'events'\nimport {\n SILK_METHOD,\n JSON_RPC_METHOD,\n SilkRequest,\n SilkResponse,\n CustomConfig,\n CredentialType,\n ProjectConfig\n} from '@silk-wallet/silk-interface-core'\nimport {\n EthereumProviderInterface,\n LoginResponse,\n RequestArguments,\n SilkEthereumProviderInterface\n} from './types.js'\nimport WalletMessageManager from '../WalletMessageManager.js'\nimport { UIMessageManager, UI_EVENT_NAMES } from '../UIMessageManager.js'\nimport {\n rpcMethodRequiresUI,\n handleWalletRequestAndResponse\n} from './requests.js'\nimport { defaultConfig, isMetaMask, isSafeTransaction } from './utils.js'\nimport { SilkWalletConnect } from '../WalletConnect.js'\n\nclass EthereumProvider\n extends EventEmitter\n implements SilkEthereumProviderInterface\n{\n public readonly isSilk = true\n public readonly isWaaP = true\n public connected = false\n public walletMessageManager: WalletMessageManager\n public uiMessageManager: UIMessageManager\n public config: CustomConfig\n private currentAccount: string | null = null\n private walletConnectProvider: any = null\n private persistedMethods: {\n login: () => Promise<LoginResponse>\n logout: () => Promise<unknown>\n getLoginMethod: () => LoginResponse\n walletMessageManager: WalletMessageManager\n uiMessageManager: UIMessageManager\n internalEventEmitter: EventEmitter\n silkRequest: (args: RequestArguments) => Promise<unknown>\n waaPRequest: (args: RequestArguments) => Promise<unknown>\n portal: (\n feature: 'gastank' | 'customization' | 'project',\n operation: 'get' | 'update' | 'topup' | 'init',\n payload?: any\n ) => Promise<unknown>\n requestEmail: () => Promise<unknown>\n requestSBT: (type: CredentialType) => Promise<unknown>\n orcid: () => Promise<unknown>\n enable: () => Promise<unknown>\n isConnected: () => boolean\n toggleDarkMode: () => Promise<void>\n }\n\n /**\n * We use the internalEventEmitter to emit as events\n * Silk messages posted to the window.\n */\n public internalEventEmitter = new EventEmitter()\n\n /**\n * @param iframeWindow - The contentWindow of the iframe of the Silk website.\n * @param referralCode - Silk points referral code\n * @param customConfig - Silk custom UI configuration\n * @param project - Silk project configuration\n * @param useStaging - Whether to use the staging environment\n */\n constructor(\n iframeWindow: Window,\n referralCode?: string,\n customConfig?: CustomConfig,\n project?: ProjectConfig,\n useStaging?: boolean\n ) {\n super()\n\n this.uiMessageManager = new UIMessageManager()\n this.walletMessageManager = new WalletMessageManager(\n iframeWindow!,\n !!useStaging\n )\n this.config = {\n ...defaultConfig,\n ...(customConfig || {}) // Override with customConfig if provided\n }\n\n // Initialize WalletConnect provider if wallet authentication is enabled\n if (this.config.authenticationMethods?.includes('wallet')) {\n // Initialize asynchronously to avoid blocking the constructor\n this.initializeWalletConnect().catch((error) => {\n console.error('WalletConnect initialization failed:', error)\n })\n }\n\n this.persistedMethods = {\n login: this.login.bind(this),\n logout: this.logout.bind(this),\n getLoginMethod: this.getLoginMethod.bind(this),\n walletMessageManager: this.walletMessageManager,\n internalEventEmitter: this.internalEventEmitter,\n uiMessageManager: this.uiMessageManager,\n portal: this.portal.bind(this),\n requestEmail: this.requestEmail.bind(this),\n requestSBT: this.requestSBT.bind(this),\n orcid: this.orcid.bind(this),\n enable: this.enable.bind(this),\n isConnected: this.isConnected.bind(this),\n toggleDarkMode: this.toggleDarkMode.bind(this),\n // We leave this silkRequest separate and never changing so that\n // we can still call the original request method if needed no matter\n // the current provider\n silkRequest: this.request.bind(this),\n waaPRequest: this.request.bind(this)\n }\n\n // Set up message listeners for the WalletMessageManager\n this.walletMessageManager.addListener({\n onReceiveConnectNotif: () => {\n console.log('onReceiveConnectNotif')\n this.connected = true\n this.emit('connect')\n },\n handleResponse: (response: SilkResponse) =>\n this.internalEventEmitter.emit(response.id, response),\n handleRequest: (request: SilkRequest) => {\n if (request.method === SILK_METHOD.show_modal) {\n this.uiMessageManager.emit(UI_EVENT_NAMES.show_modal)\n } else if (request.method === SILK_METHOD.hide_modal) {\n this.uiMessageManager.emit(UI_EVENT_NAMES.hide_modal)\n }\n },\n onAccountChanged: (newAccount: string) => {\n // Handle account change events\n if (this.currentAccount !== newAccount) {\n this.currentAccount = newAccount\n\n // Emit accountsChanged event with an array containing the new account\n // This follows the MetaMask standard (EIP-1193)\n this.emit('accountsChanged', newAccount ? [newAccount] : [])\n }\n }\n })\n\n // Tell the iframe to set the referral code\n if (referralCode) {\n // Wait for iframe to load (if it hasn't already)\n this.walletMessageManager\n .pingIframe()\n .then(() => {\n return handleWalletRequestAndResponse(\n {\n method: SILK_METHOD.set_points_referral_code,\n params: [referralCode]\n },\n false,\n this.walletMessageManager,\n this.internalEventEmitter\n )\n })\n .catch((error) => {\n console.error('Error setting referral code in Silk iframe:', error)\n })\n }\n\n // Tell the iframe to set the project config\n if (project) {\n this.walletMessageManager.pingIframe().then(() => {\n return handleWalletRequestAndResponse(\n {\n method: SILK_METHOD.set_project,\n params: [project, window.location.origin]\n },\n false,\n this.walletMessageManager,\n this.internalEventEmitter\n )\n })\n }\n\n // Tell the iframe to set the custom config\n if (customConfig) {\n this.walletMessageManager\n .pingIframe()\n .then(() => {\n return handleWalletRequestAndResponse(\n {\n method: SILK_METHOD.set_custom_config,\n params: [customConfig]\n },\n false,\n this.walletMessageManager,\n this.internalEventEmitter\n )\n })\n .catch((error) => {\n console.error('Error setting custom config in Silk iframe:', error)\n })\n }\n }\n\n private async initializeWalletConnect(): Promise<void> {\n try {\n this.walletConnectProvider = await SilkWalletConnect.getInstance()\n console.log('WalletConnect provider initialized')\n } catch (error) {\n console.error('Failed to initialize WalletConnect provider:', error)\n this.walletConnectProvider = null\n }\n }\n\n public async enable(): Promise<unknown> {\n return this.request({ method: 'eth_requestAccounts' })\n }\n\n public isConnected(): boolean {\n return this.connected\n }\n\n public async request(args: RequestArguments): Promise<unknown> {\n if (\n !Object.keys(JSON_RPC_METHOD).includes(\n args.method as keyof typeof JSON_RPC_METHOD\n )\n ) {\n return Promise.reject({ error: `Not implemented (${args.method})` })\n }\n\n // Attempt auto-connect for account-related methods\n const autoConnectResult = await this.attemptAutoConnect(args.method)\n if (autoConnectResult !== null) {\n return autoConnectResult\n }\n\n // Initial check if this is a Safe transaction (other check happens on wallet internal and on the BE)\n const isSafeTx = isSafeTransaction(args.params)\n\n /**\n * Security: Safe transactions must use eth_signTypedData_v4\n * - Safe contract only accepts EIP-712 signatures or direct hash signatures\n * - Attempting to disguise Safe transactions as regular transactions or using\n * different signing methods would fail because:\n * 1. Safe contract requires specific signature format\n * 2. Transaction simulation validates proper Safe context\n * 3. Signatures are cryptographically bound to actual transaction parameters\n */\n if (isSafeTx) {\n // Safe transactions must use eth_signTypedData_v4\n if (args.method !== JSON_RPC_METHOD.eth_signTypedData_v4) {\n return Promise.reject({\n error: 'Safe transactions must be signed using eth_signTypedData_v4'\n })\n }\n }\n\n // Wait for iframe to load (if it hasn't already)\n await this.walletMessageManager.pingIframe()\n\n const response = await handleWalletRequestAndResponse(\n args,\n rpcMethodRequiresUI(args.method as JSON_RPC_METHOD),\n this.walletMessageManager,\n this.internalEventEmitter\n )\n\n if (\n (args.method === JSON_RPC_METHOD.wallet_switchEthereumChain ||\n args.method === JSON_RPC_METHOD.wallet_addEthereumChain) &&\n response === null\n ) {\n this.emit(\n 'chainChanged',\n (args.params as { chainId: string }[])?.[0]?.chainId\n )\n\n // After switching chains, re-emit account info to ensure dApps (like Safe)\n // can re-establish the signer context on the new chain\n try {\n // Get current accounts to ensure we have the latest account info\n const accounts = (await this.request({\n method: 'eth_accounts'\n })) as string[]\n if (accounts && accounts.length > 0) {\n this.currentAccount = accounts[0]\n\n // Emit both accountsChanged and connect events to ensure dApps\n // (especially Safe protocol-kit) re-establish signer context\n this.emit('accountsChanged', accounts)\n this.emit('connect', {\n chainId: (args.params as { chainId: string }[])?.[0]?.chainId\n })\n\n console.log(\n '[EthereumProvider] Re-emitted accounts and connect after chain switch:',\n {\n accounts,\n chainId: (args.params as { chainId: string }[])?.[0]?.chainId\n }\n )\n }\n } catch (error) {\n console.warn(\n '[EthereumProvider] Failed to get accounts after chain switch:',\n error\n )\n // Fallback to current account if available\n if (this.currentAccount) {\n this.emit('accountsChanged', [this.currentAccount])\n // Also emit connect event for fallback\n this.emit('connect', {\n chainId: (args.params as { chainId: string }[])?.[0]?.chainId\n })\n }\n }\n }\n\n return response\n }\n\n public async login(\n customProvider?: EthereumProviderInterface\n ): Promise<LoginResponse> {\n // Skip if not in browser environment\n if (typeof window === 'undefined' || typeof document === 'undefined') {\n return null\n }\n\n // Use the class-level walletConnectProvider if available, otherwise initialize it\n if (\n this.config.authenticationMethods?.includes('wallet') &&\n !this.walletConnectProvider\n ) {\n await this.initializeWalletConnect()\n }\n\n const provider = customProvider || (window.ethereum as any)\n\n const providerWalletName =\n provider && isMetaMask(provider) ? 'MetaMask' : 'Browser Wallet'\n\n // Wait for iframe to load (if it hasn't already)\n await this.walletMessageManager.pingIframe()\n\n const response = await handleWalletRequestAndResponse(\n { method: SILK_METHOD.login, params: [providerWalletName] },\n true,\n this.walletMessageManager,\n this.internalEventEmitter\n )\n\n if (typeof response === 'string' && response.includes('waap')) {\n localStorage.setItem(`${window.location.origin}-connected`, 'waap')\n\n this.setupWaaP()\n }\n\n if (\n typeof response === 'string' &&\n response.includes('injected') &&\n provider\n ) {\n localStorage.setItem(`${window.location.origin}-connected`, 'injected')\n\n this.setupInjectedWallet(provider)\n }\n\n if (typeof response === 'string' && response.includes('walletconnect')) {\n localStorage.setItem(\n `${window.location.origin}-connected`,\n 'walletconnect'\n )\n\n if (!SilkWalletConnect.isConnected()) {\n await this.walletConnectProvider.open({ view: 'Connect' })\n\n await SilkWalletConnect.listenToAccountChangeEvent()\n }\n\n const provider = SilkWalletConnect.getWalletProvider()\n\n this.setupWalletConnect(provider)\n }\n\n return response as LoginResponse\n }\n\n public async logout(): Promise<unknown> {\n // Wait for iframe to load (if it hasn't already)\n await this.walletMessageManager.pingIframe()\n\n // Clear the stored login method\n this.cleanupInvalidLoginState()\n\n // Reset to Human Wallet state\n\n // Use the class-level walletConnectProvider if available\n if (this.walletConnectProvider) {\n await this.walletConnectProvider.disconnect()\n }\n\n return handleWalletRequestAndResponse(\n { method: SILK_METHOD.logout },\n false,\n this.walletMessageManager,\n this.internalEventEmitter\n )\n }\n\n private cleanupInvalidLoginState(): void {\n try {\n localStorage.removeItem(`${window.location.origin}-connected`)\n } catch (error) {\n // Ignore cleanup errors in case localStorage is not available\n console.warn('Could not clean up login state:', error)\n }\n }\n\n /**\n * Helper method to set up window.waap for WaaP\n */\n private setupWaaP(): void {\n const provider = {\n ...this.persistedMethods,\n isWaaP: true,\n request: this.request.bind(this)\n }\n // @ts-ignore\n window.silk = provider\n // @ts-ignore - Add WaaP alias\n window.waap = provider\n }\n\n /**\n * Helper method to set up window.silk for injected wallets (e.g., MetaMask)\n */\n private setupInjectedWallet(provider: any): void {\n const injectedProvider = {\n ...this.persistedMethods,\n ...provider,\n isSilk: true,\n connected: provider.connected ?? false,\n on: provider.on?.bind(provider) ?? (() => {}),\n removeListener: provider.removeListener?.bind(provider) ?? (() => {}),\n request: provider.request.bind(provider)\n }\n window.silk = injectedProvider\n // @ts-ignore - Add WaaP alias\n window.waap = injectedProvider\n }\n\n /**\n * Helper method to set up window.silk for WalletConnect\n */\n private setupWalletConnect(provider: any): void {\n const walletConnectProvider = {\n ...this.persistedMethods,\n ...provider,\n isSilk: true,\n connected: true,\n on: provider.on?.bind(provider) ?? (() => {}),\n removeListener: provider.removeListener?.bind(provider) ?? (() => {}),\n request: provider.request.bind(provider)\n }\n window.silk = walletConnectProvider\n // @ts-ignore - Add WaaP alias\n window.waap = walletConnectProvider\n }\n\n /**\n * Helper method to set up window.silk for auto-connect with injected wallets\n */\n private setupAutoConnectInjected(provider: any): void {\n const injectedProvider = {\n ...this.persistedMethods,\n ...provider,\n isSilk: false,\n // @ts-ignore\n connected: provider.isConnected?.() ?? false,\n // @ts-ignore\n on: provider.on?.bind(provider) ?? (() => {}),\n removeListener:\n // @ts-ignore\n provider.removeListener?.bind(provider) ?? (() => {}),\n // @ts-ignore\n request: provider.request.bind(provider)\n }\n window.silk = injectedProvider\n // @ts-ignore - Add WaaP alias\n window.waap = injectedProvider\n }\n\n /**\n * Helper method to set up window.silk for auto-connect with WalletConnect\n */\n private setupAutoConnectWalletConnect(provider: any): void {\n const walletConnectProvider = {\n ...this.persistedMethods,\n ...provider,\n isSilk: false,\n connected: true,\n on: provider.on?.bind(provider) ?? (() => {}),\n removeListener: provider.removeListener?.bind(provider) ?? (() => {}),\n request: provider.request.bind(provider)\n }\n window.silk = walletConnectProvider\n // @ts-ignore - Add WaaP alias\n window.waap = walletConnectProvider\n }\n\n /**\n * Attempts to auto-connect using previously stored login method\n * @param method - The RPC method being called\n * @returns Promise<unknown> if auto-connect succeeds, null if it should fall through to normal flow\n */\n private async attemptAutoConnect(method: string): Promise<unknown | null> {\n // Only attempt auto-connect for account-related methods\n if (method !== 'eth_requestAccounts' && method !== 'eth_accounts') {\n return null\n }\n\n this.walletMessageManager.pingIframe().then(async () => {\n await handleWalletRequestAndResponse(\n {\n method: SILK_METHOD.auto_conn,\n params: [window.location.origin]\n },\n false,\n this.walletMessageManager,\n this.internalEventEmitter\n )\n })\n\n // Use our robust getLoginMethod to check connection state\n const loginMethod = this.getLoginMethod()\n\n if (loginMethod === 'injected' && window.ethereum) {\n try {\n this.setupAutoConnectInjected(window.ethereum)\n\n // @ts-ignore\n return window.ethereum.request({\n method: 'eth_requestAccounts'\n })\n } catch (error) {\n // If injected wallet fails, clean up and fall through to normal flow\n console.warn('Injected wallet auto-connect failed:', error)\n this.cleanupInvalidLoginState()\n return null\n }\n } else if (loginMethod === 'walletconnect') {\n try {\n if (!this.walletConnectProvider) {\n this.walletConnectProvider = await SilkWalletConnect.getInstance()\n }\n\n // Wait for WalletConnect to be ready\n const isConnected =\n await SilkWalletConnect.waitForReadyAndCheckConnection()\n\n if (isConnected) {\n const provider = SilkWalletConnect.getWalletProvider()\n this.setupAutoConnectWalletConnect(provider)\n\n // Return the accounts from the active WalletConnect session\n return provider.request({\n method: 'eth_requestAccounts'\n })\n } else {\n console.log(\n 'WalletConnect not connected, cleaning up and falling through to normal flow'\n )\n // Clean up invalid WalletConnect state\n this.cleanupInvalidLoginState()\n return null\n }\n } catch (error) {\n // If WalletConnect fails, clean up and fall through to normal flow\n console.warn('WalletConnect auto-connect failed:', error)\n this.cleanupInvalidLoginState()\n return null\n }\n }\n\n // For 'human' login method or if auto-connect failed, fall through to normal Silk flow\n return null\n }\n\n public getLoginMethod(): LoginResponse {\n // Skip if not in browser environment\n if (typeof window === 'undefined' || typeof localStorage === 'undefined') {\n return null\n }\n\n try {\n const stored = localStorage.getItem(`${window.location.origin}-connected`)\n\n if (!stored) {\n return null\n }\n\n // Validate that stored value is a valid LoginResponse\n if (!['waap', 'human', 'injected', 'walletconnect'].includes(stored)) {\n // Invalid value in localStorage, clean it up\n this.cleanupInvalidLoginState()\n return null\n }\n\n // Verify the connection is actually still valid\n switch (stored) {\n case 'injected':\n // Check if injected wallet (e.g., MetaMask) is still available\n if (!window.ethereum) {\n // Browser wallet is no longer available, clean up\n this.cleanupInvalidLoginState()\n return null\n }\n return 'injected'\n\n case 'walletconnect':\n // Check if WalletConnect session is still active\n try {\n if (!SilkWalletConnect.isConnected()) {\n // WalletConnect session is no longer active, clean up\n this.cleanupInvalidLoginState()\n return null\n }\n return 'walletconnect'\n } catch (error) {\n // Error checking WalletConnect status, assume disconnected\n this.cleanupInvalidLoginState()\n return null\n }\n\n case 'waap':\n // For WaaP, we trust the localStorage value since the connection\n // state is managed by the Silk iframe. The actual connection verification\n // happens when eth_requestAccounts is called.\n return 'waap'\n\n case 'human':\n return 'human'\n\n default:\n // This shouldn't happen due to the validation above, but just in case\n this.cleanupInvalidLoginState()\n return null\n }\n } catch (error) {\n // Any unexpected error (localStorage access issues, etc.)\n console.warn('Error checking login method:', error)\n this.cleanupInvalidLoginState()\n return null\n }\n }\n\n public async toggleDarkMode(): Promise<void> {\n this.config.styles!.darkMode = !this.config.styles!.darkMode\n\n this.walletMessageManager\n .pingIframe()\n .then(() => {\n return handleWalletRequestAndResponse(\n {\n method: SILK_METHOD.set_custom_config,\n params: [this.config]\n },\n false,\n this.walletMessageManager,\n this.internalEventEmitter\n )\n })\n .catch((error) => {\n console.error('Error setting custom config in Silk iframe:', error)\n })\n }\n\n public async safe(): Promise<void> {\n this.walletMessageManager.pingIframe().then(() => {\n return handleWalletRequestAndResponse(\n { method: SILK_METHOD.safe },\n true,\n this.walletMessageManager,\n this.internalEventEmitter\n )\n })\n }\n\n public async orcid(): Promise<void> {\n this.walletMessageManager.pingIframe().then(() => {\n return handleWalletRequestAndResponse(\n { method: SILK_METHOD.orcid },\n true,\n this.walletMessageManager,\n this.internalEventEmitter\n )\n })\n }\n\n /**\n * INTERNAL METHOD: Gas tank administration operations\n * This method is ONLY accessible from the Dev Portal domain\n * It's not included in the public typing to hide it from regular dApps\n */\n public async portal(\n feature: 'gastank' | 'customization' | 'project',\n operation: 'get' | 'update' | 'topup' | 'init',\n payload?: any\n ): Promise<unknown> {\n // Removed this for now due to devPortalHostname constant being set as localhost for staging environment on SDK\n // Second validation happens on silk-wallet-internal\n // const reqHostname = new URL(window.location.origin).hostname\n\n // const devPortalHostname = new URL(silkDevPortalOrigin).hostname\n\n // console.log('req hostname: ', reqHostname)\n\n // console.log('devPortalHostName: ', devPortalHostname)\n\n // if (devPortalHostname !== reqHostname) {\n // return Promise.reject({\n // error:\n // 'Unauthorized: Gas tank admin functions are only available from the Dev Portal'\n // })\n // }\n\n // Wait for iframe to load (if it hasn't already)\n await this.walletMessageManager.pingIframe()\n\n let methodName: string\n switch (operation) {\n case 'get':\n methodName =\n feature === 'gastank'\n ? SILK_METHOD.gastank_get_settings\n : SILK_METHOD.customization_get\n break\n case 'update':\n methodName =\n feature === 'gastank'\n ? SILK_METHOD.gastank_update_settings\n : SILK_METHOD.customization_update\n break\n case 'topup':\n methodName = SILK_METHOD.gastank_topup\n break\n case 'init':\n methodName = SILK_METHOD.project_init\n break\n }\n\n // For update operations, mark as requiring user interaction for signing\n const interactionRequired =\n operation !== 'get' && feature !== 'customization'\n\n // Handle the request to the wallet\n return handleWalletRequestAndResponse(\n {\n method: methodName,\n params: [payload, window.location.origin]\n },\n interactionRequired, // Only open modal for update operations\n this.walletMessageManager,\n this.internalEventEmitter\n )\n }\n\n public async requestEmail(): Promise<unknown> {\n // Wait for iframe to load (if it hasn't already)\n await this.walletMessageManager.pingIframe()\n\n return handleWalletRequestAndResponse(\n { method: SILK_METHOD.silk_requestEmail },\n true,\n this.walletMessageManager,\n this.internalEventEmitter\n )\n }\n\n /**\n * Prompt the user to mint a Zeronym SBT.\n * @returns string or null - The address of the owner of the SBT, or null\n * if the user already minted the SBT.\n */\n public async requestSBT(type: CredentialType): Promise<unknown> {\n // Wait for iframe to load (if it hasn't already)\n await this.walletMessageManager.pingIframe()\n\n return handleWalletRequestAndResponse(\n {\n method: SILK_METHOD.silk_requestSbt,\n params: [type]\n },\n true,\n this.walletMessageManager,\n this.internalEventEmitter\n )\n }\n}\n\nexport { EthereumProvider }\n","import {\n silkWalletAppOrigin2,\n silkWalletAppOrigin2Staging\n} from '@silk-wallet/silk-constants'\nimport {\n InitSilkOptions,\n SilkEthereumProviderInterface\n} from '../lib/provider/types.js'\nimport { EthereumProvider } from '../lib/provider/EthereumProvider.js'\nimport { UI_EVENT_NAMES } from '../lib/UIMessageManager.js'\nimport { SilkWalletConnect } from 'lib/WalletConnect.js'\n\n// Container ID constants - supporting both old (silk-wallet) and new (waap-wallet) naming\nconst LEGACY_IFRAME_CONTAINER_ID = 'silk-wallet-iframe-container'\nconst LEGACY_IFRAME_WRAPPER_ID = 'silk-wallet-iframe-wrapper'\nconst LEGACY_IFRAME_ID = 'silk-wallet-iframe'\n\nconst NEW_IFRAME_CONTAINER_ID = 'waap-wallet-iframe-container'\nconst NEW_IFRAME_WRAPPER_ID = 'waap-wallet-iframe-wrapper'\nconst NEW_IFRAME_ID = 'waap-wallet-iframe'\n\n/**\n * Get the existing iframe container element, checking both old and new naming conventions\n * @returns HTMLElement | null\n */\nconst getIframeContainer = (): HTMLElement | null => {\n return (\n document.getElementById(NEW_IFRAME_CONTAINER_ID) ||\n document.getElementById(LEGACY_IFRAME_CONTAINER_ID)\n )\n}\n\n/**\n * Get the existing iframe wrapper element, checking both old and new naming conventions\n * @returns HTMLElement | null\n */\nconst getIframeWrapper = (): HTMLElement | null => {\n return (\n document.getElementById(NEW_IFRAME_WRAPPER_ID) ||\n document.getElementById(LEGACY_IFRAME_WRAPPER_ID)\n )\n}\n\n/**\n * Get the existing iframe element, checking both old and new naming conventions\n * @returns HTMLIFrameElement | null\n */\nconst getIframe = (): HTMLIFrameElement | null => {\n return (document.getElementById(NEW_IFRAME_ID) ||\n document.getElementById(LEGACY_IFRAME_ID)) as HTMLIFrameElement | null\n}\n\n// Default to new naming for new installations\nconst iframeContainerId = NEW_IFRAME_CONTAINER_ID\nconst iframeWrapperId = NEW_IFRAME_WRAPPER_ID\nconst iframeId = NEW_IFRAME_ID\n\nconst createSilkIframe = (useStaging: boolean) => {\n // If iframe container is already on page (checking both old and new naming), do nothing\n if (getIframeContainer()) {\n return\n }\n\n // Create iframe container element\n const container = window.document.createElement('div')\n container.id = iframeContainerId\n container.style.position = 'fixed'\n container.style.top = '0'\n container.style.left = '0'\n container.style.right = '0'\n container.style.bottom = '0'\n container.style.width = '100%'\n container.style.height = '100%'\n container.style.display = 'flex'\n container.style.alignItems = 'center'\n container.style.justifyContent = 'center'\n\n // // Completely transparent background\n // container.style.backgroundColor = 'rgba(0, 0, 0, 0)'\n\n // Semi-transparent dark overlay\n container.style.backgroundColor = 'rgba(0, 0, 0, 0.5)'\n container.style.zIndex = '99999'\n container.style.display = 'none'\n\n // // Add onClick event to container to hide the modal if user clicks outside iFrame?\n // container.addEventListener('click', (event) => {\n // console.log('event.target: ', event.target)\n // if (event.target === container) {\n // container.style.display = 'none'\n // }\n // })\n\n // Create svgs for close button\n const closeSvgString = `<svg width=\"32\" height=\"32\" viewBox=\"0 0 32 32\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\">\n <rect width=\"32\" height=\"32\" rx=\"16\" fill=\"#F5F5F5\"/>\n <path d=\"M20.9497 11.0503L11.0503 20.9498M11.0503 11.0503L20.9497 20.9498\" stroke=\"#A3A3A3\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"/>\n </svg>`\n const closeSvgBlob = new Blob([closeSvgString], { type: 'image/svg+xml' })\n const closeSvgUrl = URL.createObjectURL(closeSvgBlob)\n const closeErrorSvgString = `<svg width=\"32\" height=\"32\" viewBox=\"0 0 32 32\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\">\n <rect width=\"32\" height=\"32\" rx=\"16\" fill=\"#FEF3F2\"/>\n <path d=\"M20.9497 11.0503L11.0503 20.9498M11.0503 11.0503L20.9497 20.9498\" stroke=\"#F97066\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"/>\n </svg>`\n const closeErrorSvgBlob = new Blob([closeErrorSvgString], {\n type: 'image/svg+xml'\n })\n const closeErrorSvgUrl = URL.createObjectURL(closeErrorSvgBlob)\n\n const closeButton = document.createElement('button')\n const img = document.createElement('img')\n\n img.src = closeSvgUrl\n img.alt = 'closeIcon'\n closeButton.addEventListener('mouseenter', function () {\n img.src = closeErrorSvgUrl\n })\n closeButton.addEventListener('mouseleave', function () {\n img.src = closeSvgUrl\n })\n closeButton.style.all = 'initial'\n closeButton.style.height = 'fit-content'\n closeButton.style.position = 'absolute'\n closeButton.style.top = '1px' // \"-40px\";\n closeButton.style.right = '1px'\n // Note for future: zIndex 999999 is causing the iframe body to be\n // considered invisible by IntersectionObserverV2. We can address this\n // by removing closeButton's zIndex and giving the iframeWrapper a width\n // and height such that it does not cover the same area as the close\n // button. We will need to calculate the width and height of the iframeWrapper\n // based on the screen size to ensure that no matter what the screen size is\n // the closeButton will have enough space to be visible.\n closeButton.style.zIndex = '999999'\n closeButton.style.cursor = 'pointer'\n closeButton.appendChild(img)\n closeButton.onclick = () => {\n container.style.display = 'none'\n }\n // container.appendChild(closeButton);\n\n // Create iframe wrapper element and center the iframe inside it\n const iframeWrapper = window.document.createElement('div')\n iframeWrapper.id = iframeWrapperId\n iframeWrapper.style.position = 'relative'\n iframeWrapper.style.display = 'flex'\n iframeWrapper.style.alignItems = 'center'\n iframeWrapper.style.justifyContent = 'center'\n iframeWrapper.style.padding = '0'\n iframeWrapper.style.margin = '0'\n iframeWrapper.style.height = '600px'\n iframeWrapper.style.width = '380px'\n\n container.appendChild(iframeWrapper)\n\n // Create iframe element and put it in the iframe wrapper\n const iframe = window.document.createElement('iframe')\n iframe.id = iframeId\n iframe.src = `${\n useStaging ? silkWalletAppOrigin2Staging : silkWalletAppOrigin2\n }/iframe`\n\n console.log('iframe.src: ', iframe.src)\n // TODO: Once we handle different screen sizes in the app, make height and width\n // of the iframe different for different screen sizes.\n\n // Set iframe to fill the wrapper\n iframe.style.width = '100%'\n iframe.style.height = '100%'\n\n // Set default dimensions for iframe wrapper\n const setDefaultDimensions = () => {\n const iframeWrapper = getIframeWrapper()\n if (iframeWrapper) {\n iframeWrapper.style.height = '600px'\n iframeWrapper.style.width = '380px'\n }\n }\n\n // Set default dimensions initially\n setTimeout(setDefaultDimensions, 100)\n\n // Listen for size updates from iframe\n const handleIframeMessage = (event: MessageEvent) => {\n // Only accept messages from the iframe origin\n const expectedOrigin = useStaging\n ? silkWalletAppOrigin2Staging\n : silkWalletAppOrigin2\n\n if (event.origin !== expectedOrigin) return\n\n // Validate message structure\n if (!event.data || typeof event.data !== 'object') return\n if (event.data.type !== 'silk-iframe-size') return\n\n const contentHeight = event.data.height\n const contentWidth = event.data.width\n\n // Input validation - must be positive numbers within reasonable bounds\n const maxDimension = 2000 // Max 2000px to prevent layout issues\n const minDimension = 50 // Min 50px to ensure visibility\n\n // Type checking\n if (typeof contentHeight !== 'number' || typeof contentWidth !== 'number')\n return\n\n // Bounds checking\n if (contentHeight < minDimension || contentHeight > maxDimension) return\n if (contentWidth < minDimension || contentWidth > maxDimension) return\n\n // Safety checks for valid finite numbers\n if (!Number.isFinite(contentHeight) || !Number.isFinite(contentWidth))\n return\n\n const iframeWrapper = getIframeWrapper()\n if (!iframeWrapper) return\n\n // Apply validated dimensions (floor to prevent fractional pixels)\n iframeWrapper.style.height = `${Math.floor(contentHeight)}px`\n iframeWrapper.style.width = `${Math.floor(contentWidth)}px`\n }\n\n window.addEventListener('message', handleIframeMessage)\n\n // Store cleanup function for potential future use\n ;(iframe as any).__silkCleanup = () => {\n window.removeEventListener('message', handleIframeMessage)\n }\n\n iframe.style.border = 'none'\n iframe.style.borderRadius = '24px'\n iframe.style.backgroundColor = 'transparent'\n iframe.style.background = 'transparent'\n iframe.style.padding = '0'\n iframe.style.margin = '0'\n iframeWrapper.appendChild(iframe)\n\n // // Prevent clicks on the iframe from propagating to the container\n // iframe.addEventListener('click', (event) => {\n // event.stopPropagation()\n // })\n\n // Add the container to the window.document body\n window.document.body.appendChild(container)\n}\n\n// function warnStagingInit(useStaging: boolean) {\n// if (useStaging) {\n// console.log(\n// 'WARNING: Silk has been initialized to use the Silk staging environment. ' +\n// 'Silk staging is subject to rapid, unannounced changes, and is not ' +\n// 'recommended for production use or for storing large amounts of funds.'\n// )\n// }\n// }\n\n/**\n * @param referralCode - Silk points referral code\n * @param customConfig - Silk custom UI configuration\n * @param project - Silk project configuration\n * @param useStaging - Whether to use the staging environment\n * @param walletConnectProjectId - WalletConnect project ID (only required when passing `wallet` to `authenticationMethods`)\n * @param walletConnectOptionalChains - Optional chains to use for WalletConnect\n */\n\nconst initSilk = (\n params: InitSilkOptions = {}\n): SilkEthereumProviderInterface => {\n // warnStagingInit(!!params.useStaging)\n createSilkIframe(!!params.useStaging)\n const container = getIframeContainer()\n const iframe = getIframe()\n\n if (!container || !iframe) {\n throw new Error('Silk iframe does not exist on page')\n }\n\n // If walletConnectProjectId is provided, set it\n if (params.walletConnectProjectId) {\n SilkWalletConnect.setProjectId(params.walletConnectProjectId)\n }\n\n const { referralCode, config, project } = params\n\n // Create ethereum provider and attach it to window\n const contentWindow = iframe.contentWindow as Window\n const silkEthereumProvider = new EthereumProvider(\n contentWindow,\n referralCode,\n config || {},\n project || {},\n params.useStaging\n )\n\n silkEthereumProvider.uiMessageManager.on(UI_EVENT_NAMES.show_modal, () => {\n container.style.display = 'flex'\n })\n silkEthereumProvider.uiMessageManager.on(UI_EVENT_NAMES.hide_modal, () => {\n container.style.display = 'none'\n })\n\n // @ts-ignore\n window.silk = silkEthereumProvider\n // @ts-ignore - WaaP alias\n window.waap = silkEthereumProvider\n\n return silkEthereumProvider\n}\n\n/**\n * WaaP alias for initSilk - maintains backwards compatibility\n * @param params - Same parameters as initSilk\n * @returns SilkEthereumProviderInterface (same as initSilk)\n */\nconst initWaaP = initSilk\n\nexport { initSilk, initWaaP }\n","/**\n * A Ethereum provder API (from EIP 1193) for Silk.\n * https://eips.ethereum.org/EIPS/eip-1193\n */\n\n/**\n * Resources:\n * - EIP-2255: Wallet Permissions System: https://eips.ethereum.org/EIPS/eip-2255\n */\nimport {\n CredentialType,\n CustomConfig,\n JSON_RPC_METHOD,\n SILK_METHOD\n} from '@silk-wallet/silk-interface-core'\nimport { EventEmitter } from 'events'\nimport { EthereumProviderInterface, RequestArguments } from './types.js'\nimport { defaultConfig } from './utils.js'\n\nclass EthereumProviderExtension\n extends EventEmitter\n implements EthereumProviderInterface\n{\n public readonly isSilk = true\n public connected = false\n public config: CustomConfig\n\n constructor(customConfig?: CustomConfig) {\n super()\n this.config = {\n ...defaultConfig,\n ...(customConfig || {})\n }\n }\n\n // Send a message to the background script via `chrome.runtime.sendMessage`\n sendToExtension(args: RequestArguments) {\n // Use window.postMessage to communicate with the content script\n return new Promise((resolve, reject) => {\n window.postMessage({ type: 'FROM_PAGE', request: args }, '*')\n window.addEventListener('message', (event) => {\n if (event.data.type === 'FROM_EXTENSION') {\n if (event.data.error) reject(event.data.error)\n else resolve(event.data.result)\n }\n })\n })\n }\n\n // EIP-1193 `request` method implementation\n public async request(args: RequestArguments): Promise<unknown> {\n if (!Object.keys(JSON_RPC_METHOD).includes(args.method)) {\n return Promise.reject({ error: `Not implemented (${args.method})` })\n }\n\n const response = await this.sendToExtension(args)\n\n if (\n (args.method === JSON_RPC_METHOD.wallet_switchEthereumChain ||\n args.method === JSON_RPC_METHOD.wallet_addEthereumChain) &&\n response === null\n ) {\n this.emit(\n 'chainChanged',\n (args.params as { chainId: string }[])?.[0]?.chainId\n )\n }\n\n return response\n }\n\n // Enable method that dApps use to request accounts\n public async enable(): Promise<unknown> {\n return this.request({ method: 'eth_requestAccounts' })\n }\n\n // Check if the provider is connected\n public isConnected(): boolean {\n return this.connected\n }\n\n // Example of a custom method to handle login requests\n public async login(): Promise<unknown> {\n return this.sendToExtension({ method: SILK_METHOD.login })\n }\n\n // Example of requesting an SBT (Soulbound Token)\n public async requestSBT(type: CredentialType): Promise<unknown> {\n return this.sendToExtension({\n method: SILK_METHOD.silk_requestSbt,\n params: [type]\n })\n }\n\n // Example of toggling dark mode as part of custom config\n public async toggleDarkMode(): Promise<void> {\n this.config.styles!.darkMode = !this.config.styles!.darkMode\n\n await this.sendToExtension({\n method: SILK_METHOD.set_custom_config,\n params: [this.config]\n })\n }\n\n public async safe(): Promise<unknown> {\n return this.sendToExtension({ method: SILK_METHOD.safe })\n }\n}\n\nexport { EthereumProviderExtension }\n"],"names":["UI_EVENT_NAMES","WalletMessageManager","iframeWindow","useStaging","this","walletOrigin","silkWalletAppOrigin2Staging","silkWalletAppOrigin2","_proto","prototype","postSilkNotification","data","postMessage","target","messageType","SILK_MESSAGE_TYPE","notification","postReadyNotification","SILK_NOTIFICATION","ready","postConnectNotification","connect","pingIframe","_this","Promise","resolve","reject","setTimeout","window","addEventListener","eventHandler","event","removeEventListener","postSilkRequest","req","_this2","baseRequest","_extends","request","generateMessageId","then","id","e","addListener","config","_this3","handleResponse","handleRequest","onReceiveConnectNotif","onAccountChanged","_event$data","_event$data2","_event$data3","process","origin","error","response","_event$data4","_event$data5","type","account_changed","account","UIMessageManager","_EventEmitter","call","_inheritsLoose","EventEmitter","handleWalletRequestAndResponse","args","interactionRequired","walletMessageManager","internalProviderEventEmitter","method","params","once","defaultConfig","styles","darkMode","pact","state","value","s","_Pact","o","_settle","bind","v","observer","onFulfilled","onRejected","result","callback","thenable","SilkWalletConnect","setProjectId","projectId","getProjectIdFromEnv","env","NEXT_PUBLIC_WALLET_CONNECT_PROJECT_ID","VITE_WALLET_CONNECT_PROJECT_ID","REACT_APP_WALLET_CONNECT_PROJECT_ID","WALLET_CONNECT_PROJECT_ID","getInstance","document","_interopNamespace","require","_ref","createAppKit","_ref2","mainnet","sepolia","optimism","arbitrum","polygon","gnosis","avalanche","aurora","fantom","base","celo","metadata","name","description","url","location","icons","instance","adapters","EthersAdapter","networks","features","socials","email","console","listenToAccountChangeEvent","subscribeAccount","accountState","isConnected","waitForReadyAndCheckConnection","attempts","_temp","_for","delay","getIsConnectedState","log","_this$instance$getIsC","_this$instance","getWalletProvider","_this$instance$getWal","_this$instance2","_catch","body","recover","undefined","chains","EthereumProvider","referralCode","customConfig","project","_this$config$authenti","isSilk","isWaaP","connected","uiMessageManager","currentAccount","walletConnectProvider","persistedMethods","internalEventEmitter","authenticationMethods","includes","initializeWalletConnect","login","_assertThisInitialized","logout","getLoginMethod","portal","requestEmail","requestSBT","orcid","enable","toggleDarkMode","silkRequest","waaPRequest","emit","SILK_METHOD","show_modal","hide_modal","newAccount","set_points_referral_code","set_project","set_custom_config","_SilkWalletConnect$ge","_this4","Object","keys","JSON_RPC_METHOD","attemptAutoConnect","autoConnectResult","_typedData$domain","Array","isArray","typedData","JSON","parse","stringify","primaryType","domain","verifyingContract","message","_unused","isSafeTransaction","eth_signTypedData_v4","rpcMethodRequiresUI","_temp3","wallet_switchEthereumChain","wallet_addEthereumChain","_args$params","chainId","_temp2","accounts","_args$params2","_args$params3","length","_args$params4","warn","customProvider","_temp8","provider","ethereum","providerWalletName","isMetaMask","isApexWallet","isAvalanche","isBitKeep","isBlockWallet","isMathWallet","isOkxWallet","isOKExWallet","isOneInchIOSWallet","isOneInchAndroidWallet","isOpera","isPortal","isRabby","isDefiant","isTokenPocket","isTokenary","isZerion","_this5","localStorage","setItem","setupWaaP","setupInjectedWallet","_temp6","_temp5","setupWalletConnect","_temp4","open","view","_temp7","_this5$config$authent","_this6","_temp0","cleanupInvalidLoginState","_temp9","disconnect","removeItem","silk","waap","_provider$connected","_provider$on$bind","_provider$on","_provider$removeListe","_provider$removeListe2","injectedProvider","on","removeListener","_provider$on$bind2","_provider$on2","_provider$removeListe3","_provider$removeListe4","setupAutoConnectInjected","_provider$isConnected","_provider$on$bind3","_provider$on3","_provider$removeListe5","_provider$removeListe6","setupAutoConnectWalletConnect","_provider$on$bind4","_provider$on4","_provider$removeListe7","_provider$removeListe8","_exit","_this7","auto_conn","loginMethod","_temp14","_temp13","_provider$request","_temp10","_temp12","_SilkWalletConnect$ge2","_window$ethereum$requ","_temp1","_result2","stored","getItem","_this8","safe","_this9","_this0","feature","operation","payload","_this1","methodName","gastank_get_settings","customization_get","gastank_update_settings","customization_update","gastank_topup","project_init","_this10","silk_requestEmail","_this11","silk_requestSbt","NEW_IFRAME_CONTAINER_ID","NEW_IFRAME_WRAPPER_ID","NEW_IFRAME_ID","getIframeContainer","getElementById","getIframeWrapper","iframeContainerId","iframeWrapperId","iframeId","initSilk","container","createElement","style","position","top","left","right","bottom","width","height","display","alignItems","justifyContent","backgroundColor","zIndex","closeSvgBlob","Blob","closeSvgUrl","URL","createObjectURL","closeErrorSvgBlob","closeErrorSvgUrl","closeButton","img","src","alt","all","cursor","appendChild","onclick","iframeWrapper","padding","margin","iframe","handleIframeMessage","contentHeight","contentWidth","Number","isFinite","Math","floor","__silkCleanup","border","borderRadius","background","createSilkIframe","Error","walletConnectProjectId","silkEthereumProvider","contentWindow","initWaaP","EthereumProviderExtension","sendToExtension"],"mappings":"28BAoCM,ICzBDA,EDyBCC,eAAoB,WAIxB,SAAAA,EAAYC,EAAsBC,GAAmBC,KAH7CF,aAA8B,KAAIE,KAClCC,kBAGN,EAAAD,KAAKF,aAAeA,EACpBE,KAAKC,aAAeF,EAChBG,EAAAA,4BACAC,EAAAA,oBACN,CAAC,IAAAC,EAAAP,EAAAQ,UA2GA,OA3GAD,EAKDE,qBAAA,SAAqBC,GACnBP,KAAKF,aAAcU,YACjB,CACEC,OAAQ,OACRC,YAAaC,oBAAkBC,aAC/BL,KAAAA,GAEFP,KAAKC,aAET,EAACG,EAEDS,sBAAA,WACEb,KAAKM,qBAAqBQ,EAAAA,kBAAkBC,MAC9C,EAACX,EAEDY,wBAAA,WACEhB,KAAKM,qBAAqBQ,EAAiBA,kBAACG,QAC9C,EAACb,EAMDc,WAAA,WAAU,IAAAC,EACRnB,KAAA,OAAW,IAAAoB,QAAc,SAACC,EAASC,GACjCC,WAAW,WAAM,OAAAD,EAAO,yBAAyB,EAAE,KAWnDE,OAAOC,iBAAiB,UAVH,SAAfC,EAAgBC,GAEI,SAAtBA,EAAMpB,KAAKE,QACXkB,EAAMpB,KAAKG,cAAgBC,EAAAA,kBAAkBC,cAC7Ce,EAAMpB,KAAKA,OAASO,EAAiBA,kBAACC,QAEtCS,OAAOI,oBAAoB,UAAWF,GACtCL,IAEJ,GAEAF,EAAKN,uB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,EAAK+H,gBAAgB,CACzB3T,OAAQgH,EAAWA,YAACM,kBACpBrH,OAAQ,CAAC2L,EAAKxN,WACdJ,KACJ,aAAA,CAAC,MAAAE,GAAA,OAAAlB,QAAAE,OAAAgB,EAAA,CAAA,EAAAlC,EAEY2S,KAAI,WAAA,IACf,OAAA3R,QAAAC,QAAOrB,KAAK+X,gBAAgB,CAAE3T,OAAQgH,EAAWA,YAAC2H,OACpD,CAAC,MAAAzQ,GAAAlB,OAAAA,QAAAE,OAAAgB,EAAA,CAAA,EAAAwV,CAAA,CAtFDnU,CAAQG,EAAYA"}
|
|
1
|
+
{"version":3,"file":"index.js","sources":["../src/lib/WalletMessageManager.ts","../src/lib/UIMessageManager.ts","../src/lib/provider/requests.ts","../src/lib/provider/utils.ts","../src/lib/WalletConnect.ts","../src/lib/provider/EthereumProvider.ts","../src/ui/WaapComponent.ts","../src/ui/index.ts","../src/lib/provider/EthereumProviderExtension.ts"],"sourcesContent":["/**\n * WalletMessageManager handles messages between the wallet (in the Silk iframe)\n * and the wallet SDK (in the top frame). It is used by EthereumProvider\n * to communicate with the wallet.\n */\nimport {\n SilkRequest,\n SilkResponse,\n SILK_MESSAGE_TYPE,\n SILK_METHOD,\n SILK_NOTIFICATION,\n SilkNotificationData,\n generateMessageId\n} from '@human.tech/waap-interface-core'\n\nimport {\n silkWalletAppOrigin2,\n silkWalletAppOrigin2Staging\n} from '@human.tech/waap-constants'\n\ntype PostSilkRequestArgs = {\n method: keyof typeof SILK_METHOD\n params: any[]\n interactionRequired: boolean\n}\n\n/**\n * Listener interface for WalletMessageManager\n */\ninterface MessageListenerConfig {\n handleResponse: (response: SilkResponse) => void\n handleRequest: (request: SilkRequest) => void\n onReceiveConnectNotif?: () => void\n onAccountChanged?: (newAccount: string) => void\n}\n\nclass WalletMessageManager {\n private iframeWindow: Window | null = null\n private walletOrigin: string\n\n constructor(iframeWindow: Window, useStaging: boolean) {\n this.iframeWindow = iframeWindow\n this.walletOrigin = useStaging\n ? silkWalletAppOrigin2Staging\n : silkWalletAppOrigin2\n }\n\n /**\n * Post a Silk notification to the given iframeWindow\n */\n postSilkNotification(data: SilkNotificationData) {\n this.iframeWindow!.postMessage(\n {\n target: 'silk' as const,\n messageType: SILK_MESSAGE_TYPE.notification,\n data\n },\n this.walletOrigin\n )\n }\n\n postReadyNotification() {\n this.postSilkNotification(SILK_NOTIFICATION.ready)\n }\n\n postConnectNotification() {\n this.postSilkNotification(SILK_NOTIFICATION.connect)\n }\n\n /**\n * Post a 'ready' notification to the iframe, and wait\n * for the iframe to respond with a 'ready' notification.\n */\n pingIframe() {\n return new Promise<void>((resolve, reject) => {\n setTimeout(() => reject('Wallet ping timed out.'), 10000)\n const eventHandler = (event: MessageEvent) => {\n if (\n event.data.target === 'silk' &&\n event.data.messageType === SILK_MESSAGE_TYPE.notification &&\n event.data.data === SILK_NOTIFICATION.ready\n ) {\n window.removeEventListener('message', eventHandler)\n resolve()\n }\n }\n window.addEventListener('message', eventHandler)\n this.postReadyNotification()\n })\n }\n\n /**\n * Post a SilkRequest to the iframeWindow. Don't wait for a response.\n */\n async postSilkRequest(req: PostSilkRequestArgs) {\n const baseRequest = {\n ...req,\n target: 'silk' as const,\n messageType: SILK_MESSAGE_TYPE.request as const\n }\n const id = await generateMessageId(baseRequest)\n this.iframeWindow!.postMessage({ ...baseRequest, id }, this.walletOrigin)\n return id\n }\n\n /**\n * Add a message listener to the window in which this is called (which should be the top frame).\n * It handles all messages from the Silk iframe posted to the top frame.\n * @param config - Configuration that includes callbacks for handling specific messages.\n */\n addListener(config: MessageListenerConfig) {\n const {\n handleResponse,\n handleRequest,\n onReceiveConnectNotif,\n onAccountChanged\n } = config\n\n window.addEventListener('message', (event) => {\n // Note: It is extremely important that NODE_ENV be set properly in production\n try {\n const origin =\n typeof process !== 'undefined' &&\n process.env &&\n process.env.NODE_ENV === 'test'\n ? 'http://127.0.0.1:3000'\n : event.origin\n\n if (origin !== this.walletOrigin) {\n return\n }\n } catch (error) {\n if (event.origin !== this.walletOrigin) {\n return\n }\n }\n\n if (event.data?.messageType === SILK_MESSAGE_TYPE.request) {\n handleRequest(event.data as SilkRequest)\n } else if (event.data?.messageType === SILK_MESSAGE_TYPE.response) {\n handleResponse(event.data as SilkResponse)\n } else if (event.data?.messageType === SILK_MESSAGE_TYPE.notification) {\n if (event.data?.data === SILK_NOTIFICATION.connect) {\n onReceiveConnectNotif?.()\n } else if (\n event.data?.data?.type === SILK_NOTIFICATION.account_changed &&\n onAccountChanged\n ) {\n onAccountChanged(event.data.data.account)\n }\n }\n })\n }\n}\n\nexport { WalletMessageManager, PostSilkRequestArgs }\nexport default WalletMessageManager\n","/**\n * UIMessageManager emits events whose intended recipient is the UI\n * of the silk-wallet-sdk. It is used by EthereumProvider to\n * communicate with the UI.\n *\n * Note that the UI part of silk-wallet-sdk is not the Silk\n * website but rather the actual iframe tag that gets embedded\n * in the host site.\n */\nimport { EventEmitter } from \"events\";\n\nenum UI_EVENT_NAMES {\n show_modal = \"show_modal\",\n hide_modal = \"hide_modal\",\n}\n\nclass UIMessageManager extends EventEmitter {\n constructor() {\n super();\n }\n}\n\nexport { UI_EVENT_NAMES, UIMessageManager };\nexport default UIMessageManager;\n","import { EventEmitter } from 'events'\nimport { JSON_RPC_METHOD, SilkResponse } from '@human.tech/waap-interface-core'\nimport { rpcMethodRequiresUI } from '@human.tech/waap-constants'\nimport WalletMessageManager from '../WalletMessageManager.js'\nimport { RequestArguments } from './types.js'\n\n/**\n * Send request to wallet in iframe, and upon receiving the wallet's response\n * or error, hide modal and return wallet's response or throw wallet's error.\n */\nasync function handleWalletRequestAndResponse(\n args: RequestArguments,\n interactionRequired: boolean,\n walletMessageManager: WalletMessageManager,\n internalProviderEventEmitter: EventEmitter\n) {\n const method = args.method as JSON_RPC_METHOD\n const params = args.params as any[]\n\n // Send request to wallet in iframe\n const id = await walletMessageManager.postSilkRequest({\n method,\n params,\n interactionRequired\n })\n // Return wallet's response\n return new Promise((resolve, reject) => {\n // setTimeout(() => reject(\"Request timed out\"), 60 * 1000);\n internalProviderEventEmitter.once(id, (response: SilkResponse) => {\n // We check for error first because some RPC methods return null if they are successful\n if (response.error) reject(response.error)\n else resolve(response.data)\n })\n })\n}\n\nexport { rpcMethodRequiresUI, handleWalletRequestAndResponse }\n","import { CustomConfig } from '@human.tech/waap-interface-core'\n\nexport function isMetaMask(provider: any) {\n if (!provider?.isMetaMask) return false\n // Brave tries to make itself look like MetaMask\n // Could also try RPC `web3_clientVersion` if following is unreliable\n // if (provider.isBraveWallet && !provider._events && !provider._state) {\n // return false\n // }\n if (provider.isApexWallet) return false\n if (provider.isAvalanche) return false\n if (provider.isBitKeep) return false\n if (provider.isBlockWallet) return false\n if (provider.isMathWallet) return false\n if (provider.isOkxWallet || provider.isOKExWallet) return false\n if (provider.isOneInchIOSWallet || provider.isOneInchAndroidWallet) {\n return false\n }\n if (provider.isOpera) return false\n if (provider.isPortal) return false\n if (provider.isRabby) return false\n if (provider.isDefiant) return false\n if (provider.isTokenPocket) return false\n if (provider.isTokenary) return false\n if (provider.isZerion) return false\n return true\n}\n\nexport function isSafeTransaction(params?: unknown[] | object): boolean {\n try {\n if (!params || !Array.isArray(params)) return false\n\n // For eth_signTypedData_v4, params[1] contains the typed data\n const typedData = JSON.parse(\n typeof params[1] === 'string' ? params[1] : JSON.stringify(params[1])\n )\n\n // Check if it's a Safe transaction by verifying:\n // 1. Primary type is 'SafeTx'\n // 2. Has verifyingContract in domain (Safe address)\n // 3. Has required SafeTx fields in message\n return (\n typedData.primaryType === 'SafeTx' &&\n typedData.domain?.verifyingContract !== undefined &&\n typedData.message &&\n 'to' in typedData.message &&\n 'value' in typedData.message &&\n 'safeTxGas' in typedData.message &&\n 'baseGas' in typedData.message &&\n 'gasPrice' in typedData.message &&\n 'nonce' in typedData.message\n )\n } catch {\n return false\n }\n}\n\nexport const defaultConfig: CustomConfig = {\n styles: {\n darkMode: false\n }\n}\n","import { EthersAdapter } from '@reown/appkit-adapter-ethers'\n\nexport class SilkWalletConnect {\n private static instance: any = null\n private static projectId: string | undefined = undefined\n // Ethereum, Optimism, Gnosis, Polygon, Base, Avalanche, Arbitrum, Celo, Base Sepolia, Sepolia\n private static chains: number[] = [\n 1, 10, 100, 137, 8453, 43114, 42161, 42220, 84532, 11155111\n ]\n // private static optionalChains: AppKitNetwork[]\n\n /**\n * Set the WalletConnect project ID programmatically\n * Use this if environment variables aren't working in your setup\n *\n * @param id - The WalletConnect project ID to use\n */\n static setProjectId(id: string) {\n this.projectId = id\n }\n\n // /**\n // * Set the optional chains to use for WalletConnect\n // *\n // * @param chains - The optional chains to use (number[])\n // */\n // static setOptionalChains(chains: AppKitNetwork[]) {\n // SilkWalletConnect.optionalChains = chains\n // }\n\n static getProjectIdFromEnv() {\n try {\n // Check if process and process.env exist.\n if (typeof process !== 'undefined' && process.env) {\n // List of common env variable names to check\n return (\n process.env.NEXT_PUBLIC_WALLET_CONNECT_PROJECT_ID ||\n process.env.VITE_WALLET_CONNECT_PROJECT_ID ||\n process.env.REACT_APP_WALLET_CONNECT_PROJECT_ID ||\n process.env.WALLET_CONNECT_PROJECT_ID\n ) // Generic fallback\n }\n } catch (error) {\n // Silently fail if process is not defined.\n // This is expected in a pure browser environment.\n return undefined\n }\n return undefined\n }\n\n static async getInstance() {\n // Skip initialization if not in browser environment\n if (typeof window === 'undefined' || typeof document === 'undefined') {\n return null\n }\n // Dynamically import AppKit only in browser environment\n const { createAppKit } = await import('@reown/appkit')\n const {\n mainnet,\n sepolia,\n optimism,\n arbitrum,\n optimismGoerli,\n polygon,\n gnosis,\n avalanche,\n aurora,\n fantom,\n base,\n celo\n } = await import('@reown/appkit/networks')\n\n try {\n // // 2. Create your application's metadata object\n const metadata = {\n name: 'Human Wallet',\n description:\n 'Silk lets you create human keys for web3 wallets that are recoverable with private identity proofs and secured by zero trust protocols.',\n url: window.location.origin, // origin must match your domain & subdomain\n icons: [\n 'https://imagedelivery.net/_aTEfDRm7z3tKgu9JhfeKA/f11f5753-616a-4aa0-2aee-9b75befea700/sm'\n ]\n }\n\n // // Check for project ID in multiple places, in order of precedence\n const projectId = this.projectId || this.getProjectIdFromEnv()\n\n if (!projectId) {\n console.error(\n 'WalletConnect project ID not found. Please set it using one of these methods:\\n' +\n '1. Pass walletConnectProjectId when calling initSilk\\n' +\n '2. Call SilkWalletConnect.setProjectId(\"your-project-id\")\\n' +\n '3. Set WALLET_CONNECT_PROJECT_ID (NEXT_PUBLIC_WALLET_CONNECT_PROJECT_ID for Next projects) environment variable'\n )\n return null\n }\n\n // Set it again in case it comes from env\n this.projectId = projectId\n\n if (!this.instance) {\n this.instance = createAppKit({\n adapters: [new EthersAdapter()],\n projectId,\n metadata,\n networks: [\n // @ts-ignore\n mainnet,\n sepolia,\n arbitrum,\n optimism,\n polygon,\n gnosis,\n avalanche,\n aurora,\n fantom,\n base,\n celo\n ],\n features: {\n socials: false,\n email: false\n }\n })\n }\n\n return this.instance\n } catch (error) {\n console.error('Error importing or initializing WalletConnect:', error)\n return null\n }\n }\n\n static async listenToAccountChangeEvent() {\n await new Promise<void>((resolve) => {\n const unsubscribe = this.instance.subscribeAccount(\n (accountState: any) => {\n if (accountState?.isConnected) {\n resolve()\n }\n }\n )\n })\n }\n\n /**\n * Wait for WalletConnect to be properly initialized and connected\n * @returns Promise<boolean> - true if connected, false if timeout reached\n */\n static async waitForReadyAndCheckConnection(): Promise<boolean> {\n if (!this.instance) {\n return false\n }\n\n let isConnected = false\n let attempts = 0\n const maxAttempts = 15 // Maximum 15 attempts\n\n while (!isConnected && attempts < maxAttempts) {\n // Use shorter delays initially, then longer ones\n const delay = attempts < 5 ? 500 : 1000 // 500ms for first 5 attempts, then 1s\n await new Promise((resolve) => setTimeout(resolve, delay))\n\n isConnected = this.instance.getIsConnectedState()\n attempts++\n console.log(\n `WalletConnect connection check attempt ${attempts}: ${isConnected}`\n )\n }\n\n return isConnected\n }\n\n /**\n * Check if WalletConnect is currently connected (immediate check, no waiting)\n * @returns boolean - true if connected, false otherwise\n */\n static isConnected(): boolean {\n return this.instance?.getIsConnectedState() ?? false\n }\n\n /**\n * Get the wallet provider from the WalletConnect instance\n * @returns The wallet provider or null if not available\n */\n static getWalletProvider(): any {\n return this.instance?.getWalletProvider() ?? null\n }\n}\n","/**\n * A Ethereum provder API (from EIP 1193) for Silk.\n * https://eips.ethereum.org/EIPS/eip-1193\n */\n\n/**\n * Resources:\n * - EIP-2255: Wallet Permissions System: https://eips.ethereum.org/EIPS/eip-2255\n */\nimport { EventEmitter } from 'events'\nimport {\n SILK_METHOD,\n JSON_RPC_METHOD,\n SilkRequest,\n SilkResponse,\n CustomConfig,\n CredentialType,\n ProjectConfig\n} from '@human.tech/waap-interface-core'\nimport {\n EthereumProviderInterface,\n LoginResponse,\n RequestArguments,\n SilkEthereumProviderInterface\n} from './types.js'\nimport WalletMessageManager from '../WalletMessageManager.js'\nimport { UIMessageManager, UI_EVENT_NAMES } from '../UIMessageManager.js'\nimport {\n rpcMethodRequiresUI,\n handleWalletRequestAndResponse\n} from './requests.js'\nimport { defaultConfig, isMetaMask, isSafeTransaction } from './utils.js'\nimport { SilkWalletConnect } from '../WalletConnect.js'\n\nclass EthereumProvider\n extends EventEmitter\n implements SilkEthereumProviderInterface\n{\n public readonly isSilk = true\n public readonly isWaaP = true\n public connected = false\n public walletMessageManager: WalletMessageManager\n public uiMessageManager: UIMessageManager\n public config: CustomConfig\n private currentAccount: string | null = null\n private walletConnectProvider: any = null\n private persistedMethods: {\n login: () => Promise<LoginResponse>\n logout: () => Promise<unknown>\n getLoginMethod: () => LoginResponse\n walletMessageManager: WalletMessageManager\n uiMessageManager: UIMessageManager\n internalEventEmitter: EventEmitter\n silkRequest: (args: RequestArguments) => Promise<unknown>\n waaPRequest: (args: RequestArguments) => Promise<unknown>\n portal: (\n feature: 'gastank' | 'customization' | 'project',\n operation: 'get' | 'update' | 'topup' | 'init',\n payload?: any\n ) => Promise<unknown>\n requestEmail: () => Promise<unknown>\n requestSBT: (type: CredentialType) => Promise<unknown>\n orcid: () => Promise<unknown>\n enable: () => Promise<unknown>\n isConnected: () => boolean\n toggleDarkMode: () => Promise<void>\n }\n\n /**\n * We use the internalEventEmitter to emit as events\n * Silk messages posted to the window.\n */\n public internalEventEmitter = new EventEmitter()\n\n /**\n * @param iframeWindow - The contentWindow of the iframe of the Silk website.\n * @param referralCode - Silk points referral code\n * @param customConfig - Silk custom UI configuration\n * @param project - Silk project configuration\n * @param useStaging - Whether to use the staging environment\n * @param forceIframe - Whether to force the iframe to be used (useful for waap-builder)\n */\n constructor(\n iframeWindow: Window,\n referralCode?: string,\n customConfig?: CustomConfig,\n project?: ProjectConfig,\n useStaging?: boolean,\n forceIframe?: boolean\n ) {\n super()\n\n this.uiMessageManager = new UIMessageManager()\n this.walletMessageManager = new WalletMessageManager(\n iframeWindow!,\n !!useStaging\n )\n this.config = {\n ...defaultConfig,\n ...(customConfig || {}) // Override with customConfig if provided\n }\n\n // // Initialize WalletConnect provider if wallet authentication is enabled\n // if (this.config.authenticationMethods?.includes('wallet')) {\n // // Initialize asynchronously to avoid blocking the constructor\n // this.initializeWalletConnect().catch((error) => {\n // console.error('WalletConnect initialization failed:', error)\n // })\n // }\n\n this.persistedMethods = {\n login: this.login.bind(this),\n logout: this.logout.bind(this),\n getLoginMethod: this.getLoginMethod.bind(this),\n walletMessageManager: this.walletMessageManager,\n internalEventEmitter: this.internalEventEmitter,\n uiMessageManager: this.uiMessageManager,\n portal: this.portal.bind(this),\n requestEmail: this.requestEmail.bind(this),\n requestSBT: this.requestSBT.bind(this),\n orcid: this.orcid.bind(this),\n enable: this.enable.bind(this),\n isConnected: this.isConnected.bind(this),\n toggleDarkMode: this.toggleDarkMode.bind(this),\n // We leave this silkRequest separate and never changing so that\n // we can still call the original request method if needed no matter\n // the current provider\n silkRequest: this.request.bind(this),\n waaPRequest: this.request.bind(this)\n }\n\n // Set up message listeners for the WalletMessageManager\n this.walletMessageManager.addListener({\n onReceiveConnectNotif: () => {\n console.log('onReceiveConnectNotif')\n this.connected = true\n this.emit('connect')\n },\n handleResponse: (response: SilkResponse) =>\n this.internalEventEmitter.emit(response.id, response),\n handleRequest: (request: SilkRequest) => {\n if (request.method === SILK_METHOD.show_modal) {\n this.uiMessageManager.emit(UI_EVENT_NAMES.show_modal)\n } else if (request.method === SILK_METHOD.hide_modal) {\n this.uiMessageManager.emit(UI_EVENT_NAMES.hide_modal)\n }\n },\n onAccountChanged: (newAccount: string) => {\n // Handle account change events\n if (this.currentAccount !== newAccount) {\n this.currentAccount = newAccount\n\n // Emit accountsChanged event with an array containing the new account\n // This follows the MetaMask standard (EIP-1193)\n this.emit('accountsChanged', newAccount ? [newAccount] : [])\n }\n }\n })\n\n // Tell the iframe to set the referral code\n if (referralCode) {\n // Wait for iframe to load (if it hasn't already)\n this.walletMessageManager\n .pingIframe()\n .then(() => {\n return handleWalletRequestAndResponse(\n {\n method: SILK_METHOD.set_points_referral_code,\n params: [referralCode]\n },\n false,\n this.walletMessageManager,\n this.internalEventEmitter\n )\n })\n .catch((error) => {\n console.error('Error setting referral code in Silk iframe:', error)\n })\n }\n\n // Tell the iframe to set the project config\n if (project) {\n this.walletMessageManager.pingIframe().then(() => {\n return handleWalletRequestAndResponse(\n {\n method: SILK_METHOD.set_project,\n params: [project, window.location.origin]\n },\n false,\n this.walletMessageManager,\n this.internalEventEmitter\n )\n })\n }\n\n // Tell the iframe to set the custom config\n if (customConfig) {\n this.walletMessageManager\n .pingIframe()\n .then(() => {\n return handleWalletRequestAndResponse(\n {\n method: SILK_METHOD.set_custom_config,\n params: [customConfig]\n },\n false,\n this.walletMessageManager,\n this.internalEventEmitter\n )\n })\n .catch((error) => {\n console.error('Error setting custom config in Silk iframe:', error)\n })\n }\n\n if (forceIframe) {\n this.walletMessageManager\n .pingIframe()\n .then(() => {\n return handleWalletRequestAndResponse(\n {\n method: SILK_METHOD.force_iframe,\n params: [true]\n },\n false,\n this.walletMessageManager,\n this.internalEventEmitter\n )\n })\n .catch((error) => {\n console.error('Error forcing iframe in Silk iframe:', error)\n })\n }\n }\n\n private async initializeWalletConnect(): Promise<void> {\n try {\n this.walletConnectProvider = await SilkWalletConnect.getInstance()\n console.log('WalletConnect provider initialized')\n } catch (error) {\n console.error('Failed to initialize WalletConnect provider:', error)\n this.walletConnectProvider = null\n }\n }\n\n public async enable(): Promise<unknown> {\n return this.request({ method: 'eth_requestAccounts' })\n }\n\n public isConnected(): boolean {\n return this.connected\n }\n\n public async request(args: RequestArguments): Promise<unknown> {\n if (\n !Object.keys(JSON_RPC_METHOD).includes(\n args.method as keyof typeof JSON_RPC_METHOD\n )\n ) {\n return Promise.reject({ error: `Not implemented (${args.method})` })\n }\n\n // Attempt auto-connect for account-related methods\n const autoConnectResult = await this.attemptAutoConnect(args.method)\n if (autoConnectResult !== null) {\n return autoConnectResult\n }\n\n // Initial check if this is a Safe transaction (other check happens on wallet internal and on the BE)\n const isSafeTx = isSafeTransaction(args.params)\n\n /**\n * Security: Safe transactions must use eth_signTypedData_v4\n * - Safe contract only accepts EIP-712 signatures or direct hash signatures\n * - Attempting to disguise Safe transactions as regular transactions or using\n * different signing methods would fail because:\n * 1. Safe contract requires specific signature format\n * 2. Transaction simulation validates proper Safe context\n * 3. Signatures are cryptographically bound to actual transaction parameters\n */\n if (isSafeTx) {\n // Safe transactions must use eth_signTypedData_v4\n if (args.method !== JSON_RPC_METHOD.eth_signTypedData_v4) {\n return Promise.reject({\n error: 'Safe transactions must be signed using eth_signTypedData_v4'\n })\n }\n }\n\n // Wait for iframe to load (if it hasn't already)\n await this.walletMessageManager.pingIframe()\n\n const response = await handleWalletRequestAndResponse(\n args,\n rpcMethodRequiresUI(args.method as JSON_RPC_METHOD),\n this.walletMessageManager,\n this.internalEventEmitter\n )\n\n if (\n (args.method === JSON_RPC_METHOD.wallet_switchEthereumChain ||\n args.method === JSON_RPC_METHOD.wallet_addEthereumChain) &&\n response === null\n ) {\n this.emit(\n 'chainChanged',\n (args.params as { chainId: string }[])?.[0]?.chainId\n )\n\n // After switching chains, re-emit account info to ensure dApps (like Safe)\n // can re-establish the signer context on the new chain\n try {\n // Get current accounts to ensure we have the latest account info\n const accounts = (await this.request({\n method: 'eth_accounts'\n })) as string[]\n if (accounts && accounts.length > 0) {\n this.currentAccount = accounts[0]\n\n // Emit both accountsChanged and connect events to ensure dApps\n // (especially Safe protocol-kit) re-establish signer context\n this.emit('accountsChanged', accounts)\n this.emit('connect', {\n chainId: (args.params as { chainId: string }[])?.[0]?.chainId\n })\n\n console.log(\n '[EthereumProvider] Re-emitted accounts and connect after chain switch:',\n {\n accounts,\n chainId: (args.params as { chainId: string }[])?.[0]?.chainId\n }\n )\n }\n } catch (error) {\n console.warn(\n '[EthereumProvider] Failed to get accounts after chain switch:',\n error\n )\n // Fallback to current account if available\n if (this.currentAccount) {\n this.emit('accountsChanged', [this.currentAccount])\n // Also emit connect event for fallback\n this.emit('connect', {\n chainId: (args.params as { chainId: string }[])?.[0]?.chainId\n })\n }\n }\n }\n\n return response\n }\n\n public async login(\n customProvider?: EthereumProviderInterface\n ): Promise<LoginResponse> {\n // Skip if not in browser environment\n if (typeof window === 'undefined' || typeof document === 'undefined') {\n return null\n }\n\n // Use the class-level walletConnectProvider if available, otherwise initialize it\n if (\n this.config.authenticationMethods?.includes('wallet') &&\n !this.walletConnectProvider\n ) {\n await this.initializeWalletConnect()\n }\n\n const provider = customProvider || (window.ethereum as any)\n\n const providerWalletName =\n provider && isMetaMask(provider) ? 'MetaMask' : 'Browser Wallet'\n\n // Wait for iframe to load (if it hasn't already)\n await this.walletMessageManager.pingIframe()\n\n const response = await handleWalletRequestAndResponse(\n { method: SILK_METHOD.login, params: [providerWalletName] },\n true,\n this.walletMessageManager,\n this.internalEventEmitter\n )\n\n if (typeof response === 'string' && response.includes('waap')) {\n localStorage.setItem(`${window.location.origin}-connected`, 'waap')\n\n this.setupWaaP()\n }\n\n if (\n typeof response === 'string' &&\n response.includes('injected') &&\n provider\n ) {\n localStorage.setItem(`${window.location.origin}-connected`, 'injected')\n\n this.setupInjectedWallet(provider)\n }\n\n if (typeof response === 'string' && response.includes('walletconnect')) {\n localStorage.setItem(\n `${window.location.origin}-connected`,\n 'walletconnect'\n )\n\n if (!SilkWalletConnect.isConnected()) {\n await this.walletConnectProvider.open({ view: 'Connect' })\n\n await SilkWalletConnect.listenToAccountChangeEvent()\n }\n\n const provider = SilkWalletConnect.getWalletProvider()\n\n this.setupWalletConnect(provider)\n }\n\n return response as LoginResponse\n }\n\n public async logout(): Promise<unknown> {\n // Wait for iframe to load (if it hasn't already)\n await this.walletMessageManager.pingIframe()\n\n // Clear the stored login method\n this.cleanupInvalidLoginState()\n\n // Reset to Human Wallet state\n\n try {\n // Use the class-level walletConnectProvider if available\n if (this.walletConnectProvider) {\n await this.walletConnectProvider.disconnect()\n }\n } catch (error) {\n console.error('Error disconnecting from WalletConnect:', error)\n }\n\n return handleWalletRequestAndResponse(\n { method: SILK_METHOD.logout },\n false,\n this.walletMessageManager,\n this.internalEventEmitter\n )\n }\n\n private cleanupInvalidLoginState(): void {\n try {\n localStorage.removeItem(`${window.location.origin}-connected`)\n } catch (error) {\n // Ignore cleanup errors in case localStorage is not available\n console.warn('Could not clean up login state:', error)\n }\n }\n\n /**\n * Helper method to set up window.waap for WaaP\n */\n private setupWaaP(): void {\n const provider = {\n ...this.persistedMethods,\n isWaaP: true,\n request: this.request.bind(this)\n }\n // @ts-ignore\n window.silk = provider\n // @ts-ignore - Add WaaP alias\n window.waap = provider\n }\n\n /**\n * Helper method to set up window.silk for injected wallets (e.g., MetaMask)\n */\n private setupInjectedWallet(provider: any): void {\n const injectedProvider = {\n ...this.persistedMethods,\n ...provider,\n isSilk: true,\n connected: provider.connected ?? false,\n on: provider.on?.bind(provider) ?? (() => {}),\n removeListener: provider.removeListener?.bind(provider) ?? (() => {}),\n request: provider.request.bind(provider)\n }\n window.silk = injectedProvider\n // @ts-ignore - Add WaaP alias\n window.waap = injectedProvider\n }\n\n /**\n * Helper method to set up window.silk for WalletConnect\n */\n private setupWalletConnect(provider: any): void {\n const walletConnectProvider = {\n ...this.persistedMethods,\n ...provider,\n isSilk: true,\n connected: true,\n on: provider.on?.bind(provider) ?? (() => {}),\n removeListener: provider.removeListener?.bind(provider) ?? (() => {}),\n request: provider.request.bind(provider)\n }\n window.silk = walletConnectProvider\n // @ts-ignore - Add WaaP alias\n window.waap = walletConnectProvider\n }\n\n /**\n * Helper method to set up window.silk for auto-connect with injected wallets\n */\n private setupAutoConnectInjected(provider: any): void {\n const injectedProvider = {\n ...this.persistedMethods,\n ...provider,\n isSilk: false,\n // @ts-ignore\n connected: provider.isConnected?.() ?? false,\n // @ts-ignore\n on: provider.on?.bind(provider) ?? (() => {}),\n removeListener:\n // @ts-ignore\n provider.removeListener?.bind(provider) ?? (() => {}),\n // @ts-ignore\n request: provider.request.bind(provider)\n }\n window.silk = injectedProvider\n // @ts-ignore - Add WaaP alias\n window.waap = injectedProvider\n }\n\n /**\n * Helper method to set up window.silk for auto-connect with WalletConnect\n */\n private setupAutoConnectWalletConnect(provider: any): void {\n const walletConnectProvider = {\n ...this.persistedMethods,\n ...provider,\n isSilk: false,\n connected: true,\n on: provider.on?.bind(provider) ?? (() => {}),\n removeListener: provider.removeListener?.bind(provider) ?? (() => {}),\n request: provider.request.bind(provider)\n }\n window.silk = walletConnectProvider\n // @ts-ignore - Add WaaP alias\n window.waap = walletConnectProvider\n }\n\n /**\n * Attempts to auto-connect using previously stored login method\n * @param method - The RPC method being called\n * @returns Promise<unknown> if auto-connect succeeds, null if it should fall through to normal flow\n */\n private async attemptAutoConnect(method: string): Promise<unknown | null> {\n // Only attempt auto-connect for account-related methods\n if (method !== 'eth_requestAccounts' && method !== 'eth_accounts') {\n return null\n }\n\n this.walletMessageManager.pingIframe().then(async () => {\n await handleWalletRequestAndResponse(\n {\n method: SILK_METHOD.auto_conn,\n params: [window.location.origin]\n },\n false,\n this.walletMessageManager,\n this.internalEventEmitter\n )\n })\n\n // Use our robust getLoginMethod to check connection state\n const loginMethod = this.getLoginMethod()\n\n if (loginMethod === 'injected' && window.ethereum) {\n try {\n this.setupAutoConnectInjected(window.ethereum)\n\n // @ts-ignore\n return window.ethereum.request({\n method: 'eth_requestAccounts'\n })\n } catch (error) {\n // If injected wallet fails, clean up and fall through to normal flow\n console.warn('Injected wallet auto-connect failed:', error)\n this.cleanupInvalidLoginState()\n return null\n }\n } else if (loginMethod === 'walletconnect') {\n try {\n if (!this.walletConnectProvider) {\n this.walletConnectProvider = await SilkWalletConnect.getInstance()\n }\n\n // Wait for WalletConnect to be ready\n const isConnected =\n await SilkWalletConnect.waitForReadyAndCheckConnection()\n\n if (isConnected) {\n const provider = SilkWalletConnect.getWalletProvider()\n this.setupAutoConnectWalletConnect(provider)\n\n // Return the accounts from the active WalletConnect session\n return provider.request({\n method: 'eth_requestAccounts'\n })\n } else {\n console.log(\n 'WalletConnect not connected, cleaning up and falling through to normal flow'\n )\n // Clean up invalid WalletConnect state\n this.cleanupInvalidLoginState()\n return null\n }\n } catch (error) {\n // If WalletConnect fails, clean up and fall through to normal flow\n console.warn('WalletConnect auto-connect failed:', error)\n this.cleanupInvalidLoginState()\n return null\n }\n }\n\n // For 'human' login method or if auto-connect failed, fall through to normal Silk flow\n return null\n }\n\n public getLoginMethod(): LoginResponse {\n // Skip if not in browser environment\n if (typeof window === 'undefined' || typeof localStorage === 'undefined') {\n return null\n }\n\n try {\n const stored = localStorage.getItem(`${window.location.origin}-connected`)\n\n if (!stored) {\n return null\n }\n\n // Validate that stored value is a valid LoginResponse\n if (!['waap', 'human', 'injected', 'walletconnect'].includes(stored)) {\n // Invalid value in localStorage, clean it up\n this.cleanupInvalidLoginState()\n return null\n }\n\n // Verify the connection is actually still valid\n switch (stored) {\n case 'injected':\n // Check if injected wallet (e.g., MetaMask) is still available\n if (!window.ethereum) {\n // Browser wallet is no longer available, clean up\n this.cleanupInvalidLoginState()\n return null\n }\n return 'injected'\n\n case 'walletconnect':\n // Check if WalletConnect session is still active\n try {\n if (!SilkWalletConnect.isConnected()) {\n // WalletConnect session is no longer active, clean up\n this.cleanupInvalidLoginState()\n return null\n }\n return 'walletconnect'\n } catch (error) {\n // Error checking WalletConnect status, assume disconnected\n this.cleanupInvalidLoginState()\n return null\n }\n\n case 'waap':\n // For WaaP, we trust the localStorage value since the connection\n // state is managed by the Silk iframe. The actual connection verification\n // happens when eth_requestAccounts is called.\n return 'waap'\n\n case 'human':\n return 'human'\n\n default:\n // This shouldn't happen due to the validation above, but just in case\n this.cleanupInvalidLoginState()\n return null\n }\n } catch (error) {\n // Any unexpected error (localStorage access issues, etc.)\n console.warn('Error checking login method:', error)\n this.cleanupInvalidLoginState()\n return null\n }\n }\n\n public async toggleDarkMode(): Promise<void> {\n this.config.styles!.darkMode = !this.config.styles!.darkMode\n\n this.walletMessageManager\n .pingIframe()\n .then(() => {\n return handleWalletRequestAndResponse(\n {\n method: SILK_METHOD.set_custom_config,\n params: [this.config]\n },\n false,\n this.walletMessageManager,\n this.internalEventEmitter\n )\n })\n .catch((error) => {\n console.error('Error setting custom config in Silk iframe:', error)\n })\n }\n\n public async safe(): Promise<void> {\n this.walletMessageManager.pingIframe().then(() => {\n return handleWalletRequestAndResponse(\n { method: SILK_METHOD.safe },\n true,\n this.walletMessageManager,\n this.internalEventEmitter\n )\n })\n }\n\n public async orcid(): Promise<void> {\n this.walletMessageManager.pingIframe().then(() => {\n return handleWalletRequestAndResponse(\n { method: SILK_METHOD.orcid },\n true,\n this.walletMessageManager,\n this.internalEventEmitter\n )\n })\n }\n\n /**\n * INTERNAL METHOD: Gas tank administration operations\n * This method is ONLY accessible from the Dev Portal domain\n * It's not included in the public typing to hide it from regular dApps\n */\n public async portal(\n feature: 'gastank' | 'customization' | 'project',\n operation: 'get' | 'update' | 'topup' | 'init',\n payload?: any\n ): Promise<unknown> {\n // Removed this for now due to devPortalHostname constant being set as localhost for staging environment on SDK\n // Second validation happens on silk-wallet-internal\n // const reqHostname = new URL(window.location.origin).hostname\n\n // const devPortalHostname = new URL(silkDevPortalOrigin).hostname\n\n // console.log('req hostname: ', reqHostname)\n\n // console.log('devPortalHostName: ', devPortalHostname)\n\n // if (devPortalHostname !== reqHostname) {\n // return Promise.reject({\n // error:\n // 'Unauthorized: Gas tank admin functions are only available from the Dev Portal'\n // })\n // }\n\n // Wait for iframe to load (if it hasn't already)\n await this.walletMessageManager.pingIframe()\n\n let methodName: string\n switch (operation) {\n case 'get':\n methodName =\n feature === 'gastank'\n ? SILK_METHOD.gastank_get_settings\n : SILK_METHOD.customization_get\n break\n case 'update':\n methodName =\n feature === 'gastank'\n ? SILK_METHOD.gastank_update_settings\n : SILK_METHOD.customization_update\n break\n case 'topup':\n methodName = SILK_METHOD.gastank_topup\n break\n case 'init':\n methodName = SILK_METHOD.project_init\n break\n }\n\n // For update operations, mark as requiring user interaction for signing\n const interactionRequired =\n operation !== 'get' && feature !== 'customization'\n\n // Handle the request to the wallet\n return handleWalletRequestAndResponse(\n {\n method: methodName,\n params: [payload, window.location.origin]\n },\n interactionRequired, // Only open modal for update operations\n this.walletMessageManager,\n this.internalEventEmitter\n )\n }\n\n public async requestEmail(): Promise<unknown> {\n // Wait for iframe to load (if it hasn't already)\n await this.walletMessageManager.pingIframe()\n\n return handleWalletRequestAndResponse(\n { method: SILK_METHOD.silk_requestEmail },\n true,\n this.walletMessageManager,\n this.internalEventEmitter\n )\n }\n\n /**\n * Prompt the user to mint a Zeronym SBT.\n * @returns string or null - The address of the owner of the SBT, or null\n * if the user already minted the SBT.\n */\n public async requestSBT(type: CredentialType): Promise<unknown> {\n // Wait for iframe to load (if it hasn't already)\n await this.walletMessageManager.pingIframe()\n\n return handleWalletRequestAndResponse(\n {\n method: SILK_METHOD.silk_requestSbt,\n params: [type]\n },\n true,\n this.walletMessageManager,\n this.internalEventEmitter\n )\n }\n}\n\nexport { EthereumProvider }\n","/**\n * WaaP Component\n *\n * A custom HTML element that allows developers to control where the WaaP wallet\n * renders in their UI. When present, the wallet will render inside this component\n * instead of as a centered modal with backdrop.\n *\n * Usage in HTML:\n * ```html\n * <waap-wallet></waap-wallet>\n * ```\n *\n * Usage in React/JSX:\n * ```tsx\n * function App() {\n * return <waap-wallet style={{ width: '400px', height: '600px' }} />\n * }\n * ```\n */\n\n// Internal constants (not exported)\nconst WAAP_COMPONENT_TAG_NAME = 'waap-wallet'\nconst WAAP_COMPONENT_CONTAINER_ID = 'waap-component-container'\n\n/**\n * Check if we're in a browser environment\n */\nconst isBrowser =\n typeof window !== 'undefined' &&\n typeof document !== 'undefined' &&\n typeof HTMLElement !== 'undefined'\n\n/**\n * Custom HTML element for WaaP wallet\n * Only defined in browser environments to avoid SSR issues\n */\nlet WaapWalletElement: any\n\nif (isBrowser) {\n WaapWalletElement = class extends HTMLElement {\n constructor() {\n super()\n\n // Set default styles if not specified\n if (!this.style.display || this.style.display === '') {\n this.style.display = 'flex'\n this.style.alignItems = 'center'\n this.style.justifyContent = 'center'\n }\n\n if (!this.style.width || this.style.width === '') {\n this.style.width = '100%'\n }\n\n if (!this.style.height || this.style.height === '') {\n this.style.height = '100%'\n }\n\n // Add container ID for SDK to find it\n this.id = WAAP_COMPONENT_CONTAINER_ID\n }\n\n connectedCallback() {\n // Element has been added to the DOM\n this.setAttribute('data-waap-mounted', 'true')\n }\n\n disconnectedCallback() {\n // Element has been removed from the DOM\n this.removeAttribute('data-waap-mounted')\n }\n }\n\n // Auto-register the component when in browser\n if (\n typeof customElements !== 'undefined' &&\n !customElements.get(WAAP_COMPONENT_TAG_NAME)\n ) {\n customElements.define(WAAP_COMPONENT_TAG_NAME, WaapWalletElement)\n }\n} else {\n // Provide a dummy class for SSR environments\n WaapWalletElement = class {}\n}\n\n/**\n * Check if a WaaP component exists in the DOM (internal use)\n */\nexport function hasWaapComponent(): boolean {\n if (!isBrowser) return false\n\n return (\n !!document.getElementById(WAAP_COMPONENT_CONTAINER_ID) ||\n !!document.querySelector(WAAP_COMPONENT_TAG_NAME)\n )\n}\n\n/**\n * Get the WaaP component container element (internal use)\n */\nexport function getWaapComponentContainer(): HTMLElement | null {\n if (!isBrowser) return null\n\n return (\n document.getElementById(WAAP_COMPONENT_CONTAINER_ID) ||\n document.querySelector(WAAP_COMPONENT_TAG_NAME)\n )\n}\n\n/**\n * Export the custom element class for advanced use cases\n * Most users won't need this - just use <waap-wallet> in your HTML/JSX\n */\nexport { WaapWalletElement as WaaP }\n","import {\n silkWalletAppOrigin2,\n silkWalletAppOrigin2Staging\n} from '@human.tech/waap-constants'\nimport {\n InitSilkOptions,\n SilkEthereumProviderInterface\n} from '../lib/provider/types.js'\nimport { EthereumProvider } from '../lib/provider/EthereumProvider.js'\nimport { UI_EVENT_NAMES } from '../lib/UIMessageManager.js'\nimport { SilkWalletConnect } from 'lib/WalletConnect.js'\nimport { hasWaapComponent, getWaapComponentContainer } from './WaapComponent.js'\n\n// Container ID constants - supporting both old (silk-wallet) and new (waap-wallet) naming\nconst LEGACY_IFRAME_CONTAINER_ID = 'silk-wallet-iframe-container'\nconst LEGACY_IFRAME_WRAPPER_ID = 'silk-wallet-iframe-wrapper'\nconst LEGACY_IFRAME_ID = 'silk-wallet-iframe'\n\nconst NEW_IFRAME_CONTAINER_ID = 'waap-wallet-iframe-container'\nconst NEW_IFRAME_WRAPPER_ID = 'waap-wallet-iframe-wrapper'\nconst NEW_IFRAME_ID = 'waap-wallet-iframe'\n\n/**\n * Get the existing iframe container element, checking both old and new naming conventions\n * @returns HTMLElement | null\n */\nconst getIframeContainer = (): HTMLElement | null => {\n return (\n document.getElementById(NEW_IFRAME_CONTAINER_ID) ||\n document.getElementById(LEGACY_IFRAME_CONTAINER_ID)\n )\n}\n\n/**\n * Get the existing iframe wrapper element, checking both old and new naming conventions\n * @returns HTMLElement | null\n */\nconst getIframeWrapper = (): HTMLElement | null => {\n return (\n document.getElementById(NEW_IFRAME_WRAPPER_ID) ||\n document.getElementById(LEGACY_IFRAME_WRAPPER_ID)\n )\n}\n\n/**\n * Get the existing iframe element, checking both old and new naming conventions\n * @returns HTMLIFrameElement | null\n */\nconst getIframe = (): HTMLIFrameElement | null => {\n return (document.getElementById(NEW_IFRAME_ID) ||\n document.getElementById(LEGACY_IFRAME_ID)) as HTMLIFrameElement | null\n}\n\n// Default to new naming for new installations\nconst iframeContainerId = NEW_IFRAME_CONTAINER_ID\nconst iframeWrapperId = NEW_IFRAME_WRAPPER_ID\nconst iframeId = NEW_IFRAME_ID\n\n/**\n * Create iframe element with proper configuration\n */\nconst createIframeElement = (useStaging: boolean): HTMLIFrameElement => {\n const iframe = window.document.createElement('iframe')\n iframe.id = iframeId\n iframe.src = `${\n useStaging ? silkWalletAppOrigin2Staging : silkWalletAppOrigin2\n }/iframe`\n\n console.log('iframe.src: ', iframe.src)\n\n iframe.style.width = '100%'\n iframe.style.height = '100%'\n iframe.style.border = 'none'\n iframe.style.borderRadius = '24px'\n iframe.style.backgroundColor = 'transparent'\n iframe.style.background = 'transparent'\n iframe.style.padding = '0'\n iframe.style.margin = '0'\n\n return iframe\n}\n\n/**\n * Setup message listener for iframe size updates\n */\nconst setupIframeMessageListener = (\n useStaging: boolean,\n iframe: HTMLIFrameElement\n) => {\n const handleIframeMessage = (event: MessageEvent) => {\n const expectedOrigin = useStaging\n ? silkWalletAppOrigin2Staging\n : silkWalletAppOrigin2\n\n if (event.origin !== expectedOrigin) return\n if (!event.data || typeof event.data !== 'object') return\n if (event.data.type !== 'silk-iframe-size') return\n\n const contentHeight = event.data.height\n const contentWidth = event.data.width\n\n const maxDimension = 2000\n const minDimension = 50\n\n if (typeof contentHeight !== 'number' || typeof contentWidth !== 'number')\n return\n if (contentHeight < minDimension || contentHeight > maxDimension) return\n if (contentWidth < minDimension || contentWidth > maxDimension) return\n if (!Number.isFinite(contentHeight) || !Number.isFinite(contentWidth))\n return\n\n const iframeWrapper = getIframeWrapper()\n if (!iframeWrapper) return\n\n iframeWrapper.style.height = `${Math.floor(contentHeight)}px`\n iframeWrapper.style.width = `${Math.floor(contentWidth)}px`\n }\n\n window.addEventListener('message', handleIframeMessage)\n ;(iframe as any).__silkCleanup = () => {\n window.removeEventListener('message', handleIframeMessage)\n }\n}\n\n/**\n * Create iframe in custom component mode (no modal/backdrop)\n */\nconst createComponentModeIframe = (useStaging: boolean) => {\n const componentContainer = getWaapComponentContainer()\n if (!componentContainer) {\n throw new Error('WaaP component not found in DOM')\n }\n\n // Check if iframe already exists\n if (getIframe()) {\n return\n }\n\n // Create iframe wrapper\n const iframeWrapper = window.document.createElement('div')\n iframeWrapper.id = iframeWrapperId\n iframeWrapper.style.position = 'relative'\n iframeWrapper.style.display = 'flex'\n iframeWrapper.style.alignItems = 'center'\n iframeWrapper.style.justifyContent = 'center'\n iframeWrapper.style.padding = '0'\n iframeWrapper.style.margin = '0'\n iframeWrapper.style.height = '600px'\n iframeWrapper.style.width = '380px'\n\n // Create and configure iframe\n const iframe = createIframeElement(useStaging)\n setupIframeMessageListener(useStaging, iframe)\n\n // Set default dimensions\n setTimeout(() => {\n const wrapper = getIframeWrapper()\n if (wrapper) {\n wrapper.style.height = '600px'\n wrapper.style.width = '380px'\n }\n }, 100)\n\n iframeWrapper.appendChild(iframe)\n componentContainer.appendChild(iframeWrapper)\n}\n\n/**\n * Create iframe in modal mode (with backdrop) - default behavior\n */\nconst createModalModeIframe = (useStaging: boolean) => {\n // If iframe container is already on page, do nothing\n if (getIframeContainer()) {\n return\n }\n\n // Create modal container\n const container = window.document.createElement('div')\n container.id = iframeContainerId\n container.style.position = 'fixed'\n container.style.top = '0'\n container.style.left = '0'\n container.style.right = '0'\n container.style.bottom = '0'\n container.style.width = '100%'\n container.style.height = '100%'\n container.style.display = 'flex'\n container.style.alignItems = 'center'\n container.style.justifyContent = 'center'\n container.style.backgroundColor = 'rgba(0, 0, 0, 0.5)'\n container.style.zIndex = '99999'\n container.style.display = 'none'\n\n // Create iframe wrapper\n const iframeWrapper = window.document.createElement('div')\n iframeWrapper.id = iframeWrapperId\n iframeWrapper.style.position = 'relative'\n iframeWrapper.style.display = 'flex'\n iframeWrapper.style.alignItems = 'center'\n iframeWrapper.style.justifyContent = 'center'\n iframeWrapper.style.padding = '0'\n iframeWrapper.style.margin = '0'\n iframeWrapper.style.height = '600px'\n iframeWrapper.style.width = '380px'\n\n container.appendChild(iframeWrapper)\n\n // Create and configure iframe\n const iframe = createIframeElement(useStaging)\n setupIframeMessageListener(useStaging, iframe)\n\n // Set default dimensions\n setTimeout(() => {\n const wrapper = getIframeWrapper()\n if (wrapper) {\n wrapper.style.height = '600px'\n wrapper.style.width = '380px'\n }\n }, 100)\n\n iframeWrapper.appendChild(iframe)\n window.document.body.appendChild(container)\n}\n\n/**\n * Main function to create the WaaP iframe in either modal or component mode\n */\nconst createSilkIframe = (useStaging: boolean) => {\n // Check if custom component exists\n if (hasWaapComponent()) {\n createComponentModeIframe(useStaging)\n } else {\n createModalModeIframe(useStaging)\n }\n}\n\n// function warnStagingInit(useStaging: boolean) {\n// if (useStaging) {\n// console.log(\n// 'WARNING: Silk has been initialized to use the Silk staging environment. ' +\n// 'Silk staging is subject to rapid, unannounced changes, and is not ' +\n// 'recommended for production use or for storing large amounts of funds.'\n// )\n// }\n// }\n\n/**\n * @param referralCode - WaaP points referral code\n * @param customConfig - WaaP custom UI configuration\n * @param project - WaaP project configuration\n * @param useStaging - Whether to use the staging environment\n * @param walletConnectProjectId - WalletConnect project ID (only required when passing `wallet` to `authenticationMethods`)\n * @param walletConnectOptionalChains - Optional chains to use for WalletConnect\n */\n\nconst initWaaP = (\n params: InitSilkOptions = {}\n): SilkEthereumProviderInterface => {\n // warnStagingInit(!!params.useStaging)\n createSilkIframe(!!params.useStaging)\n\n const iframe = getIframe()\n if (!iframe) {\n throw new Error('WaaP iframe does not exist on page')\n }\n\n // Check if we're in component mode or modal mode\n const isComponentMode = hasWaapComponent()\n const container = getIframeContainer()\n const componentContainer = getWaapComponentContainer()\n const iframeWrapper = getIframeWrapper()\n\n // If walletConnectProjectId is provided, set it\n if (params.walletConnectProjectId) {\n SilkWalletConnect.setProjectId(params.walletConnectProjectId)\n }\n\n const { referralCode, config, project, forceIframe } = params\n\n // Create ethereum provider and attach it to window\n const contentWindow = iframe.contentWindow as Window\n const silkEthereumProvider = new EthereumProvider(\n contentWindow,\n referralCode,\n config || {},\n project || {},\n params.useStaging,\n forceIframe\n )\n\n // Track the current mode to detect changes\n let currentMode: 'modal' | 'component' = isComponentMode\n ? 'component'\n : 'modal'\n\n // Setup visibility handlers - check component mode dynamically when showing\n silkEthereumProvider.uiMessageManager.on(UI_EVENT_NAMES.show_modal, () => {\n // Re-check component mode each time (component might be added after init)\n const nowComponentMode = hasWaapComponent()\n const newMode = nowComponentMode ? 'component' : 'modal'\n const iframeWrapper = getIframeWrapper()\n\n // If mode changed, move iframe wrapper to new location\n if (newMode !== currentMode && iframeWrapper) {\n currentMode = newMode\n\n if (nowComponentMode) {\n // Move to component\n const componentContainer = getWaapComponentContainer()\n if (componentContainer) {\n componentContainer.appendChild(iframeWrapper)\n }\n } else {\n // Move back to modal container\n let modalContainer = getIframeContainer()\n if (!modalContainer) {\n // Create modal container if it doesn't exist\n modalContainer = window.document.createElement('div')\n modalContainer.id = iframeContainerId\n modalContainer.style.position = 'fixed'\n modalContainer.style.top = '0'\n modalContainer.style.left = '0'\n modalContainer.style.right = '0'\n modalContainer.style.bottom = '0'\n modalContainer.style.width = '100%'\n modalContainer.style.height = '100%'\n modalContainer.style.display = 'flex'\n modalContainer.style.alignItems = 'center'\n modalContainer.style.justifyContent = 'center'\n modalContainer.style.backgroundColor = 'rgba(0, 0, 0, 0.5)'\n modalContainer.style.zIndex = '99999'\n window.document.body.appendChild(modalContainer)\n }\n modalContainer.appendChild(iframeWrapper)\n }\n }\n\n const container = getIframeContainer()\n\n if (nowComponentMode && iframeWrapper) {\n // Component mode - show wrapper only\n iframeWrapper.style.display = 'flex'\n } else if (container) {\n // Modal mode - show container with backdrop\n container.style.display = 'flex'\n }\n })\n\n silkEthereumProvider.uiMessageManager.on(UI_EVENT_NAMES.hide_modal, () => {\n const isComponentMode = hasWaapComponent()\n const iframeWrapper = getIframeWrapper()\n const container = getIframeContainer()\n\n if (isComponentMode && iframeWrapper) {\n iframeWrapper.style.display = 'none'\n } else if (container) {\n container.style.display = 'none'\n }\n })\n\n // @ts-ignore\n window.silk = silkEthereumProvider\n // @ts-ignore - WaaP alias\n window.waap = silkEthereumProvider\n\n return silkEthereumProvider\n}\n\nexport { initWaaP }\n","/**\n * A Ethereum provder API (from EIP 1193) for Silk.\n * https://eips.ethereum.org/EIPS/eip-1193\n */\n\n/**\n * Resources:\n * - EIP-2255: Wallet Permissions System: https://eips.ethereum.org/EIPS/eip-2255\n */\nimport {\n CredentialType,\n CustomConfig,\n JSON_RPC_METHOD,\n SILK_METHOD\n} from '@human.tech/waap-interface-core'\nimport { EventEmitter } from 'events'\nimport { EthereumProviderInterface, RequestArguments } from './types.js'\nimport { defaultConfig } from './utils.js'\n\nclass EthereumProviderExtension\n extends EventEmitter\n implements EthereumProviderInterface\n{\n public readonly isSilk = true\n public connected = false\n public config: CustomConfig\n\n constructor(customConfig?: CustomConfig) {\n super()\n this.config = {\n ...defaultConfig,\n ...(customConfig || {})\n }\n }\n\n // Send a message to the background script via `chrome.runtime.sendMessage`\n sendToExtension(args: RequestArguments) {\n // Use window.postMessage to communicate with the content script\n return new Promise((resolve, reject) => {\n window.postMessage({ type: 'FROM_PAGE', request: args }, '*')\n window.addEventListener('message', (event) => {\n if (event.data.type === 'FROM_EXTENSION') {\n if (event.data.error) reject(event.data.error)\n else resolve(event.data.result)\n }\n })\n })\n }\n\n // EIP-1193 `request` method implementation\n public async request(args: RequestArguments): Promise<unknown> {\n if (!Object.keys(JSON_RPC_METHOD).includes(args.method)) {\n return Promise.reject({ error: `Not implemented (${args.method})` })\n }\n\n const response = await this.sendToExtension(args)\n\n if (\n (args.method === JSON_RPC_METHOD.wallet_switchEthereumChain ||\n args.method === JSON_RPC_METHOD.wallet_addEthereumChain) &&\n response === null\n ) {\n this.emit(\n 'chainChanged',\n (args.params as { chainId: string }[])?.[0]?.chainId\n )\n }\n\n return response\n }\n\n // Enable method that dApps use to request accounts\n public async enable(): Promise<unknown> {\n return this.request({ method: 'eth_requestAccounts' })\n }\n\n // Check if the provider is connected\n public isConnected(): boolean {\n return this.connected\n }\n\n // Example of a custom method to handle login requests\n public async login(): Promise<unknown> {\n return this.sendToExtension({ method: SILK_METHOD.login })\n }\n\n // Example of requesting an SBT (Soulbound Token)\n public async requestSBT(type: CredentialType): Promise<unknown> {\n return this.sendToExtension({\n method: SILK_METHOD.silk_requestSbt,\n params: [type]\n })\n }\n\n // Example of toggling dark mode as part of custom config\n public async toggleDarkMode(): Promise<void> {\n this.config.styles!.darkMode = !this.config.styles!.darkMode\n\n await this.sendToExtension({\n method: SILK_METHOD.set_custom_config,\n params: [this.config]\n })\n }\n\n public async safe(): Promise<unknown> {\n return this.sendToExtension({ method: SILK_METHOD.safe })\n }\n}\n\nexport { EthereumProviderExtension }\n"],"names":["UI_EVENT_NAMES","WalletMessageManager","iframeWindow","useStaging","this","walletOrigin","silkWalletAppOrigin2Staging","silkWalletAppOrigin2","_proto","prototype","postSilkNotification","data","postMessage","target","messageType","SILK_MESSAGE_TYPE","notification","postReadyNotification","SILK_NOTIFICATION","ready","postConnectNotification","connect","pingIframe","_this","Promise","resolve","reject","setTimeout","window","addEventListener","eventHandler","event","removeEventListener","postSilkRequest","req","_this2","baseRequest","_extends","request","generateMessageId","then","id","e","addListener","config","_this3","handleResponse","handleRequest","onReceiveConnectNotif","onAccountChanged","_event$data","_event$data2","_event$data3","process","origin","error","response","_event$data4","_event$data5","type","account_changed","account","UIMessageManager","_EventEmitter","call","_inheritsLoose","EventEmitter","handleWalletRequestAndResponse","args","interactionRequired","walletMessageManager","internalProviderEventEmitter","method","params","once","defaultConfig","styles","darkMode","pact","state","value","s","_Pact","o","_settle","bind","v","observer","onFulfilled","onRejected","result","callback","thenable","SilkWalletConnect","setProjectId","projectId","getProjectIdFromEnv","env","NEXT_PUBLIC_WALLET_CONNECT_PROJECT_ID","VITE_WALLET_CONNECT_PROJECT_ID","REACT_APP_WALLET_CONNECT_PROJECT_ID","WALLET_CONNECT_PROJECT_ID","getInstance","document","_interopNamespace","require","_ref","createAppKit","_ref2","mainnet","sepolia","optimism","arbitrum","polygon","gnosis","avalanche","aurora","fantom","base","celo","metadata","name","description","url","location","icons","instance","adapters","EthersAdapter","networks","features","socials","email","console","listenToAccountChangeEvent","subscribeAccount","accountState","isConnected","waitForReadyAndCheckConnection","attempts","_temp","_for","delay","getIsConnectedState","log","_this$instance$getIsC","_this$instance","getWalletProvider","_this$instance$getWal","_this$instance2","_catch","body","recover","undefined","chains","EthereumProvider","referralCode","customConfig","project","forceIframe","isSilk","isWaaP","connected","uiMessageManager","currentAccount","walletConnectProvider","persistedMethods","internalEventEmitter","login","_assertThisInitialized","logout","getLoginMethod","portal","requestEmail","requestSBT","orcid","enable","toggleDarkMode","silkRequest","waaPRequest","emit","SILK_METHOD","show_modal","hide_modal","newAccount","set_points_referral_code","set_project","set_custom_config","force_iframe","initializeWalletConnect","_SilkWalletConnect$ge","_this4","Object","keys","JSON_RPC_METHOD","includes","attemptAutoConnect","autoConnectResult","_typedData$domain","Array","isArray","typedData","JSON","parse","stringify","primaryType","domain","verifyingContract","message","_unused","isSafeTransaction","eth_signTypedData_v4","rpcMethodRequiresUI","_temp3","wallet_switchEthereumChain","wallet_addEthereumChain","_args$params","chainId","_temp2","accounts","_args$params2","_args$params3","length","_args$params4","warn","customProvider","_temp8","provider","ethereum","providerWalletName","isMetaMask","isApexWallet","isAvalanche","isBitKeep","isBlockWallet","isMathWallet","isOkxWallet","isOKExWallet","isOneInchIOSWallet","isOneInchAndroidWallet","isOpera","isPortal","isRabby","isDefiant","isTokenPocket","isTokenary","isZerion","_this5","localStorage","setItem","setupWaaP","setupInjectedWallet","_temp6","_temp5","setupWalletConnect","_temp4","open","view","_temp7","_this5$config$authent","authenticationMethods","_this6","_temp1","cleanupInvalidLoginState","_temp0","_temp9","disconnect","removeItem","silk","waap","_provider$connected","_provider$on$bind","_provider$on","_provider$removeListe","_provider$removeListe2","injectedProvider","on","removeListener","_provider$on$bind2","_provider$on2","_provider$removeListe3","_provider$removeListe4","setupAutoConnectInjected","_provider$isConnected","_provider$on$bind3","_provider$on3","_provider$removeListe5","_provider$removeListe6","setupAutoConnectWalletConnect","_provider$on$bind4","_provider$on4","_provider$removeListe7","_provider$removeListe8","_exit","_this7","auto_conn","loginMethod","_temp15","_temp14","_provider$request","_temp11","_temp13","_SilkWalletConnect$ge2","_window$ethereum$requ","_result2","stored","getItem","_this8","safe","_this9","_this0","feature","operation","payload","_this1","methodName","gastank_get_settings","customization_get","gastank_update_settings","customization_update","gastank_topup","project_init","_this10","silk_requestEmail","_this11","silk_requestSbt","WAAP_COMPONENT_TAG_NAME","WAAP_COMPONENT_CONTAINER_ID","isBrowser","HTMLElement","hasWaapComponent","getElementById","querySelector","getWaapComponentContainer","WaapWalletElement","_HTMLElement","style","display","alignItems","justifyContent","width","height","connectedCallback","setAttribute","disconnectedCallback","removeAttribute","_wrapNativeSuper","customElements","get","define","WaaP","NEW_IFRAME_CONTAINER_ID","NEW_IFRAME_WRAPPER_ID","NEW_IFRAME_ID","getIframeContainer","getIframeWrapper","getIframe","iframeContainerId","iframeWrapperId","iframeId","createIframeElement","iframe","createElement","src","border","borderRadius","backgroundColor","background","padding","margin","setupIframeMessageListener","handleIframeMessage","contentHeight","contentWidth","Number","isFinite","iframeWrapper","Math","floor","__silkCleanup","EthereumProviderExtension","sendToExtension","componentContainer","Error","position","wrapper","appendChild","createComponentModeIframe","container","top","left","right","bottom","zIndex","createModalModeIframe","isComponentMode","walletConnectProjectId","silkEthereumProvider","contentWindow","currentMode","nowComponentMode","newMode","modalContainer"],"mappings":"w6DAoCM,ICzBDA,EDyBCC,eAAoB,WAIxB,SAAAA,EAAYC,EAAsBC,GAAmBC,KAH7CF,aAA8B,KAAIE,KAClCC,kBAGN,EAAAD,KAAKF,aAAeA,EACpBE,KAAKC,aAAeF,EAChBG,EAAAA,4BACAC,EAAAA,oBACN,CAAC,IAA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,rpcMethodRequiresUI as n}from"@silk-wallet/silk-constants";export{rpcMethodRequiresUI}from"@silk-wallet/silk-constants";import{EventEmitter as i}from"events";import{SILK_MESSAGE_TYPE as a,SILK_NOTIFICATION as s,generateMessageId as o,SILK_METHOD as r,JSON_RPC_METHOD as l}from"@silk-wallet/silk-interface-core";export{SILK_METHOD,SILK_METHOD as WAAP_METHOD}from"@silk-wallet/silk-interface-core";import{EthersAdapter as c}from"@reown/appkit-adapter-ethers";function d(){return d=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var i in n)({}).hasOwnProperty.call(n,i)&&(e[i]=n[i])}return e},d.apply(null,arguments)}class h{constructor(n,i){this.iframeWindow=null,this.walletOrigin=void 0,this.iframeWindow=n,this.walletOrigin=i?e:t}postSilkNotification(e){this.iframeWindow.postMessage({target:"silk",messageType:a.notification,data:e},this.walletOrigin)}postReadyNotification(){this.postSilkNotification(s.ready)}postConnectNotification(){this.postSilkNotification(s.connect)}pingIframe(){return new Promise((e,t)=>{setTimeout(()=>t("Wallet ping timed out."),1e4);const n=t=>{"silk"===t.data.target&&t.data.messageType===a.notification&&t.data.data===s.ready&&(window.removeEventListener("message",n),e())};window.addEventListener("message",n),this.postReadyNotification()})}async postSilkRequest(e){const t=d({},e,{target:"silk",messageType:a.request}),n=await o(t);return this.iframeWindow.postMessage(d({},t,{id:n}),this.walletOrigin),n}addListener(e){const{handleResponse:t,handleRequest:n,onReceiveConnectNotif:i,onAccountChanged:o}=e;window.addEventListener("message",e=>{var r,l,c;try{if("undefined"!=typeof process&&process,e.origin!==this.walletOrigin)return}catch(t){if(e.origin!==this.walletOrigin)return}if((null==(r=e.data)?void 0:r.messageType)===a.request)n(e.data);else if((null==(l=e.data)?void 0:l.messageType)===a.response)t(e.data);else if((null==(c=e.data)?void 0:c.messageType)===a.notification){var d,h;(null==(d=e.data)?void 0:d.data)===s.connect?null==i||i():(null==(h=e.data)||null==(h=h.data)?void 0:h.type)===s.account_changed&&o&&o(e.data.data.account)}})}}var u;!function(e){e.show_modal="show_modal",e.hide_modal="hide_modal"}(u||(u={}));class g extends i{constructor(){super()}}async function m(e,t,n,i){const a=e.method,s=e.params,o=await n.postSilkRequest({method:a,params:s,interactionRequired:t});return new Promise((e,t)=>{i.once(o,n=>{n.error?t(n.error):e(n.data)})})}const w={styles:{darkMode:!1}};class p{static setProjectId(e){this.projectId=e}static getProjectIdFromEnv(){try{if("undefined"!=typeof process&&process.env)return process.env.NEXT_PUBLIC_WALLET_CONNECT_PROJECT_ID||process.env.VITE_WALLET_CONNECT_PROJECT_ID||process.env.REACT_APP_WALLET_CONNECT_PROJECT_ID||process.env.WALLET_CONNECT_PROJECT_ID}catch(e){return}}static async getInstance(){if("undefined"==typeof window||"undefined"==typeof document)return null;const{createAppKit:e}=await import("@reown/appkit"),{mainnet:t,sepolia:n,optimism:i,arbitrum:a,polygon:s,gnosis:o,avalanche:r,aurora:l,fantom:d,base:h,celo:u}=await import("@reown/appkit/networks");try{const g={name:"Human Wallet",description:"Silk lets you create human keys for web3 wallets that are recoverable with private identity proofs and secured by zero trust protocols.",url:window.location.origin,icons:["https://imagedelivery.net/_aTEfDRm7z3tKgu9JhfeKA/f11f5753-616a-4aa0-2aee-9b75befea700/sm"]},m=this.projectId||this.getProjectIdFromEnv();return m?(this.projectId=m,this.instance||(this.instance=e({adapters:[new c],projectId:m,metadata:g,networks:[t,n,a,i,s,o,r,l,d,h,u],features:{socials:!1,email:!1}})),this.instance):(console.error('WalletConnect project ID not found. Please set it using one of these methods:\n1. Pass walletConnectProjectId when calling initSilk\n2. Call SilkWalletConnect.setProjectId("your-project-id")\n3. Set WALLET_CONNECT_PROJECT_ID (NEXT_PUBLIC_WALLET_CONNECT_PROJECT_ID for Next projects) environment variable'),null)}catch(e){return console.error("Error importing or initializing WalletConnect:",e),null}}static async listenToAccountChangeEvent(){await new Promise(e=>{this.instance.subscribeAccount(t=>{null!=t&&t.isConnected&&e()})})}static async waitForReadyAndCheckConnection(){if(!this.instance)return!1;let e=!1,t=0;for(;!e&&t<15;){const n=t<5?500:1e3;await new Promise(e=>setTimeout(e,n)),e=this.instance.getIsConnectedState(),t++,console.log(`WalletConnect connection check attempt ${t}: ${e}`)}return e}static isConnected(){var e,t;return null!=(e=null==(t=this.instance)?void 0:t.getIsConnectedState())&&e}static getWalletProvider(){var e,t;return null!=(e=null==(t=this.instance)?void 0:t.getWalletProvider())?e:null}}p.instance=null,p.projectId=void 0,p.chains=[1,10,100,137,8453,43114,42161,42220,84532,11155111];class f extends i{constructor(e,t,n,a,s){var o;super(),this.isSilk=!0,this.isWaaP=!0,this.connected=!1,this.walletMessageManager=void 0,this.uiMessageManager=void 0,this.config=void 0,this.currentAccount=null,this.walletConnectProvider=null,this.persistedMethods=void 0,this.internalEventEmitter=new i,this.uiMessageManager=new g,this.walletMessageManager=new h(e,!!s),this.config=d({},w,n||{}),null!=(o=this.config.authenticationMethods)&&o.includes("wallet")&&this.initializeWalletConnect().catch(e=>{console.error("WalletConnect initialization failed:",e)}),this.persistedMethods={login:this.login.bind(this),logout:this.logout.bind(this),getLoginMethod:this.getLoginMethod.bind(this),walletMessageManager:this.walletMessageManager,internalEventEmitter:this.internalEventEmitter,uiMessageManager:this.uiMessageManager,portal:this.portal.bind(this),requestEmail:this.requestEmail.bind(this),requestSBT:this.requestSBT.bind(this),orcid:this.orcid.bind(this),enable:this.enable.bind(this),isConnected:this.isConnected.bind(this),toggleDarkMode:this.toggleDarkMode.bind(this),silkRequest:this.request.bind(this),waaPRequest:this.request.bind(this)},this.walletMessageManager.addListener({onReceiveConnectNotif:()=>{console.log("onReceiveConnectNotif"),this.connected=!0,this.emit("connect")},handleResponse:e=>this.internalEventEmitter.emit(e.id,e),handleRequest:e=>{e.method===r.show_modal?this.uiMessageManager.emit(u.show_modal):e.method===r.hide_modal&&this.uiMessageManager.emit(u.hide_modal)},onAccountChanged:e=>{this.currentAccount!==e&&(this.currentAccount=e,this.emit("accountsChanged",e?[e]:[]))}}),t&&this.walletMessageManager.pingIframe().then(()=>m({method:r.set_points_referral_code,params:[t]},!1,this.walletMessageManager,this.internalEventEmitter)).catch(e=>{console.error("Error setting referral code in Silk iframe:",e)}),a&&this.walletMessageManager.pingIframe().then(()=>m({method:r.set_project,params:[a,window.location.origin]},!1,this.walletMessageManager,this.internalEventEmitter)),n&&this.walletMessageManager.pingIframe().then(()=>m({method:r.set_custom_config,params:[n]},!1,this.walletMessageManager,this.internalEventEmitter)).catch(e=>{console.error("Error setting custom config in Silk iframe:",e)})}async initializeWalletConnect(){try{this.walletConnectProvider=await p.getInstance(),console.log("WalletConnect provider initialized")}catch(e){console.error("Failed to initialize WalletConnect provider:",e),this.walletConnectProvider=null}}async enable(){return this.request({method:"eth_requestAccounts"})}isConnected(){return this.connected}async request(e){if(!Object.keys(l).includes(e.method))return Promise.reject({error:`Not implemented (${e.method})`});const t=await this.attemptAutoConnect(e.method);if(null!==t)return t;if(function(e){try{var t;if(!e||!Array.isArray(e))return!1;const n=JSON.parse("string"==typeof e[1]?e[1]:JSON.stringify(e[1]));return"SafeTx"===n.primaryType&&void 0!==(null==(t=n.domain)?void 0:t.verifyingContract)&&n.message&&"to"in n.message&&"value"in n.message&&"safeTxGas"in n.message&&"baseGas"in n.message&&"gasPrice"in n.message&&"nonce"in n.message}catch(e){return!1}}(e.params)&&e.method!==l.eth_signTypedData_v4)return Promise.reject({error:"Safe transactions must be signed using eth_signTypedData_v4"});await this.walletMessageManager.pingIframe();const i=await m(e,n(e.method),this.walletMessageManager,this.internalEventEmitter);if((e.method===l.wallet_switchEthereumChain||e.method===l.wallet_addEthereumChain)&&null===i){var a;this.emit("chainChanged",null==(a=e.params)||null==(a=a[0])?void 0:a.chainId);try{const t=await this.request({method:"eth_accounts"});var s,o;t&&t.length>0&&(this.currentAccount=t[0],this.emit("accountsChanged",t),this.emit("connect",{chainId:null==(s=e.params)||null==(s=s[0])?void 0:s.chainId}),console.log("[EthereumProvider] Re-emitted accounts and connect after chain switch:",{accounts:t,chainId:null==(o=e.params)||null==(o=o[0])?void 0:o.chainId}))}catch(t){var r;console.warn("[EthereumProvider] Failed to get accounts after chain switch:",t),this.currentAccount&&(this.emit("accountsChanged",[this.currentAccount]),this.emit("connect",{chainId:null==(r=e.params)||null==(r=r[0])?void 0:r.chainId}))}}return i}async login(e){var t;if("undefined"==typeof window||"undefined"==typeof document)return null;null!=(t=this.config.authenticationMethods)&&t.includes("wallet")&&!this.walletConnectProvider&&await this.initializeWalletConnect();const n=e||window.ethereum,i=n&&function(e){return!(null==e||!e.isMetaMask||e.isApexWallet||e.isAvalanche||e.isBitKeep||e.isBlockWallet||e.isMathWallet||e.isOkxWallet||e.isOKExWallet||e.isOneInchIOSWallet||e.isOneInchAndroidWallet||e.isOpera||e.isPortal||e.isRabby||e.isDefiant||e.isTokenPocket||e.isTokenary||e.isZerion)}(n)?"MetaMask":"Browser Wallet";await this.walletMessageManager.pingIframe();const a=await m({method:r.login,params:[i]},!0,this.walletMessageManager,this.internalEventEmitter);if("string"==typeof a&&a.includes("waap")&&(localStorage.setItem(`${window.location.origin}-connected`,"waap"),this.setupWaaP()),"string"==typeof a&&a.includes("injected")&&n&&(localStorage.setItem(`${window.location.origin}-connected`,"injected"),this.setupInjectedWallet(n)),"string"==typeof a&&a.includes("walletconnect")){localStorage.setItem(`${window.location.origin}-connected`,"walletconnect"),p.isConnected()||(await this.walletConnectProvider.open({view:"Connect"}),await p.listenToAccountChangeEvent());const e=p.getWalletProvider();this.setupWalletConnect(e)}return a}async logout(){return await this.walletMessageManager.pingIframe(),this.cleanupInvalidLoginState(),this.walletConnectProvider&&await this.walletConnectProvider.disconnect(),m({method:r.logout},!1,this.walletMessageManager,this.internalEventEmitter)}cleanupInvalidLoginState(){try{localStorage.removeItem(`${window.location.origin}-connected`)}catch(e){console.warn("Could not clean up login state:",e)}}setupWaaP(){const e=d({},this.persistedMethods,{isWaaP:!0,request:this.request.bind(this)});window.silk=e,window.waap=e}setupInjectedWallet(e){var t,n,i,a,s;const o=d({},this.persistedMethods,e,{isSilk:!0,connected:null!=(t=e.connected)&&t,on:null!=(n=null==(i=e.on)?void 0:i.bind(e))?n:()=>{},removeListener:null!=(a=null==(s=e.removeListener)?void 0:s.bind(e))?a:()=>{},request:e.request.bind(e)});window.silk=o,window.waap=o}setupWalletConnect(e){var t,n,i,a;const s=d({},this.persistedMethods,e,{isSilk:!0,connected:!0,on:null!=(t=null==(n=e.on)?void 0:n.bind(e))?t:()=>{},removeListener:null!=(i=null==(a=e.removeListener)?void 0:a.bind(e))?i:()=>{},request:e.request.bind(e)});window.silk=s,window.waap=s}setupAutoConnectInjected(e){var t,n,i,a,s;const o=d({},this.persistedMethods,e,{isSilk:!1,connected:null!=(t=null==e.isConnected?void 0:e.isConnected())&&t,on:null!=(n=null==(i=e.on)?void 0:i.bind(e))?n:()=>{},removeListener:null!=(a=null==(s=e.removeListener)?void 0:s.bind(e))?a:()=>{},request:e.request.bind(e)});window.silk=o,window.waap=o}setupAutoConnectWalletConnect(e){var t,n,i,a;const s=d({},this.persistedMethods,e,{isSilk:!1,connected:!0,on:null!=(t=null==(n=e.on)?void 0:n.bind(e))?t:()=>{},removeListener:null!=(i=null==(a=e.removeListener)?void 0:a.bind(e))?i:()=>{},request:e.request.bind(e)});window.silk=s,window.waap=s}async attemptAutoConnect(e){var t=this;if("eth_requestAccounts"!==e&&"eth_accounts"!==e)return null;this.walletMessageManager.pingIframe().then(async function(){await m({method:r.auto_conn,params:[window.location.origin]},!1,t.walletMessageManager,t.internalEventEmitter)});const n=this.getLoginMethod();if("injected"===n&&window.ethereum)try{return this.setupAutoConnectInjected(window.ethereum),window.ethereum.request({method:"eth_requestAccounts"})}catch(e){return console.warn("Injected wallet auto-connect failed:",e),this.cleanupInvalidLoginState(),null}else if("walletconnect"===n)try{if(this.walletConnectProvider||(this.walletConnectProvider=await p.getInstance()),await p.waitForReadyAndCheckConnection()){const e=p.getWalletProvider();return this.setupAutoConnectWalletConnect(e),e.request({method:"eth_requestAccounts"})}return console.log("WalletConnect not connected, cleaning up and falling through to normal flow"),this.cleanupInvalidLoginState(),null}catch(e){return console.warn("WalletConnect auto-connect failed:",e),this.cleanupInvalidLoginState(),null}return null}getLoginMethod(){if("undefined"==typeof window||"undefined"==typeof localStorage)return null;try{const e=localStorage.getItem(`${window.location.origin}-connected`);if(!e)return null;if(!["waap","human","injected","walletconnect"].includes(e))return this.cleanupInvalidLoginState(),null;switch(e){case"injected":return window.ethereum?"injected":(this.cleanupInvalidLoginState(),null);case"walletconnect":try{return p.isConnected()?"walletconnect":(this.cleanupInvalidLoginState(),null)}catch(e){return this.cleanupInvalidLoginState(),null}case"waap":return"waap";case"human":return"human";default:return this.cleanupInvalidLoginState(),null}}catch(e){return console.warn("Error checking login method:",e),this.cleanupInvalidLoginState(),null}}async toggleDarkMode(){this.config.styles.darkMode=!this.config.styles.darkMode,this.walletMessageManager.pingIframe().then(()=>m({method:r.set_custom_config,params:[this.config]},!1,this.walletMessageManager,this.internalEventEmitter)).catch(e=>{console.error("Error setting custom config in Silk iframe:",e)})}async safe(){this.walletMessageManager.pingIframe().then(()=>m({method:r.safe},!0,this.walletMessageManager,this.internalEventEmitter))}async orcid(){this.walletMessageManager.pingIframe().then(()=>m({method:r.orcid},!0,this.walletMessageManager,this.internalEventEmitter))}async portal(e,t,n){let i;switch(await this.walletMessageManager.pingIframe(),t){case"get":i="gastank"===e?r.gastank_get_settings:r.customization_get;break;case"update":i="gastank"===e?r.gastank_update_settings:r.customization_update;break;case"topup":i=r.gastank_topup;break;case"init":i=r.project_init}return m({method:i,params:[n,window.location.origin]},"get"!==t&&"customization"!==e,this.walletMessageManager,this.internalEventEmitter)}async requestEmail(){return await this.walletMessageManager.pingIframe(),m({method:r.silk_requestEmail},!0,this.walletMessageManager,this.internalEventEmitter)}async requestSBT(e){return await this.walletMessageManager.pingIframe(),m({method:r.silk_requestSbt,params:[e]},!0,this.walletMessageManager,this.internalEventEmitter)}}const v="waap-wallet-iframe-container",y="waap-wallet-iframe-wrapper",M="waap-wallet-iframe",E=()=>document.getElementById(v)||document.getElementById("silk-wallet-iframe-container"),C=()=>document.getElementById(y)||document.getElementById("silk-wallet-iframe-wrapper"),k=v,I=y,_=M,b=(n={})=>{(n=>{if(E())return;const i=window.document.createElement("div");i.id=k,i.style.position="fixed",i.style.top="0",i.style.left="0",i.style.right="0",i.style.bottom="0",i.style.width="100%",i.style.height="100%",i.style.display="flex",i.style.alignItems="center",i.style.justifyContent="center",i.style.backgroundColor="rgba(0, 0, 0, 0.5)",i.style.zIndex="99999",i.style.display="none";const a=new Blob(['<svg width="32" height="32" viewBox="0 0 32 32" fill="none" xmlns="http://www.w3.org/2000/svg">\n <rect width="32" height="32" rx="16" fill="#F5F5F5"/>\n <path d="M20.9497 11.0503L11.0503 20.9498M11.0503 11.0503L20.9497 20.9498" stroke="#A3A3A3" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>\n </svg>'],{type:"image/svg+xml"}),s=URL.createObjectURL(a),o=new Blob(['<svg width="32" height="32" viewBox="0 0 32 32" fill="none" xmlns="http://www.w3.org/2000/svg">\n <rect width="32" height="32" rx="16" fill="#FEF3F2"/>\n <path d="M20.9497 11.0503L11.0503 20.9498M11.0503 11.0503L20.9497 20.9498" stroke="#F97066" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>\n </svg>'],{type:"image/svg+xml"}),r=URL.createObjectURL(o),l=document.createElement("button"),c=document.createElement("img");c.src=s,c.alt="closeIcon",l.addEventListener("mouseenter",function(){c.src=r}),l.addEventListener("mouseleave",function(){c.src=s}),l.style.all="initial",l.style.height="fit-content",l.style.position="absolute",l.style.top="1px",l.style.right="1px",l.style.zIndex="999999",l.style.cursor="pointer",l.appendChild(c),l.onclick=()=>{i.style.display="none"};const d=window.document.createElement("div");d.id=I,d.style.position="relative",d.style.display="flex",d.style.alignItems="center",d.style.justifyContent="center",d.style.padding="0",d.style.margin="0",d.style.height="600px",d.style.width="380px",i.appendChild(d);const h=window.document.createElement("iframe");h.id=_,h.src=`${n?e:t}/iframe`,console.log("iframe.src: ",h.src),h.style.width="100%",h.style.height="100%",setTimeout(()=>{const e=C();e&&(e.style.height="600px",e.style.width="380px")},100);const u=i=>{if(i.origin!==(n?e:t))return;if(!i.data||"object"!=typeof i.data)return;if("silk-iframe-size"!==i.data.type)return;const a=i.data.height,s=i.data.width;if("number"!=typeof a||"number"!=typeof s)return;if(a<50||a>2e3)return;if(s<50||s>2e3)return;if(!Number.isFinite(a)||!Number.isFinite(s))return;const o=C();o&&(o.style.height=`${Math.floor(a)}px`,o.style.width=`${Math.floor(s)}px`)};window.addEventListener("message",u),h.__silkCleanup=()=>{window.removeEventListener("message",u)},h.style.border="none",h.style.borderRadius="24px",h.style.backgroundColor="transparent",h.style.background="transparent",h.style.padding="0",h.style.margin="0",d.appendChild(h),window.document.body.appendChild(i)})(!!n.useStaging);const i=E(),a=document.getElementById(M)||document.getElementById("silk-wallet-iframe");if(!i||!a)throw new Error("Silk iframe does not exist on page");n.walletConnectProjectId&&p.setProjectId(n.walletConnectProjectId);const{referralCode:s,config:o,project:r}=n,l=new f(a.contentWindow,s,o||{},r||{},n.useStaging);return l.uiMessageManager.on(u.show_modal,()=>{i.style.display="flex"}),l.uiMessageManager.on(u.hide_modal,()=>{i.style.display="none"}),window.silk=l,window.waap=l,l},L=b;class P extends i{constructor(e){super(),this.isSilk=!0,this.connected=!1,this.config=void 0,this.config=d({},w,e||{})}sendToExtension(e){return new Promise((t,n)=>{window.postMessage({type:"FROM_PAGE",request:e},"*"),window.addEventListener("message",e=>{"FROM_EXTENSION"===e.data.type&&(e.data.error?n(e.data.error):t(e.data.result))})})}async request(e){if(!Object.keys(l).includes(e.method))return Promise.reject({error:`Not implemented (${e.method})`});const t=await this.sendToExtension(e);var n;return e.method!==l.wallet_switchEthereumChain&&e.method!==l.wallet_addEthereumChain||null!==t||this.emit("chainChanged",null==(n=e.params)||null==(n=n[0])?void 0:n.chainId),t}async enable(){return this.request({method:"eth_requestAccounts"})}isConnected(){return this.connected}async login(){return this.sendToExtension({method:r.login})}async requestSBT(e){return this.sendToExtension({method:r.silk_requestSbt,params:[e]})}async toggleDarkMode(){this.config.styles.darkMode=!this.config.styles.darkMode,await this.sendToExtension({method:r.set_custom_config,params:[this.config]})}async safe(){return this.sendToExtension({method:r.safe})}}export{f as EthereumProvider,P as EthereumProviderExtension,p as SilkWalletConnect,g as UIMessageManager,u as UI_EVENT_NAMES,p as WaaPWalletConnect,h as WalletMessageManager,m as handleWalletRequestAndResponse,b as initSilk,L as initWaaP};
|
|
1
|
+
import{silkWalletAppOrigin2Staging as e,silkWalletAppOrigin2 as t,rpcMethodRequiresUI as n}from"@human.tech/waap-constants";export{rpcMethodRequiresUI}from"@human.tech/waap-constants";import{EventEmitter as i}from"events";import{SILK_MESSAGE_TYPE as a,SILK_NOTIFICATION as s,generateMessageId as o,SILK_METHOD as r,JSON_RPC_METHOD as l}from"@human.tech/waap-interface-core";export{SILK_METHOD,SILK_METHOD as WAAP_METHOD}from"@human.tech/waap-interface-core";import{EthersAdapter as c}from"@reown/appkit-adapter-ethers";function d(){return d=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var i in n)({}).hasOwnProperty.call(n,i)&&(e[i]=n[i])}return e},d.apply(null,arguments)}class h{constructor(n,i){this.iframeWindow=null,this.walletOrigin=void 0,this.iframeWindow=n,this.walletOrigin=i?e:t}postSilkNotification(e){this.iframeWindow.postMessage({target:"silk",messageType:a.notification,data:e},this.walletOrigin)}postReadyNotification(){this.postSilkNotification(s.ready)}postConnectNotification(){this.postSilkNotification(s.connect)}pingIframe(){return new Promise((e,t)=>{setTimeout(()=>t("Wallet ping timed out."),1e4);const n=t=>{"silk"===t.data.target&&t.data.messageType===a.notification&&t.data.data===s.ready&&(window.removeEventListener("message",n),e())};window.addEventListener("message",n),this.postReadyNotification()})}async postSilkRequest(e){const t=d({},e,{target:"silk",messageType:a.request}),n=await o(t);return this.iframeWindow.postMessage(d({},t,{id:n}),this.walletOrigin),n}addListener(e){const{handleResponse:t,handleRequest:n,onReceiveConnectNotif:i,onAccountChanged:o}=e;window.addEventListener("message",e=>{var r,l,c;try{if("undefined"!=typeof process&&process,e.origin!==this.walletOrigin)return}catch(t){if(e.origin!==this.walletOrigin)return}if((null==(r=e.data)?void 0:r.messageType)===a.request)n(e.data);else if((null==(l=e.data)?void 0:l.messageType)===a.response)t(e.data);else if((null==(c=e.data)?void 0:c.messageType)===a.notification){var d,h;(null==(d=e.data)?void 0:d.data)===s.connect?null==i||i():(null==(h=e.data)||null==(h=h.data)?void 0:h.type)===s.account_changed&&o&&o(e.data.data.account)}})}}var u;!function(e){e.show_modal="show_modal",e.hide_modal="hide_modal"}(u||(u={}));class g extends i{constructor(){super()}}async function m(e,t,n,i){const a=e.method,s=e.params,o=await n.postSilkRequest({method:a,params:s,interactionRequired:t});return new Promise((e,t)=>{i.once(o,n=>{n.error?t(n.error):e(n.data)})})}const p={styles:{darkMode:!1}};class w{static setProjectId(e){this.projectId=e}static getProjectIdFromEnv(){try{if("undefined"!=typeof process&&process.env)return process.env.NEXT_PUBLIC_WALLET_CONNECT_PROJECT_ID||process.env.VITE_WALLET_CONNECT_PROJECT_ID||process.env.REACT_APP_WALLET_CONNECT_PROJECT_ID||process.env.WALLET_CONNECT_PROJECT_ID}catch(e){return}}static async getInstance(){if("undefined"==typeof window||"undefined"==typeof document)return null;const{createAppKit:e}=await import("@reown/appkit"),{mainnet:t,sepolia:n,optimism:i,arbitrum:a,polygon:s,gnosis:o,avalanche:r,aurora:l,fantom:d,base:h,celo:u}=await import("@reown/appkit/networks");try{const g={name:"Human Wallet",description:"Silk lets you create human keys for web3 wallets that are recoverable with private identity proofs and secured by zero trust protocols.",url:window.location.origin,icons:["https://imagedelivery.net/_aTEfDRm7z3tKgu9JhfeKA/f11f5753-616a-4aa0-2aee-9b75befea700/sm"]},m=this.projectId||this.getProjectIdFromEnv();return m?(this.projectId=m,this.instance||(this.instance=e({adapters:[new c],projectId:m,metadata:g,networks:[t,n,a,i,s,o,r,l,d,h,u],features:{socials:!1,email:!1}})),this.instance):(console.error('WalletConnect project ID not found. Please set it using one of these methods:\n1. Pass walletConnectProjectId when calling initSilk\n2. Call SilkWalletConnect.setProjectId("your-project-id")\n3. Set WALLET_CONNECT_PROJECT_ID (NEXT_PUBLIC_WALLET_CONNECT_PROJECT_ID for Next projects) environment variable'),null)}catch(e){return console.error("Error importing or initializing WalletConnect:",e),null}}static async listenToAccountChangeEvent(){await new Promise(e=>{this.instance.subscribeAccount(t=>{null!=t&&t.isConnected&&e()})})}static async waitForReadyAndCheckConnection(){if(!this.instance)return!1;let e=!1,t=0;for(;!e&&t<15;){const n=t<5?500:1e3;await new Promise(e=>setTimeout(e,n)),e=this.instance.getIsConnectedState(),t++,console.log(`WalletConnect connection check attempt ${t}: ${e}`)}return e}static isConnected(){var e,t;return null!=(e=null==(t=this.instance)?void 0:t.getIsConnectedState())&&e}static getWalletProvider(){var e,t;return null!=(e=null==(t=this.instance)?void 0:t.getWalletProvider())?e:null}}w.instance=null,w.projectId=void 0,w.chains=[1,10,100,137,8453,43114,42161,42220,84532,11155111];class f extends i{constructor(e,t,n,a,s,o){super(),this.isSilk=!0,this.isWaaP=!0,this.connected=!1,this.walletMessageManager=void 0,this.uiMessageManager=void 0,this.config=void 0,this.currentAccount=null,this.walletConnectProvider=null,this.persistedMethods=void 0,this.internalEventEmitter=new i,this.uiMessageManager=new g,this.walletMessageManager=new h(e,!!s),this.config=d({},p,n||{}),this.persistedMethods={login:this.login.bind(this),logout:this.logout.bind(this),getLoginMethod:this.getLoginMethod.bind(this),walletMessageManager:this.walletMessageManager,internalEventEmitter:this.internalEventEmitter,uiMessageManager:this.uiMessageManager,portal:this.portal.bind(this),requestEmail:this.requestEmail.bind(this),requestSBT:this.requestSBT.bind(this),orcid:this.orcid.bind(this),enable:this.enable.bind(this),isConnected:this.isConnected.bind(this),toggleDarkMode:this.toggleDarkMode.bind(this),silkRequest:this.request.bind(this),waaPRequest:this.request.bind(this)},this.walletMessageManager.addListener({onReceiveConnectNotif:()=>{console.log("onReceiveConnectNotif"),this.connected=!0,this.emit("connect")},handleResponse:e=>this.internalEventEmitter.emit(e.id,e),handleRequest:e=>{e.method===r.show_modal?this.uiMessageManager.emit(u.show_modal):e.method===r.hide_modal&&this.uiMessageManager.emit(u.hide_modal)},onAccountChanged:e=>{this.currentAccount!==e&&(this.currentAccount=e,this.emit("accountsChanged",e?[e]:[]))}}),t&&this.walletMessageManager.pingIframe().then(()=>m({method:r.set_points_referral_code,params:[t]},!1,this.walletMessageManager,this.internalEventEmitter)).catch(e=>{console.error("Error setting referral code in Silk iframe:",e)}),a&&this.walletMessageManager.pingIframe().then(()=>m({method:r.set_project,params:[a,window.location.origin]},!1,this.walletMessageManager,this.internalEventEmitter)),n&&this.walletMessageManager.pingIframe().then(()=>m({method:r.set_custom_config,params:[n]},!1,this.walletMessageManager,this.internalEventEmitter)).catch(e=>{console.error("Error setting custom config in Silk iframe:",e)}),o&&this.walletMessageManager.pingIframe().then(()=>m({method:r.force_iframe,params:[!0]},!1,this.walletMessageManager,this.internalEventEmitter)).catch(e=>{console.error("Error forcing iframe in Silk iframe:",e)})}async initializeWalletConnect(){try{this.walletConnectProvider=await w.getInstance(),console.log("WalletConnect provider initialized")}catch(e){console.error("Failed to initialize WalletConnect provider:",e),this.walletConnectProvider=null}}async enable(){return this.request({method:"eth_requestAccounts"})}isConnected(){return this.connected}async request(e){if(!Object.keys(l).includes(e.method))return Promise.reject({error:`Not implemented (${e.method})`});const t=await this.attemptAutoConnect(e.method);if(null!==t)return t;if(function(e){try{var t;if(!e||!Array.isArray(e))return!1;const n=JSON.parse("string"==typeof e[1]?e[1]:JSON.stringify(e[1]));return"SafeTx"===n.primaryType&&void 0!==(null==(t=n.domain)?void 0:t.verifyingContract)&&n.message&&"to"in n.message&&"value"in n.message&&"safeTxGas"in n.message&&"baseGas"in n.message&&"gasPrice"in n.message&&"nonce"in n.message}catch(e){return!1}}(e.params)&&e.method!==l.eth_signTypedData_v4)return Promise.reject({error:"Safe transactions must be signed using eth_signTypedData_v4"});await this.walletMessageManager.pingIframe();const i=await m(e,n(e.method),this.walletMessageManager,this.internalEventEmitter);if((e.method===l.wallet_switchEthereumChain||e.method===l.wallet_addEthereumChain)&&null===i){var a;this.emit("chainChanged",null==(a=e.params)||null==(a=a[0])?void 0:a.chainId);try{const t=await this.request({method:"eth_accounts"});var s,o;t&&t.length>0&&(this.currentAccount=t[0],this.emit("accountsChanged",t),this.emit("connect",{chainId:null==(s=e.params)||null==(s=s[0])?void 0:s.chainId}),console.log("[EthereumProvider] Re-emitted accounts and connect after chain switch:",{accounts:t,chainId:null==(o=e.params)||null==(o=o[0])?void 0:o.chainId}))}catch(t){var r;console.warn("[EthereumProvider] Failed to get accounts after chain switch:",t),this.currentAccount&&(this.emit("accountsChanged",[this.currentAccount]),this.emit("connect",{chainId:null==(r=e.params)||null==(r=r[0])?void 0:r.chainId}))}}return i}async login(e){var t;if("undefined"==typeof window||"undefined"==typeof document)return null;null!=(t=this.config.authenticationMethods)&&t.includes("wallet")&&!this.walletConnectProvider&&await this.initializeWalletConnect();const n=e||window.ethereum,i=n&&function(e){return!(null==e||!e.isMetaMask||e.isApexWallet||e.isAvalanche||e.isBitKeep||e.isBlockWallet||e.isMathWallet||e.isOkxWallet||e.isOKExWallet||e.isOneInchIOSWallet||e.isOneInchAndroidWallet||e.isOpera||e.isPortal||e.isRabby||e.isDefiant||e.isTokenPocket||e.isTokenary||e.isZerion)}(n)?"MetaMask":"Browser Wallet";await this.walletMessageManager.pingIframe();const a=await m({method:r.login,params:[i]},!0,this.walletMessageManager,this.internalEventEmitter);if("string"==typeof a&&a.includes("waap")&&(localStorage.setItem(`${window.location.origin}-connected`,"waap"),this.setupWaaP()),"string"==typeof a&&a.includes("injected")&&n&&(localStorage.setItem(`${window.location.origin}-connected`,"injected"),this.setupInjectedWallet(n)),"string"==typeof a&&a.includes("walletconnect")){localStorage.setItem(`${window.location.origin}-connected`,"walletconnect"),w.isConnected()||(await this.walletConnectProvider.open({view:"Connect"}),await w.listenToAccountChangeEvent());const e=w.getWalletProvider();this.setupWalletConnect(e)}return a}async logout(){await this.walletMessageManager.pingIframe(),this.cleanupInvalidLoginState();try{this.walletConnectProvider&&await this.walletConnectProvider.disconnect()}catch(e){console.error("Error disconnecting from WalletConnect:",e)}return m({method:r.logout},!1,this.walletMessageManager,this.internalEventEmitter)}cleanupInvalidLoginState(){try{localStorage.removeItem(`${window.location.origin}-connected`)}catch(e){console.warn("Could not clean up login state:",e)}}setupWaaP(){const e=d({},this.persistedMethods,{isWaaP:!0,request:this.request.bind(this)});window.silk=e,window.waap=e}setupInjectedWallet(e){var t,n,i,a,s;const o=d({},this.persistedMethods,e,{isSilk:!0,connected:null!=(t=e.connected)&&t,on:null!=(n=null==(i=e.on)?void 0:i.bind(e))?n:()=>{},removeListener:null!=(a=null==(s=e.removeListener)?void 0:s.bind(e))?a:()=>{},request:e.request.bind(e)});window.silk=o,window.waap=o}setupWalletConnect(e){var t,n,i,a;const s=d({},this.persistedMethods,e,{isSilk:!0,connected:!0,on:null!=(t=null==(n=e.on)?void 0:n.bind(e))?t:()=>{},removeListener:null!=(i=null==(a=e.removeListener)?void 0:a.bind(e))?i:()=>{},request:e.request.bind(e)});window.silk=s,window.waap=s}setupAutoConnectInjected(e){var t,n,i,a,s;const o=d({},this.persistedMethods,e,{isSilk:!1,connected:null!=(t=null==e.isConnected?void 0:e.isConnected())&&t,on:null!=(n=null==(i=e.on)?void 0:i.bind(e))?n:()=>{},removeListener:null!=(a=null==(s=e.removeListener)?void 0:s.bind(e))?a:()=>{},request:e.request.bind(e)});window.silk=o,window.waap=o}setupAutoConnectWalletConnect(e){var t,n,i,a;const s=d({},this.persistedMethods,e,{isSilk:!1,connected:!0,on:null!=(t=null==(n=e.on)?void 0:n.bind(e))?t:()=>{},removeListener:null!=(i=null==(a=e.removeListener)?void 0:a.bind(e))?i:()=>{},request:e.request.bind(e)});window.silk=s,window.waap=s}async attemptAutoConnect(e){var t=this;if("eth_requestAccounts"!==e&&"eth_accounts"!==e)return null;this.walletMessageManager.pingIframe().then(async function(){await m({method:r.auto_conn,params:[window.location.origin]},!1,t.walletMessageManager,t.internalEventEmitter)});const n=this.getLoginMethod();if("injected"===n&&window.ethereum)try{return this.setupAutoConnectInjected(window.ethereum),window.ethereum.request({method:"eth_requestAccounts"})}catch(e){return console.warn("Injected wallet auto-connect failed:",e),this.cleanupInvalidLoginState(),null}else if("walletconnect"===n)try{if(this.walletConnectProvider||(this.walletConnectProvider=await w.getInstance()),await w.waitForReadyAndCheckConnection()){const e=w.getWalletProvider();return this.setupAutoConnectWalletConnect(e),e.request({method:"eth_requestAccounts"})}return console.log("WalletConnect not connected, cleaning up and falling through to normal flow"),this.cleanupInvalidLoginState(),null}catch(e){return console.warn("WalletConnect auto-connect failed:",e),this.cleanupInvalidLoginState(),null}return null}getLoginMethod(){if("undefined"==typeof window||"undefined"==typeof localStorage)return null;try{const e=localStorage.getItem(`${window.location.origin}-connected`);if(!e)return null;if(!["waap","human","injected","walletconnect"].includes(e))return this.cleanupInvalidLoginState(),null;switch(e){case"injected":return window.ethereum?"injected":(this.cleanupInvalidLoginState(),null);case"walletconnect":try{return w.isConnected()?"walletconnect":(this.cleanupInvalidLoginState(),null)}catch(e){return this.cleanupInvalidLoginState(),null}case"waap":return"waap";case"human":return"human";default:return this.cleanupInvalidLoginState(),null}}catch(e){return console.warn("Error checking login method:",e),this.cleanupInvalidLoginState(),null}}async toggleDarkMode(){this.config.styles.darkMode=!this.config.styles.darkMode,this.walletMessageManager.pingIframe().then(()=>m({method:r.set_custom_config,params:[this.config]},!1,this.walletMessageManager,this.internalEventEmitter)).catch(e=>{console.error("Error setting custom config in Silk iframe:",e)})}async safe(){this.walletMessageManager.pingIframe().then(()=>m({method:r.safe},!0,this.walletMessageManager,this.internalEventEmitter))}async orcid(){this.walletMessageManager.pingIframe().then(()=>m({method:r.orcid},!0,this.walletMessageManager,this.internalEventEmitter))}async portal(e,t,n){let i;switch(await this.walletMessageManager.pingIframe(),t){case"get":i="gastank"===e?r.gastank_get_settings:r.customization_get;break;case"update":i="gastank"===e?r.gastank_update_settings:r.customization_update;break;case"topup":i=r.gastank_topup;break;case"init":i=r.project_init}return m({method:i,params:[n,window.location.origin]},"get"!==t&&"customization"!==e,this.walletMessageManager,this.internalEventEmitter)}async requestEmail(){return await this.walletMessageManager.pingIframe(),m({method:r.silk_requestEmail},!0,this.walletMessageManager,this.internalEventEmitter)}async requestSBT(e){return await this.walletMessageManager.pingIframe(),m({method:r.silk_requestSbt,params:[e]},!0,this.walletMessageManager,this.internalEventEmitter)}}const y="waap-wallet",v="waap-component-container",M="undefined"!=typeof window&&"undefined"!=typeof document&&"undefined"!=typeof HTMLElement;let E;function C(){return!(!M||!document.getElementById(v)&&!document.querySelector(y))}function I(){return M?document.getElementById(v)||document.querySelector(y):null}M?(E=class extends HTMLElement{constructor(){super(),this.style.display&&""!==this.style.display||(this.style.display="flex",this.style.alignItems="center",this.style.justifyContent="center"),this.style.width&&""!==this.style.width||(this.style.width="100%"),this.style.height&&""!==this.style.height||(this.style.height="100%"),this.id=v}connectedCallback(){this.setAttribute("data-waap-mounted","true")}disconnectedCallback(){this.removeAttribute("data-waap-mounted")}},"undefined"==typeof customElements||customElements.get(y)||customElements.define(y,E)):E=class{};const _="waap-wallet-iframe-container",k="waap-wallet-iframe-wrapper",b="waap-wallet-iframe",P=()=>document.getElementById(_)||document.getElementById("silk-wallet-iframe-container"),T=()=>document.getElementById(k)||document.getElementById("silk-wallet-iframe-wrapper"),S=()=>document.getElementById(b)||document.getElementById("silk-wallet-iframe"),W=_,L=k,q=b,A=n=>{const i=window.document.createElement("iframe");return i.id=q,i.src=`${n?e:t}/iframe`,console.log("iframe.src: ",i.src),i.style.width="100%",i.style.height="100%",i.style.border="none",i.style.borderRadius="24px",i.style.backgroundColor="transparent",i.style.background="transparent",i.style.padding="0",i.style.margin="0",i},j=(n,i)=>{const a=i=>{if(i.origin!==(n?e:t))return;if(!i.data||"object"!=typeof i.data)return;if("silk-iframe-size"!==i.data.type)return;const a=i.data.height,s=i.data.width;if("number"!=typeof a||"number"!=typeof s)return;if(a<50||a>2e3)return;if(s<50||s>2e3)return;if(!Number.isFinite(a)||!Number.isFinite(s))return;const o=T();o&&(o.style.height=`${Math.floor(a)}px`,o.style.width=`${Math.floor(s)}px`)};window.addEventListener("message",a),i.__silkCleanup=()=>{window.removeEventListener("message",a)}},x=(e={})=>{var t;t=!!e.useStaging,C()?(e=>{const t=I();if(!t)throw new Error("WaaP component not found in DOM");if(S())return;const n=window.document.createElement("div");n.id=L,n.style.position="relative",n.style.display="flex",n.style.alignItems="center",n.style.justifyContent="center",n.style.padding="0",n.style.margin="0",n.style.height="600px",n.style.width="380px";const i=A(e);j(e,i),setTimeout(()=>{const e=T();e&&(e.style.height="600px",e.style.width="380px")},100),n.appendChild(i),t.appendChild(n)})(t):(e=>{if(P())return;const t=window.document.createElement("div");t.id=W,t.style.position="fixed",t.style.top="0",t.style.left="0",t.style.right="0",t.style.bottom="0",t.style.width="100%",t.style.height="100%",t.style.display="flex",t.style.alignItems="center",t.style.justifyContent="center",t.style.backgroundColor="rgba(0, 0, 0, 0.5)",t.style.zIndex="99999",t.style.display="none";const n=window.document.createElement("div");n.id=L,n.style.position="relative",n.style.display="flex",n.style.alignItems="center",n.style.justifyContent="center",n.style.padding="0",n.style.margin="0",n.style.height="600px",n.style.width="380px",t.appendChild(n);const i=A(e);j(e,i),setTimeout(()=>{const e=T();e&&(e.style.height="600px",e.style.width="380px")},100),n.appendChild(i),window.document.body.appendChild(t)})(t);const n=S();if(!n)throw new Error("WaaP iframe does not exist on page");const i=C();P(),I(),T(),e.walletConnectProjectId&&w.setProjectId(e.walletConnectProjectId);const{referralCode:a,config:s,project:o,forceIframe:r}=e,l=new f(n.contentWindow,a,s||{},o||{},e.useStaging,r);let c=i?"component":"modal";return l.uiMessageManager.on(u.show_modal,()=>{const e=C(),t=e?"component":"modal",n=T();if(t!==c&&n)if(c=t,e){const e=I();e&&e.appendChild(n)}else{let e=P();e||(e=window.document.createElement("div"),e.id=W,e.style.position="fixed",e.style.top="0",e.style.left="0",e.style.right="0",e.style.bottom="0",e.style.width="100%",e.style.height="100%",e.style.display="flex",e.style.alignItems="center",e.style.justifyContent="center",e.style.backgroundColor="rgba(0, 0, 0, 0.5)",e.style.zIndex="99999",window.document.body.appendChild(e)),e.appendChild(n)}const i=P();e&&n?n.style.display="flex":i&&(i.style.display="flex")}),l.uiMessageManager.on(u.hide_modal,()=>{const e=C(),t=T(),n=P();e&&t?t.style.display="none":n&&(n.style.display="none")}),window.silk=l,window.waap=l,l};class O extends i{constructor(e){super(),this.isSilk=!0,this.connected=!1,this.config=void 0,this.config=d({},p,e||{})}sendToExtension(e){return new Promise((t,n)=>{window.postMessage({type:"FROM_PAGE",request:e},"*"),window.addEventListener("message",e=>{"FROM_EXTENSION"===e.data.type&&(e.data.error?n(e.data.error):t(e.data.result))})})}async request(e){if(!Object.keys(l).includes(e.method))return Promise.reject({error:`Not implemented (${e.method})`});const t=await this.sendToExtension(e);var n;return e.method!==l.wallet_switchEthereumChain&&e.method!==l.wallet_addEthereumChain||null!==t||this.emit("chainChanged",null==(n=e.params)||null==(n=n[0])?void 0:n.chainId),t}async enable(){return this.request({method:"eth_requestAccounts"})}isConnected(){return this.connected}async login(){return this.sendToExtension({method:r.login})}async requestSBT(e){return this.sendToExtension({method:r.silk_requestSbt,params:[e]})}async toggleDarkMode(){this.config.styles.darkMode=!this.config.styles.darkMode,await this.sendToExtension({method:r.set_custom_config,params:[this.config]})}async safe(){return this.sendToExtension({method:r.safe})}}export{f as EthereumProvider,O as EthereumProviderExtension,w as SilkWalletConnect,g as UIMessageManager,u as UI_EVENT_NAMES,E as WaaP,w as WaaPWalletConnect,h as WalletMessageManager,m as handleWalletRequestAndResponse,x as initWaaP};
|
|
2
2
|
//# sourceMappingURL=index.modern.mjs.map
|