From 7b7d13ce6c40d876231676a2b3cfb1bf779621fe Mon Sep 17 00:00:00 2001 From: NicolasCantu Date: Fri, 28 Mar 2025 12:52:47 +0100 Subject: [PATCH] Various fix to build again the project --- src/components/header/header.ts | 10 +- src/components/modal/confirmation-modal.ts | 6 +- .../qrcode-scanner-component.ts | 2 +- src/pages/account/account.ts | 39 +++++--- src/router.ts | 4 +- src/services/database.service.ts | 19 ++-- src/services/service.ts | 98 +++++++++---------- src/services/storage.service.ts | 4 +- src/utils/sp-address.utils.ts | 19 +--- 9 files changed, 102 insertions(+), 99 deletions(-) diff --git a/src/components/header/header.ts b/src/components/header/header.ts index d3635e4..9e3ae9c 100755 --- a/src/components/header/header.ts +++ b/src/components/header/header.ts @@ -9,7 +9,7 @@ let notifications = []; export async function unpair() { const service = await Services.getInstance(); await service.unpairDevice(); - navigate('home'); + await navigate('home'); } (window as any).unpair = unpair; @@ -28,7 +28,7 @@ function toggleMenu() { async function getNotifications() { const service = await Services.getInstance(); - notifications = service.getNotifications(); + notifications = service.getNotifications() || []; return notifications; } function openCloseNotifications() { @@ -102,8 +102,8 @@ async function setNotification(notifications: any[]): Promise { async function fetchNotifications() { const service = await Services.getInstance(); - const data = service.getNotifications(); - setNotification(data); + const data = service.getNotifications() || []; + await setNotification(data); } async function loadUserProfile() { @@ -204,7 +204,7 @@ async function disconnect() { await Promise.all(registrations.map(registration => registration.unregister())); console.log('Service worker unregistered'); - navigate('home'); + await navigate('home'); setTimeout(() => { window.location.href = window.location.origin; diff --git a/src/components/modal/confirmation-modal.ts b/src/components/modal/confirmation-modal.ts index 789c905..292d875 100755 --- a/src/components/modal/confirmation-modal.ts +++ b/src/components/modal/confirmation-modal.ts @@ -1,9 +1,9 @@ import ModalService from '../../services/modal.service'; const modalService = await ModalService.getInstance(); -export async function confirm() { - modalService.confirmPairing(); -} +// export async function confirm() { +// modalService.confirmPairing(); +// } export async function closeConfirmationModal() { modalService.closeConfirmationModal(); diff --git a/src/components/qrcode-scanner/qrcode-scanner-component.ts b/src/components/qrcode-scanner/qrcode-scanner-component.ts index bff3e08..1e39d3b 100644 --- a/src/components/qrcode-scanner/qrcode-scanner-component.ts +++ b/src/components/qrcode-scanner/qrcode-scanner-component.ts @@ -55,7 +55,7 @@ export default class QrScannerComponent extends HTMLElement { if (spAddress) { // Call the sendPairingTx function with the extracted sp_address try { - await prepareAndSendPairingTx(spAddress); + await prepareAndSendPairingTx(); } catch (e) { console.error('Failed to pair:', e); } diff --git a/src/pages/account/account.ts b/src/pages/account/account.ts index 4515168..ca58d43 100755 --- a/src/pages/account/account.ts +++ b/src/pages/account/account.ts @@ -52,6 +52,23 @@ let isAddingRow = false; let currentRow: HTMLTableRowElement | null = null; let currentMode: keyof typeof STORAGE_KEYS = 'pairing'; +interface Process { + states: Array<{ + committed_in: string; + keys: {}; + pcd_commitment: { + counter: string; + }; + public_data: { + memberPublicName?: string; + }; + roles: { + pairing?: {}; + }; + state_id: string; + validation_tokens: Array; + }>; +} class AccountElement extends HTMLElement { private dom: Node; @@ -836,7 +853,9 @@ private async showProcess(): Promise { try { const service = await Services.getInstance(); const myProcesses = await service.getMyProcesses(); - this.updateProcessTableContent(myProcesses); + if (myProcesses) { + this.updateProcessTableContent(myProcesses); + } } catch (error) { console.error('Error loading processes:', error); const tbody = processContent.querySelector('tbody'); @@ -853,11 +872,11 @@ private async showProcess(): Promise { } } -private updateProcessTableContent(processes: any[]): void { +private async updateProcessTableContent(processes: Process[] | any): Promise { const tbody = this.shadowRoot?.querySelector('#process-table tbody'); if (!tbody) return; - if (processes.length === 0) { + if (!processes || processes.length === 0) { tbody.innerHTML = ` No processes found @@ -958,9 +977,11 @@ private handleLogout(): void { // Fonctions de gestion des contrats -private showContractPopup(contractId: string) { - // Empêcher la navigation par défaut - event?.preventDefault(); +private showContractPopup(contractId: string, event?: Event) { + if (event) { + event.preventDefault(); + } + // Check if the contract exists in mockContracts const contract = mockContracts[contractId as keyof typeof mockContracts]; if (!contract) { @@ -968,7 +989,6 @@ private showContractPopup(contractId: string) { return; } - // Créer la popup const popup = document.createElement('div'); popup.className = 'contract-popup-overlay'; popup.innerHTML = ` @@ -987,10 +1007,8 @@ private showContractPopup(contractId: string) { `; - // Ajouter la popup au body this.shadowRoot?.appendChild(popup); - // Gérer la fermeture const closeBtn = popup.querySelector('.close-contract-popup'); const closePopup = () => popup.remove(); @@ -1065,8 +1083,7 @@ private async showPairing(): Promise { const pairingProcess = await service.getProcess(pairingProcessId); console.log('Pairing Process:', pairingProcess); - const userName = pairingProcess?.states?.[0]?.metadata?.userName - || pairingProcess?.states?.[0]?.metadata?.name + const userName = pairingProcess?.states?.[0]?.public_data?.memberPublicName || localStorage.getItem('userName') console.log('Username found:', userName); diff --git a/src/router.ts b/src/router.ts index 67a002f..54d6345 100755 --- a/src/router.ts +++ b/src/router.ts @@ -155,7 +155,7 @@ export async function init(): Promise { console.log('Detected source \'lecoffre\'') // We pair first if necessary if (!services.isPaired()) { - await prepareAndSendPairingTx(false); + await prepareAndSendPairingTx(); await services.confirmPairing(); } if (services.isPaired()) { @@ -182,7 +182,7 @@ export async function init(): Promise { setTimeout(async () => { try { // check if we have a shared secret with that address - await prepareAndSendPairingTx(pairingAddress); + await prepareAndSendPairingTx(); } catch (e) { console.error('Failed to pair:', e); } diff --git a/src/services/database.service.ts b/src/services/database.service.ts index f1321aa..e5c7be7 100755 --- a/src/services/database.service.ts +++ b/src/services/database.service.ts @@ -144,10 +144,10 @@ export class Database { // Set up a periodic check to ensure the service worker is active and to send a SYNC message. this.serviceWorkerCheckIntervalId = window.setInterval(async () => { - const activeWorker = this.serviceWorkerRegistration.active || (await this.waitForServiceWorkerActivation(this.serviceWorkerRegistration)); + const activeWorker = this.serviceWorkerRegistration?.active || (await this.waitForServiceWorkerActivation(this.serviceWorkerRegistration!)); const service = await Services.getInstance(); const payload = await service.getMyProcesses(); - if (payload.length != 0) { + if (payload!.length != 0) { activeWorker?.postMessage({ type: 'SCAN', payload }); } }, 5000); @@ -199,9 +199,9 @@ export class Database { } } - private async handleDownloadList(downloadList: string[]): void { + private async handleDownloadList(downloadList: string[]): Promise { // Download the missing data - let requestedStateId = []; + let requestedStateId: string[] = []; const service = await Services.getInstance(); for (const hash of downloadList) { const diff = await service.getDiffByValue(hash); @@ -250,7 +250,7 @@ export class Database { } else if (data.type === 'TO_DOWNLOAD') { console.log(`Received missing data ${data}`); // Download the missing data - let requestedStateId = []; + let requestedStateId: string[] = []; for (const hash of data.data) { try { const valueBytes = await service.fetchValueFromStorage(hash); @@ -263,9 +263,12 @@ export class Database { console.log('Request data from managers of the process'); // get the diff from db const diff = await service.getDiffByValue(hash); - const processId = diff.process_id; - const stateId = diff.state_id; - const roles = diff.roles; + if (diff === null) { + continue; + } + const processId = diff!.process_id; + const stateId = diff!.state_id; + const roles = diff!.roles; if (!requestedStateId.includes(stateId)) { await service.requestDataFromPeers(processId, [stateId], [roles]); requestedStateId.push(stateId); diff --git a/src/services/service.ts b/src/services/service.ts index a5d8c41..71f23df 100755 --- a/src/services/service.ts +++ b/src/services/service.ts @@ -3,9 +3,10 @@ import { INotification } from '~/models/notification.model'; import { IProcess } from '~/models/process.model'; // import Database from './database'; import { initWebsocket, sendMessage } from '../websockets'; -import { ApiReturn, Device, HandshakeMessage, Member, Process, RoleDefinition, SecretsStore, UserDiff } from '../../pkg/sdk_client'; +import { ApiReturn, Device, HandshakeMessage, Member, OutPointProcessMap, Process, ProcessState, RoleDefinition, SecretsStore, UserDiff } from '../../pkg/sdk_client'; import ModalService from './modal.service'; import Database from './database.service'; +import { navigate } from '../router'; import { storeData, retrieveData, testData } from './storage.service'; import { BackUp } from '~/models/backup.model'; @@ -23,7 +24,7 @@ export default class Services { private processId: string | null = null; private stateId: string | null = null; private sdkClient: any; - private myProcesses: Set = new Set(); + private myProcesses: Set = new Set(); private notifications: any[] | null = null; private subscriptions: { element: Element; event: string; eventHandler: string }[] = []; private database: any; @@ -331,7 +332,7 @@ export default class Services { }, ], storages: [STORAGEURL] - } + }, dm: { members: [ { sp_addresses: myAddresses }, @@ -378,7 +379,7 @@ export default class Services { } public async createNotaryProcess(notaryTokens: string[]): Promise { - const notaryProcess = this.lookForNotaryProcess(); + const notaryProcess = await this.lookForNotaryProcess(); if (notaryProcess) { throw new Error('There is already a notary process'); } @@ -466,12 +467,18 @@ export default class Services { private async lookForNotaryProcess(): Promise { const processes = await this.getMyProcesses(); + if (processes === null) { + return null; + } for (const processId of processes) { try { const process = await this.getProcess(processId); const roles = this.getRoles(process); - const roleKeys = Object.keys(roles); + if (!roles) { + throw new Error('Failed to get roles'); + } + const roleKeys = Object.keys(roles!); if (roleKeys.includes("notary")) { let publicData; @@ -504,7 +511,7 @@ export default class Services { return null; } - public async updateProcess(process: Process, new_state: any, roles: Record | null): Promise { + public async updateProcess(process: Process, privateData: Record, publicData: Record, roles: Record | null): Promise { // If roles is null, we just take the last commited state roles if (!roles) { roles = this.getRoles(process); @@ -512,18 +519,17 @@ export default class Services { // We should check that we have the right to change the roles here, or maybe it's better leave it to the wasm console.log('Provided new roles:', JSON.stringify(roles)); } - let members = new Set(); - for (const role of Object.values(roles)) { + let members: Set = new Set(); + for (const role of Object.values(roles!)) { for (const member of role.members) { members.add(member) } } - console.log(members); await this.checkConnections([...members]); const membersList = this.getAllMembers(); try { console.log(process); - return this.sdkClient.update_process(process, newState, roles, publicData, membersList); + return this.sdkClient.update_process(process, privateData, roles, publicData, membersList); } catch (e) { throw new Error(`Failed to update process: ${e}`); } @@ -547,7 +553,7 @@ export default class Services { throw new Error('Unknown process'); } try { - return this.sdkClient.create_response_prd(process, pcdMerkleRoot, this.getAllMembers()); + return this.sdkClient.create_response_prd(process, stateId, this.getAllMembers()); } catch (e) { throw new Error(`Failed to create response prd: ${e}`); } @@ -777,7 +783,7 @@ export default class Services { const newDevice = this.dumpDeviceFromMemory(); console.log(newDevice); await this.saveDeviceInDatabase(newDevice); - navigate('account'); + await navigate('account'); } public async pairDevice() { @@ -1046,26 +1052,27 @@ export default class Services { return processes; } - public async getChildrenOfProcess(processId: string): Promise { - const processes = await this.getProcesses(); + // TODO rewrite that it's a mess and we don't use it now + // public async getChildrenOfProcess(processId: string): Promise { + // const processes = await this.getProcesses(); - const res = []; - for (const [hash, process] of Object.entries(processes)) { - const firstState = process.states[0]; - const pcdCommitment = firstState['pcd_commitment']; - try { - const parentIdHash = pcdCommitment['parent_id']; - const diff = await this.getDiffByValue(parentIdHash); - if (diff && diff['new_value'] === processId) { - res.push(JSON.stringify(process)); - } - } catch (e) { - continue; - } - } + // const res = []; + // for (const [hash, process] of Object.entries(processes)) { + // const firstState = process.states[0]; + // const pcdCommitment = firstState['pcd_commitment']; + // try { + // const parentIdHash = pcdCommitment['parent_id']; + // const diff = await this.getDiffByValue(parentIdHash); + // if (diff && diff['new_value'] === processId) { + // res.push(JSON.stringify(process)); + // } + // } catch (e) { + // continue; + // } + // } - return res; - } + // return res; + // } public async restoreProcessesFromBackUp(processes: Record) { const db = await Database.getInstance(); @@ -1283,7 +1290,7 @@ export default class Services { } setTimeout(async () => { - const newProcesses = handshakeMsg.processes_list; + const newProcesses: OutPointProcessMap = handshakeMsg.processes_list; if (newProcesses && Object.keys(newProcesses).length !== 0) { for (const [processId, process] of Object.entries(newProcesses)) { const existing = await this.getProcess(processId); @@ -1350,7 +1357,7 @@ export default class Services { } public getAddressesForMemberId(memberId: string): string[] | null { - return this.membersList[memberId]; + return this.membersList[memberId].sp_addresses; } public compareMembers(memberA: string[], memberB: string[]): boolean { @@ -1385,9 +1392,8 @@ export default class Services { if (firstState && firstState.roles && Object.keys(firstState.roles).length != 0) { return firstState!.roles; } - } else { - return null; } + return null; } public getPublicData(process: Process): Record | null { @@ -1399,9 +1405,8 @@ export default class Services { if (firstState && firstState.public_data && Object.keys(firstState.public_data).length != 0) { return firstState!.public_data; } - } else { - return null; } + return null; } public getProcessName(process: Process): string | null { @@ -1415,7 +1420,7 @@ export default class Services { } } - public async getMyProcesses(): Promise { + public async getMyProcesses(): Promise { try { const processes = await this.getProcesses(); @@ -1437,6 +1442,7 @@ export default class Services { return Array.from(this.myProcesses); } catch (e) { console.error("Failed to get processes:", e); + return null; } } @@ -1495,22 +1501,10 @@ export default class Services { } public async updateMemberPublicName(process: Process, newName: string): Promise { - const lastState = this.getLastCommitedState(process); - if (!lastState) { - throw new Error('No committed state found'); - } - - // Create new state with updated memberPublicName - const newState = { - ...lastState, - public_data: { - ...lastState.public_data, - memberPublicName: newName, - pairedAddresses: lastState.public_data.pairedAddresses // Préserver les adresses existantes - } + const publicData = { + 'memberPublicName': newName }; - // Update the process with new state - return await this.updateProcess(process, newState, null); + return await this.updateProcess(process, {}, publicData, null); } } diff --git a/src/services/storage.service.ts b/src/services/storage.service.ts index fbb31dd..47ee776 100644 --- a/src/services/storage.service.ts +++ b/src/services/storage.service.ts @@ -23,7 +23,7 @@ export async function storeData(servers: string[], key: string, value: Blob, ttl } return response; } catch (error) { - if (error?.response?.status === 409) { + if (axios.isAxiosError(error) && error.response?.status === 409) { return null; } console.error('Error storing data:', error); @@ -58,7 +58,7 @@ interface TestResponse { } export async function testData(servers: string[], key: string): Promise | null> { - const res = {}; + const res: Record = {}; for (const server of servers) { res[server] = null; try { diff --git a/src/utils/sp-address.utils.ts b/src/utils/sp-address.utils.ts index 2fbc023..fcbd196 100755 --- a/src/utils/sp-address.utils.ts +++ b/src/utils/sp-address.utils.ts @@ -154,12 +154,10 @@ export function initAddressInput() { } } +// TODO I don't think this is still relevant, but we need to talk about what we expect this button to do async function onOkButtonClick() { - const container = getCorrectDOM('login-4nk-component') as HTMLElement - const secondDeviceAddress = (container.querySelector('#addressInput') as HTMLInputElement).value; try { - // Connect to target, if necessary - await prepareAndSendPairingTx(secondDeviceAddress); + await prepareAndSendPairingTx(); } catch (e) { console.error(`onOkButtonClick error: ${e}`); } @@ -175,7 +173,7 @@ async function onCreateButtonClick() { } } -export async function prepareAndSendPairingTx(promptName: boolean = false): Promise { +export async function prepareAndSendPairingTx(): Promise { const service = await Services.getInstance(); try { @@ -184,22 +182,13 @@ export async function prepareAndSendPairingTx(promptName: boolean = false): Prom throw e; } - // Prompt the user for a username. - let userName; - if (promptName) { - userName = prompt("Please enter your user name:"); - } else { - userName = ""; - } - try { const relayAddress = service.getAllRelays(); const createPairingProcessReturn = await service.createPairingProcess( - userName, + "", [], relayAddress[0].spAddress, 1, - userName ); if (!createPairingProcessReturn.updated_process) {