diff --git a/src/components/header/header.ts b/src/components/header/header.ts index 47f52be..0ebf93b 100644 --- a/src/components/header/header.ts +++ b/src/components/header/header.ts @@ -7,7 +7,7 @@ let notifications = []; export async function unpair() { const service = await Services.getInstance(); await service.unpairDevice(); - navigate('home') + navigate('home'); } (window as any).unpair = unpair; @@ -27,7 +27,7 @@ function toggleMenu() { async function getNotifications() { const service = await Services.getInstance(); notifications = service.getNotifications(); - return notifications + return notifications; } function openCloseNotifications() { const notifications = document.querySelector('.notification-board') as HTMLDivElement; @@ -40,7 +40,7 @@ export async function initHeader() { if (currentRoute === 'home') { hideSomeFunctionnalities(); } else { - fetchNotifications() + fetchNotifications(); setInterval(fetchNotifications, 2 * 60 * 1000); } } @@ -82,8 +82,7 @@ async function setNotification(notifications: INotification[]): Promise { } async function fetchNotifications() { - const service = await Services.getInstance() + const service = await Services.getInstance(); const data = service.getNotifications(); - setNotification(data) + setNotification(data); } - diff --git a/src/components/modal/confirmation-modal.ts b/src/components/modal/confirmation-modal.ts index 2cbb8f6..789c905 100644 --- a/src/components/modal/confirmation-modal.ts +++ b/src/components/modal/confirmation-modal.ts @@ -1,13 +1,13 @@ -import ModalService from "../../services/modal.service"; - -const modalService = await ModalService.getInstance(); -export async function confirm() { - modalService.confirmPairing() -} - -export async function closeConfirmationModal() { - modalService.closeConfirmationModal() -} - -(window as any).confirm = confirm; -(window as any).closeConfirmationModal = closeConfirmationModal; \ No newline at end of file +import ModalService from '../../services/modal.service'; + +const modalService = await ModalService.getInstance(); +export async function confirm() { + modalService.confirmPairing(); +} + +export async function closeConfirmationModal() { + modalService.closeConfirmationModal(); +} + +(window as any).confirm = confirm; +(window as any).closeConfirmationModal = closeConfirmationModal; diff --git a/src/pages/home/home.ts b/src/pages/home/home.ts index 2758495..fb6c9a3 100644 --- a/src/pages/home/home.ts +++ b/src/pages/home/home.ts @@ -17,16 +17,16 @@ export async function initHomePage(): Promise { document.querySelectorAll('.tab-content').forEach((content) => content.classList.remove('active')); document.getElementById(tab.getAttribute('data-tab') as string)?.classList.add('active'); - }) + }); }); const service = await Services.getInstance(); - const spAddress = await service.getDeviceAddress() - generateQRCode(spAddress) - displayEmojis(spAddress) + const spAddress = await service.getDeviceAddress(); + generateQRCode(spAddress); + displayEmojis(spAddress); - const notifBell = document.getElementById('notification-bell') - if(notifBell) addSubscription(notifBell, 'click', openCloseNotifications) + const notifBell = document.getElementById('notification-bell'); + if (notifBell) addSubscription(notifBell, 'click', openCloseNotifications); var html5QrcodeScanner = new Html5QrcodeScanner('qr-reader', { fps: 10, qrbox: 250 }, undefined); html5QrcodeScanner.render(onScanSuccess, undefined); diff --git a/src/pages/process-element/process-element.ts b/src/pages/process-element/process-element.ts index 74dfdbd..9c5e7c7 100644 --- a/src/pages/process-element/process-element.ts +++ b/src/pages/process-element/process-element.ts @@ -1,3 +1,4 @@ +import { interpolate } from '../../utils/html.utils'; import Services from '../../services/service'; let currentPageStyle: HTMLStyleElement | null = null; @@ -13,10 +14,6 @@ export async function initProcessElement(id: string, zone: string) { } } -function interpolate(template: string, data: { [key: string]: string }) { - return template.replace(/{{(.*?)}}/g, (_, key) => data[key.trim()]); -} - async function loadPage(data?: any) { const content = document.getElementById('containerId'); if (content && data) { diff --git a/src/pages/process/process.ts b/src/pages/process/process.ts index 1db1373..b587592 100644 --- a/src/pages/process/process.ts +++ b/src/pages/process/process.ts @@ -7,7 +7,7 @@ export async function init() { const element = document.querySelector('select') as HTMLSelectElement; // Create div that wroaps all the elements inside (select, elements selected, search div) to put select inside const wrapper = document.createElement('div'); - if(wrapper) addSubscription(wrapper, 'click', clickOnWrapper) + if (wrapper) addSubscription(wrapper, 'click', clickOnWrapper); wrapper.classList.add('multi-select-component'); wrapper.classList.add('input-field'); @@ -18,16 +18,16 @@ export async function init() { input.classList.add('selected-input'); input.setAttribute('autocomplete', 'off'); input.setAttribute('tabindex', '0'); - if(input) { - addSubscription(input, 'keyup', inputChange) - addSubscription(input, 'keydown', deletePressed) - addSubscription(input, 'click', openOptions) + if (input) { + addSubscription(input, 'keyup', inputChange); + addSubscription(input, 'keydown', deletePressed); + addSubscription(input, 'click', openOptions); } const dropdown_icon = document.createElement('a'); dropdown_icon.classList.add('dropdown-icon'); - if(dropdown_icon) addSubscription(dropdown_icon, 'click', clickDropdown) + if (dropdown_icon) addSubscription(dropdown_icon, 'click', clickDropdown); const autocomplete_list = document.createElement('ul'); autocomplete_list.classList.add('autocomplete-list'); search_div.appendChild(input); @@ -131,7 +131,7 @@ function createToken(wrapper: HTMLElement, value: any) { close.setAttribute('data-option', value); close.setAttribute('data-hits', '0'); close.innerText = 'x'; - if(close) addSubscription(close, 'click', removeToken) + if (close) addSubscription(close, 'click', removeToken); token.appendChild(token_span); token.appendChild(close); inputInderline?.appendChild(token); @@ -188,7 +188,7 @@ function populateAutocompleteList(select: HTMLSelectElement, query: string, drop const li = document.createElement('li'); li.innerText = options_to_show[0]; li.setAttribute('data-value', options_to_show[0]); - if(li) addSubscription(li, 'click', selectOption) + if (li) addSubscription(li, 'click', selectOption); autocomplete_list?.appendChild(li); if (query.length == options_to_show[0].length) { const event = new Event('click'); @@ -199,7 +199,7 @@ function populateAutocompleteList(select: HTMLSelectElement, query: string, drop const li = document.createElement('li'); li.innerText = options_to_show[i]; li.setAttribute('data-value', options_to_show[i]); - if(li) addSubscription(li, 'click', selectOption) + if (li) addSubscription(li, 'click', selectOption); autocomplete_list?.appendChild(li); } } else { @@ -348,7 +348,7 @@ addSubscription(document, 'click', () => { } } } -}) +}); async function showSelectedProcess(elem: MouseEvent) { if (elem) { diff --git a/src/router.ts b/src/router.ts index 95e60d7..aa47771 100644 --- a/src/router.ts +++ b/src/router.ts @@ -12,7 +12,7 @@ const routes: { [key: string]: string } = { export let currentRoute = ''; export async function navigate(path: string) { - cleanSubscriptions() + cleanSubscriptions(); path = path.replace(/^\//, ''); if (path.includes('/')) { const parsedPath = path.split('/')[0]; @@ -29,7 +29,7 @@ async function handleLocation(path: string) { if (path.includes('/')) { path = parsedPath[0]; } - currentRoute = path + currentRoute = path; const routeHtml = routes[path] || routes['home']; const content = document.getElementById('containerId'); @@ -57,10 +57,10 @@ async function handleLocation(path: string) { window.onpopstate = async () => { const services = await Services.getInstance(); - if(!services.isPaired()) { - handleLocation('home') + if (!services.isPaired()) { + handleLocation('home'); } else { - handleLocation('process') + handleLocation('process'); } }; @@ -108,7 +108,7 @@ async function injectHeader() { script.src = '/src/components/header/header.ts'; script.type = 'module'; document.head.appendChild(script); - initHeader() + initHeader(); } } diff --git a/src/services/modal.service.ts b/src/services/modal.service.ts index 1706e81..8fea690 100644 --- a/src/services/modal.service.ts +++ b/src/services/modal.service.ts @@ -41,8 +41,8 @@ export default class ModalService { let html = await fetch('/src/components/modal/confirmation-modal.html').then((res) => res.text()); html = html.replace('{{device1}}', await addressToEmoji(members[0]['sp_addresses'][0])); html = html.replace('{{device2}}', await addressToEmoji(members[0]['sp_addresses'][1])); - container.innerHTML += html; - + container.innerHTML += html; + // Dynamically load the header JS const script = document.createElement('script'); script.src = '/src/components/modal/confirmation-modal.ts'; @@ -57,7 +57,7 @@ export default class ModalService { let members = roles['owner']['members']; console.log(members); // We take all the addresses except our own - const service = await Services.getInstance() + const service = await Services.getInstance(); const localAddress = await service.getDeviceAddress(); console.log('🚀 ~ Routing ~ openConfirmationModal ~ pcd:', pcd); for (const address of members[0]['sp_addresses']) { @@ -65,7 +65,7 @@ export default class ModalService { this.paired_addresses.push(address); } } - await this.injectModal(members) + await this.injectModal(members); const modal = document.getElementById('modal'); if (modal) modal.style.display = 'flex'; // const newScript = document.createElement('script'); diff --git a/src/services/service.ts b/src/services/service.ts index 5eda46e..6a63d30 100644 --- a/src/services/service.ts +++ b/src/services/service.ts @@ -37,7 +37,7 @@ export default class Services { Services.initializing = (async () => { const instance = new Services(); await instance.init(); - instance.routingInstance = await ModalService.getInstance() + instance.routingInstance = await ModalService.getInstance(); return instance; })(); } @@ -57,8 +57,8 @@ export default class Services { public async addWebsocketConnection(url: string): Promise { // const services = await Services.getInstance(); - console.log('Opening new websocket connection'); - const newClient = initWebsocket(url); + console.log('Opening new websocket connection'); + const newClient = initWebsocket(url); } public isPaired(): boolean | undefined { @@ -330,7 +330,7 @@ export default class Services { console.log('🚀 ~ Services ~ createFaucetMessage ~ message:', message); return message; } - + async createNewDevice() { let spAddress = ''; try { diff --git a/src/utils/html.utils.ts b/src/utils/html.utils.ts new file mode 100644 index 0000000..729fc9b --- /dev/null +++ b/src/utils/html.utils.ts @@ -0,0 +1,3 @@ +export function interpolate(template: string, data: { [key: string]: string }) { + return template.replace(/{{(.*?)}}/g, (_, key) => data[key.trim()]); +} diff --git a/src/utils/sp-address.utils.ts b/src/utils/sp-address.utils.ts index 10dcba9..e05471a 100644 --- a/src/utils/sp-address.utils.ts +++ b/src/utils/sp-address.utils.ts @@ -1,175 +1,174 @@ -import Services from "../services/service"; -import { addSubscription } from "./subscription.utils"; -import QRCode from 'qrcode'; - -//Copy Address -export async function copyToClipboard(fullAddress: string) { - try { - await navigator.clipboard.writeText(fullAddress); - alert('Adresse copiée dans le presse-papiers !'); - } catch (err) { - console.error('Failed to copy the address: ', err); - } - } - -//Generate emojis list -export function generateEmojiList(): string[] { - const emojiRanges = [ - [0x1f600, 0x1f64f], - [0x1f300, 0x1f5ff], - [0x1f680, 0x1f6ff], - [0x1f700, 0x1f77f], - ]; - - const emojiList: string[] = []; - for (const range of emojiRanges) { - const [start, end] = range; - for (let i = start; i <= end && emojiList.length < 256; i++) { - emojiList.push(String.fromCodePoint(i)); - } - if (emojiList.length >= 256) { - break; - } - } - - return emojiList.slice(0, 256); -} - -//Adress to emojis -export async function addressToEmoji(text: string): Promise { - //Adress to Hash - const encoder = new TextEncoder(); - const data = encoder.encode(text); - const hashBuffer = await crypto.subtle.digest('SHA-256', data); - - const hash = new Uint8Array(hashBuffer); - const bytes = hash.slice(-4); - - //Hash slice to emojis - const emojiList = generateEmojiList(); - const emojis = Array.from(bytes) - .map((byte) => emojiList[byte]) - .join(''); - return emojis; -}; - - - //Get emojis from other device -async function emojisPairingRequest() { - try { - const container = document.getElementById('containerId'); - - const urlParams: URLSearchParams = new URLSearchParams(window.location.search); - const sp_adress: string | null = urlParams.get('sp_address'); - - if (!sp_adress) { - // console.error("No 'sp_adress' parameter found in the URL."); - return; - } - - const emojis = await addressToEmoji(sp_adress); - const emojiDisplay = container?.querySelector('.pairing-request'); - - if (emojiDisplay) { - emojiDisplay.textContent = '(Request from: ' + emojis + ')'; - } - } catch (err) { - console.error(err); - } - } - - // Display address emojis and other device emojis - export async function displayEmojis(text: string) { - console.log('🚀 ~ Services ~ adressToEmoji'); - try { - const container = document.getElementById('containerId'); - const emojis = await addressToEmoji(text); - const emojiDisplay = container?.querySelector('.emoji-display'); - - if (emojiDisplay) { - emojiDisplay.textContent = emojis; - } - - emojisPairingRequest(); - - initAddressInput(); - } catch (err) { - console.error(err); - } - }; - - // Verify Other address - export function initAddressInput() { - const addressInput = document.getElementById('addressInput') as HTMLInputElement; - const emojiDisplay = document.getElementById('emoji-display-2'); - const okButton = document.getElementById('okButton'); - addSubscription(addressInput, 'input', async () => { - let address = addressInput.value; - - // Vérifie si l'adresse est une URL - try { - const url = new URL(address); - // Si c'est une URL valide, extraire le paramètre sp_address - const urlParams = new URLSearchParams(url.search); - const extractedAddress = urlParams.get('sp_address') || ''; // Prend sp_address ou une chaîne vide - - if (extractedAddress) { - address = extractedAddress; - addressInput.value = address; // Met à jour l'input pour afficher uniquement l'adresse extraite - } - } catch (e) { - // Si ce n'est pas une URL valide, on garde l'adresse originale - console.log("Ce n'est pas une URL valide, on garde l'adresse originale."); - } - if (address) { - const emojis = await addressToEmoji(address); - if (emojiDisplay) { - emojiDisplay.innerHTML = emojis; - } - if (okButton) { - okButton.style.display = 'inline-block'; - } - } else { - if (emojiDisplay) { - emojiDisplay.innerHTML = ''; - } - if (okButton) { - okButton.style.display = 'none'; - } - } - }) - - if (okButton) { - addSubscription(okButton, 'click', () => { - onOkButtonClick(); - }); - } - } - -async function onOkButtonClick() { - const service = await Services.getInstance() - const addressInput = (document.getElementById('addressInput') as HTMLInputElement).value; - await service.sendPairingTx(addressInput); - } - -export async function generateQRCode(spAddress: string) { - try { - const container = document.getElementById('containerId'); - const currentUrl = 'https://' + window.location.host; - const url = await QRCode.toDataURL(currentUrl + '?sp_address=' + spAddress); - const qrCode = container?.querySelector('.qr-code img'); - qrCode?.setAttribute('src', url); - - //Generate Address CopyBtn - const address = container?.querySelector('.sp-address-btn'); - if (address) { - address.textContent = 'Copy address'; - } - const copyBtn = document.getElementById('copyBtn'); - if (copyBtn) { - addSubscription(copyBtn, 'click', () => copyToClipboard(currentUrl + '?sp_address=' + spAddress)) - } - } catch (err) { - console.error(err); - } - }; \ No newline at end of file +import Services from '../services/service'; +import { addSubscription } from './subscription.utils'; +import QRCode from 'qrcode'; + +//Copy Address +export async function copyToClipboard(fullAddress: string) { + try { + await navigator.clipboard.writeText(fullAddress); + alert('Adresse copiée dans le presse-papiers !'); + } catch (err) { + console.error('Failed to copy the address: ', err); + } +} + +//Generate emojis list +export function generateEmojiList(): string[] { + const emojiRanges = [ + [0x1f600, 0x1f64f], + [0x1f300, 0x1f5ff], + [0x1f680, 0x1f6ff], + [0x1f700, 0x1f77f], + ]; + + const emojiList: string[] = []; + for (const range of emojiRanges) { + const [start, end] = range; + for (let i = start; i <= end && emojiList.length < 256; i++) { + emojiList.push(String.fromCodePoint(i)); + } + if (emojiList.length >= 256) { + break; + } + } + + return emojiList.slice(0, 256); +} + +//Adress to emojis +export async function addressToEmoji(text: string): Promise { + //Adress to Hash + const encoder = new TextEncoder(); + const data = encoder.encode(text); + const hashBuffer = await crypto.subtle.digest('SHA-256', data); + + const hash = new Uint8Array(hashBuffer); + const bytes = hash.slice(-4); + + //Hash slice to emojis + const emojiList = generateEmojiList(); + const emojis = Array.from(bytes) + .map((byte) => emojiList[byte]) + .join(''); + return emojis; +} + +//Get emojis from other device +async function emojisPairingRequest() { + try { + const container = document.getElementById('containerId'); + + const urlParams: URLSearchParams = new URLSearchParams(window.location.search); + const sp_adress: string | null = urlParams.get('sp_address'); + + if (!sp_adress) { + // console.error("No 'sp_adress' parameter found in the URL."); + return; + } + + const emojis = await addressToEmoji(sp_adress); + const emojiDisplay = container?.querySelector('.pairing-request'); + + if (emojiDisplay) { + emojiDisplay.textContent = '(Request from: ' + emojis + ')'; + } + } catch (err) { + console.error(err); + } +} + +// Display address emojis and other device emojis +export async function displayEmojis(text: string) { + console.log('🚀 ~ Services ~ adressToEmoji'); + try { + const container = document.getElementById('containerId'); + const emojis = await addressToEmoji(text); + const emojiDisplay = container?.querySelector('.emoji-display'); + + if (emojiDisplay) { + emojiDisplay.textContent = emojis; + } + + emojisPairingRequest(); + + initAddressInput(); + } catch (err) { + console.error(err); + } +} + +// Verify Other address +export function initAddressInput() { + const addressInput = document.getElementById('addressInput') as HTMLInputElement; + const emojiDisplay = document.getElementById('emoji-display-2'); + const okButton = document.getElementById('okButton'); + addSubscription(addressInput, 'input', async () => { + let address = addressInput.value; + + // Vérifie si l'adresse est une URL + try { + const url = new URL(address); + // Si c'est une URL valide, extraire le paramètre sp_address + const urlParams = new URLSearchParams(url.search); + const extractedAddress = urlParams.get('sp_address') || ''; // Prend sp_address ou une chaîne vide + + if (extractedAddress) { + address = extractedAddress; + addressInput.value = address; // Met à jour l'input pour afficher uniquement l'adresse extraite + } + } catch (e) { + // Si ce n'est pas une URL valide, on garde l'adresse originale + console.log("Ce n'est pas une URL valide, on garde l'adresse originale."); + } + if (address) { + const emojis = await addressToEmoji(address); + if (emojiDisplay) { + emojiDisplay.innerHTML = emojis; + } + if (okButton) { + okButton.style.display = 'inline-block'; + } + } else { + if (emojiDisplay) { + emojiDisplay.innerHTML = ''; + } + if (okButton) { + okButton.style.display = 'none'; + } + } + }); + + if (okButton) { + addSubscription(okButton, 'click', () => { + onOkButtonClick(); + }); + } +} + +async function onOkButtonClick() { + const service = await Services.getInstance(); + const addressInput = (document.getElementById('addressInput') as HTMLInputElement).value; + await service.sendPairingTx(addressInput); +} + +export async function generateQRCode(spAddress: string) { + try { + const container = document.getElementById('containerId'); + const currentUrl = 'https://' + window.location.host; + const url = await QRCode.toDataURL(currentUrl + '?sp_address=' + spAddress); + const qrCode = container?.querySelector('.qr-code img'); + qrCode?.setAttribute('src', url); + + //Generate Address CopyBtn + const address = container?.querySelector('.sp-address-btn'); + if (address) { + address.textContent = 'Copy address'; + } + const copyBtn = document.getElementById('copyBtn'); + if (copyBtn) { + addSubscription(copyBtn, 'click', () => copyToClipboard(currentUrl + '?sp_address=' + spAddress)); + } + } catch (err) { + console.error(err); + } +} diff --git a/src/utils/subscription.utils.ts b/src/utils/subscription.utils.ts index 0b79ef3..907a1f2 100644 --- a/src/utils/subscription.utils.ts +++ b/src/utils/subscription.utils.ts @@ -1,16 +1,16 @@ -let subscriptions: { element: Element | Document, event: any, eventHandler: EventListenerOrEventListenerObject }[] = []; - -export function cleanSubscriptions(): void { - console.log("🚀 ~ cleanSubscriptions ~ sub:", subscriptions) - for (const sub of subscriptions) { - const el = sub.element; - const eventHandler = sub.eventHandler; - el.removeEventListener(sub.event, eventHandler); - } - subscriptions = []; - } - -export function addSubscription(element: Element | Document, event: any, eventHandler: EventListenerOrEventListenerObject): void { - subscriptions.push({ element, event, eventHandler }); - element.addEventListener(event, eventHandler); - } \ No newline at end of file +let subscriptions: { element: Element | Document; event: any; eventHandler: EventListenerOrEventListenerObject }[] = []; + +export function cleanSubscriptions(): void { + console.log('🚀 ~ cleanSubscriptions ~ sub:', subscriptions); + for (const sub of subscriptions) { + const el = sub.element; + const eventHandler = sub.eventHandler; + el.removeEventListener(sub.event, eventHandler); + } + subscriptions = []; +} + +export function addSubscription(element: Element | Document, event: any, eventHandler: EventListenerOrEventListenerObject): void { + subscriptions.push({ element, event, eventHandler }); + element.addEventListener(event, eventHandler); +} diff --git a/src/websockets.ts b/src/websockets.ts index c8210ca..db5460c 100644 --- a/src/websockets.ts +++ b/src/websockets.ts @@ -3,127 +3,93 @@ import Services from './services/service'; let ws: WebSocket; let messageQueue: string[] = []; -let services: Services +let services: Services; export async function initWebsocket(url: string) { - ws = new WebSocket(url); - services = await Services.getInstance() + ws = new WebSocket(url); + services = await Services.getInstance(); - if (ws !== null) { - ws.onopen = async (event) => { - console.log('WebSocket connection established'); + if (ws !== null) { + ws.onopen = async (event) => { + console.log('WebSocket connection established'); - const amount = await services.getAmount(); + const amount = await services.getAmount(); - if (amount === 0n) { - const faucetMsg = await services.createFaucetMessage(); - await services.sendFaucetMessage(faucetMsg); + if (amount === 0n) { + const faucetMsg = await services.createFaucetMessage(); + await services.sendFaucetMessage(faucetMsg); + } + while (messageQueue.length > 0) { + const message = messageQueue.shift(); + if (message) { + ws.send(message); } - while (messageQueue.length > 0) { - const message = messageQueue.shift(); - if (message) { - ws.send(message); - } - } - }; + } + }; - // Listen for messages - ws.onmessage = (event) => { - const msgData = event.data; + // Listen for messages + ws.onmessage = (event) => { + const msgData = event.data; - // console.log("Received text message: ", msgData); - (async () => { - if (typeof msgData === 'string') { - try { - const feeRate = 0.0001; - const parsedMessage = JSON.parse(msgData); - // console.log("🚀 ~ WebSocketClient ~ parsedMessage:", parsedMessage) - switch (parsedMessage.flag) { - case 'NewTx': - await services.parseNewTx(parsedMessage.content); - break; - case 'Cipher': - await services.parseCipher(parsedMessage.content); - // device = await services.dumpWallet() - // console.log("🚀 ~ WebSocketClient ~ device:", device) - // await services.saveDevice(device) - break; - } - // By parsing the message, we can link it with existing cached message and return the updated version of the message - // if (res.status === 'FaucetComplete') { - // // we received a faucet tx, there's nothing else to do - // window.alert(`New faucet output\n${res.commited_in}`); - // } else if (res.status === 'TxWaitingCipher') { - // // we received a tx but we don't have the cipher - // console.debug(`received notification in output ${res.commited_in}, waiting for cipher message`); - // } else if (res.status === 'CipherWaitingTx') { - // // we received a cipher but we don't have the key - // console.debug(`received a cipher`); - // } else if (res.status === 'SentWaitingConfirmation') { - // // We are sender and we're waiting for the challenge that will confirm recipient got the transaction and the message - // } else if (res.status === 'MustSpendConfirmation') { - // // we received a challenge for a notification we made - // // that means we can stop rebroadcasting the tx and we must spend the challenge to confirm - // window.alert(`Spending ${res.confirmed_by} to prove our identity`); - // console.debug(`sending confirm message to ${res.recipient}`); - // } else if (res.status === 'ReceivedMustConfirm') { - // // we found a notification and decrypted the cipher - // window.alert(`Received message from ${res.sender}\n${res.plaintext}`); - // // we must spend the commited_in output to sender - // } else if (res.status === 'Complete') { - // window.alert(`Received confirmation that ${res.sender} is the author of message ${res.plaintext}`) - // } else { - // console.debug('Received an unimplemented valid message'); - // } - } catch (error) { - console.error('Received an invalid message:', error); + // console.log("Received text message: ", msgData); + (async () => { + if (typeof msgData === 'string') { + try { + const feeRate = 0.0001; + const parsedMessage = JSON.parse(msgData); + switch (parsedMessage.flag) { + case 'NewTx': + await services.parseNewTx(parsedMessage.content); + break; + case 'Cipher': + await services.parseCipher(parsedMessage.content); + break; } - } else { - console.error('Received a non-string message'); + } catch (error) { + console.error('Received an invalid message:', error); } - })(); - }; + } else { + console.error('Received a non-string message'); + } + })(); + }; - // Listen for possible errors - ws.onerror = (event) => { - console.error('WebSocket error:', event); - }; + // Listen for possible errors + ws.onerror = (event) => { + console.error('WebSocket error:', event); + }; - // Listen for when the connection is closed - ws.onclose = (event) => { - console.log('WebSocket is closed now.'); - }; - } + // Listen for when the connection is closed + ws.onclose = (event) => { + console.log('WebSocket is closed now.'); + }; } +} - // Method to send messages - export async function sendMessage(flag: AnkFlag, message: string): Promise { - if (ws.readyState === WebSocket.OPEN) { - const networkMessage = { - flag: flag, - content: message, - }; - // if(flag === 'Cipher') { - // const services = await Services.getInstance(); - // services.parseCipher(JSON.stringify(networkMessage)) - // } - console.log('Sending message:', JSON.stringify(networkMessage)); - ws.send(JSON.stringify(networkMessage)); - } else { - console.error('WebSocket is not open. ReadyState:', ws.readyState); - messageQueue.push(message); - } +// Method to send messages +export async function sendMessage(flag: AnkFlag, message: string): Promise { + if (ws.readyState === WebSocket.OPEN) { + const networkMessage = { + flag: flag, + content: message, + }; + console.log('Sending message:', JSON.stringify(networkMessage)); + ws.send(JSON.stringify(networkMessage)); + } else { + console.error('WebSocket is not open. ReadyState:', ws.readyState); + messageQueue.push(message); } +} - export function getUrl(): string { - return ws.url; - } +export function getUrl(): string { + return ws.url; +} - export function sendNormalMessage(message: string) { - ws.send(message); - console.log('Sending message:', JSON.stringify(message)); - } +export function sendNormalMessage(message: string) { + ws.send(message); + console.log('Sending message:', JSON.stringify(message)); +} - // Method to close the WebSocket connection - export function close(): void { - ws.close(); - } +// Method to close the WebSocket connection +export function close(): void { + ws.close(); +}