From 8085ee4bf392ed3b507d1cd91217f97b6475a633 Mon Sep 17 00:00:00 2001 From: Adw8 Date: Thu, 7 Nov 2024 13:40:12 +0530 Subject: [PATCH] Add bundled method to create account --- src/components/WalletEmbed.tsx | 70 ++++++++++++++++++++++++++++++---- 1 file changed, 63 insertions(+), 7 deletions(-) diff --git a/src/components/WalletEmbed.tsx b/src/components/WalletEmbed.tsx index f28542e..2ad30d4 100644 --- a/src/components/WalletEmbed.tsx +++ b/src/components/WalletEmbed.tsx @@ -2,9 +2,7 @@ import React, { useEffect } from 'react' export const WalletEmbed = () => { useEffect(() => { - const handleMessage = (event: MessageEvent) => { - // Not checking for event origin as only account addresses are returned - + const handleGetAccounts = (event: MessageEvent) => { if (event.data.type === 'REQUEST_WALLET_ACCOUNTS') { try { let accountsData = ''; @@ -47,12 +45,70 @@ export const WalletEmbed = () => { } }; - // Set up the message event listener - window.addEventListener('message', handleMessage); + window.addEventListener('message', handleGetAccounts); - // Clean up the event listener on component unmount return () => { - window.removeEventListener('message', handleMessage); + window.removeEventListener('message', handleGetAccounts); + }; + }, []); + + useEffect(() => { + const handleCreateAccounts = (event: MessageEvent) => { + if (event.data.type === 'REQUEST_CREATE_OR_GET_ACCOUNTS') { + try { + console.log("Create Accounts request received:", event.data); + let accountsData = ''; + console.log("chainId", event.data.chainId); + console.log("ls: \n", localStorage); + const indices = localStorage.getItem(`addAccountCounter/cosmos:laconic-testnet-2`); + if (indices) { + for (let i = 0; i < Number(indices); i++) { + const account = localStorage.getItem(`accounts/cosmos:${event.data.chainId}/${i}`); + console.log("Account found", account); + if (account) { + accountsData += `${account},`; + } + } + } + // Remove trailing comma + accountsData = accountsData.slice(0, -1); + + if (!accountsData) { + event.source?.postMessage({ + type: 'ERROR', + message: 'Wallet accounts not found in local storage', + }); + return; + } + + const elements = accountsData.split(','); + const addresses = elements.filter((_, index) => (index + 1) % 4 === 0); // Process the accounts as required + + console.log('Accounts Data:', addresses); // Log processed accounts data + + // Send the accounts data back to the origin + (event.source as Window)?.postMessage( + { + type: 'WALLET_ACCOUNTS_DATA', + data: addresses, + }, + event.origin + ); + + } catch (error) { + console.error('Error handling account creation:', error); // Log error + (event.source as Window)?.postMessage({ + type: 'ERROR', + message: 'Error accessing or creating wallet accounts data' + }, event.origin); + } + } + }; + + window.addEventListener('message', handleCreateAccounts); + + return () => { + window.removeEventListener('message', handleCreateAccounts); }; }, []);