Various fix to build again the project

This commit is contained in:
NicolasCantu 2025-03-28 12:52:47 +01:00
parent cc9396c4b8
commit 7b7d13ce6c
9 changed files with 102 additions and 99 deletions

View File

@ -9,7 +9,7 @@ let notifications = [];
export async function unpair() { export async function unpair() {
const service = await Services.getInstance(); const service = await Services.getInstance();
await service.unpairDevice(); await service.unpairDevice();
navigate('home'); await navigate('home');
} }
(window as any).unpair = unpair; (window as any).unpair = unpair;
@ -28,7 +28,7 @@ function toggleMenu() {
async function getNotifications() { async function getNotifications() {
const service = await Services.getInstance(); const service = await Services.getInstance();
notifications = service.getNotifications(); notifications = service.getNotifications() || [];
return notifications; return notifications;
} }
function openCloseNotifications() { function openCloseNotifications() {
@ -102,8 +102,8 @@ async function setNotification(notifications: any[]): Promise<void> {
async function fetchNotifications() { async function fetchNotifications() {
const service = await Services.getInstance(); const service = await Services.getInstance();
const data = service.getNotifications(); const data = service.getNotifications() || [];
setNotification(data); await setNotification(data);
} }
async function loadUserProfile() { async function loadUserProfile() {
@ -204,7 +204,7 @@ async function disconnect() {
await Promise.all(registrations.map(registration => registration.unregister())); await Promise.all(registrations.map(registration => registration.unregister()));
console.log('Service worker unregistered'); console.log('Service worker unregistered');
navigate('home'); await navigate('home');
setTimeout(() => { setTimeout(() => {
window.location.href = window.location.origin; window.location.href = window.location.origin;

View File

@ -1,9 +1,9 @@
import ModalService from '../../services/modal.service'; import ModalService from '../../services/modal.service';
const modalService = await ModalService.getInstance(); const modalService = await ModalService.getInstance();
export async function confirm() { // export async function confirm() {
modalService.confirmPairing(); // modalService.confirmPairing();
} // }
export async function closeConfirmationModal() { export async function closeConfirmationModal() {
modalService.closeConfirmationModal(); modalService.closeConfirmationModal();

View File

@ -55,7 +55,7 @@ export default class QrScannerComponent extends HTMLElement {
if (spAddress) { if (spAddress) {
// Call the sendPairingTx function with the extracted sp_address // Call the sendPairingTx function with the extracted sp_address
try { try {
await prepareAndSendPairingTx(spAddress); await prepareAndSendPairingTx();
} catch (e) { } catch (e) {
console.error('Failed to pair:', e); console.error('Failed to pair:', e);
} }

View File

@ -52,6 +52,23 @@ let isAddingRow = false;
let currentRow: HTMLTableRowElement | null = null; let currentRow: HTMLTableRowElement | null = null;
let currentMode: keyof typeof STORAGE_KEYS = 'pairing'; 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<any>;
}>;
}
class AccountElement extends HTMLElement { class AccountElement extends HTMLElement {
private dom: Node; private dom: Node;
@ -836,7 +853,9 @@ private async showProcess(): Promise<void> {
try { try {
const service = await Services.getInstance(); const service = await Services.getInstance();
const myProcesses = await service.getMyProcesses(); const myProcesses = await service.getMyProcesses();
if (myProcesses) {
this.updateProcessTableContent(myProcesses); this.updateProcessTableContent(myProcesses);
}
} catch (error) { } catch (error) {
console.error('Error loading processes:', error); console.error('Error loading processes:', error);
const tbody = processContent.querySelector('tbody'); const tbody = processContent.querySelector('tbody');
@ -853,11 +872,11 @@ private async showProcess(): Promise<void> {
} }
} }
private updateProcessTableContent(processes: any[]): void { private async updateProcessTableContent(processes: Process[] | any): Promise<void> {
const tbody = this.shadowRoot?.querySelector('#process-table tbody'); const tbody = this.shadowRoot?.querySelector('#process-table tbody');
if (!tbody) return; if (!tbody) return;
if (processes.length === 0) { if (!processes || processes.length === 0) {
tbody.innerHTML = ` tbody.innerHTML = `
<tr> <tr>
<td colspan="3">No processes found</td> <td colspan="3">No processes found</td>
@ -958,9 +977,11 @@ private handleLogout(): void {
// Fonctions de gestion des contrats // Fonctions de gestion des contrats
private showContractPopup(contractId: string) { private showContractPopup(contractId: string, event?: Event) {
// Empêcher la navigation par défaut if (event) {
event?.preventDefault(); event.preventDefault();
}
// Check if the contract exists in mockContracts // Check if the contract exists in mockContracts
const contract = mockContracts[contractId as keyof typeof mockContracts]; const contract = mockContracts[contractId as keyof typeof mockContracts];
if (!contract) { if (!contract) {
@ -968,7 +989,6 @@ private showContractPopup(contractId: string) {
return; return;
} }
// Créer la popup
const popup = document.createElement('div'); const popup = document.createElement('div');
popup.className = 'contract-popup-overlay'; popup.className = 'contract-popup-overlay';
popup.innerHTML = ` popup.innerHTML = `
@ -987,10 +1007,8 @@ private showContractPopup(contractId: string) {
</div> </div>
`; `;
// Ajouter la popup au body
this.shadowRoot?.appendChild(popup); this.shadowRoot?.appendChild(popup);
// Gérer la fermeture
const closeBtn = popup.querySelector('.close-contract-popup'); const closeBtn = popup.querySelector('.close-contract-popup');
const closePopup = () => popup.remove(); const closePopup = () => popup.remove();
@ -1065,8 +1083,7 @@ private async showPairing(): Promise<void> {
const pairingProcess = await service.getProcess(pairingProcessId); const pairingProcess = await service.getProcess(pairingProcessId);
console.log('Pairing Process:', pairingProcess); console.log('Pairing Process:', pairingProcess);
const userName = pairingProcess?.states?.[0]?.metadata?.userName const userName = pairingProcess?.states?.[0]?.public_data?.memberPublicName
|| pairingProcess?.states?.[0]?.metadata?.name
|| localStorage.getItem('userName') || localStorage.getItem('userName')
console.log('Username found:', userName); console.log('Username found:', userName);

View File

@ -155,7 +155,7 @@ export async function init(): Promise<void> {
console.log('Detected source \'lecoffre\'') console.log('Detected source \'lecoffre\'')
// We pair first if necessary // We pair first if necessary
if (!services.isPaired()) { if (!services.isPaired()) {
await prepareAndSendPairingTx(false); await prepareAndSendPairingTx();
await services.confirmPairing(); await services.confirmPairing();
} }
if (services.isPaired()) { if (services.isPaired()) {
@ -182,7 +182,7 @@ export async function init(): Promise<void> {
setTimeout(async () => { setTimeout(async () => {
try { try {
// check if we have a shared secret with that address // check if we have a shared secret with that address
await prepareAndSendPairingTx(pairingAddress); await prepareAndSendPairingTx();
} catch (e) { } catch (e) {
console.error('Failed to pair:', e); console.error('Failed to pair:', e);
} }

View File

@ -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. // Set up a periodic check to ensure the service worker is active and to send a SYNC message.
this.serviceWorkerCheckIntervalId = window.setInterval(async () => { 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 service = await Services.getInstance();
const payload = await service.getMyProcesses(); const payload = await service.getMyProcesses();
if (payload.length != 0) { if (payload!.length != 0) {
activeWorker?.postMessage({ type: 'SCAN', payload }); activeWorker?.postMessage({ type: 'SCAN', payload });
} }
}, 5000); }, 5000);
@ -199,9 +199,9 @@ export class Database {
} }
} }
private async handleDownloadList(downloadList: string[]): void { private async handleDownloadList(downloadList: string[]): Promise<void> {
// Download the missing data // Download the missing data
let requestedStateId = []; let requestedStateId: string[] = [];
const service = await Services.getInstance(); const service = await Services.getInstance();
for (const hash of downloadList) { for (const hash of downloadList) {
const diff = await service.getDiffByValue(hash); const diff = await service.getDiffByValue(hash);
@ -250,7 +250,7 @@ export class Database {
} else if (data.type === 'TO_DOWNLOAD') { } else if (data.type === 'TO_DOWNLOAD') {
console.log(`Received missing data ${data}`); console.log(`Received missing data ${data}`);
// Download the missing data // Download the missing data
let requestedStateId = []; let requestedStateId: string[] = [];
for (const hash of data.data) { for (const hash of data.data) {
try { try {
const valueBytes = await service.fetchValueFromStorage(hash); const valueBytes = await service.fetchValueFromStorage(hash);
@ -263,9 +263,12 @@ export class Database {
console.log('Request data from managers of the process'); console.log('Request data from managers of the process');
// get the diff from db // get the diff from db
const diff = await service.getDiffByValue(hash); const diff = await service.getDiffByValue(hash);
const processId = diff.process_id; if (diff === null) {
const stateId = diff.state_id; continue;
const roles = diff.roles; }
const processId = diff!.process_id;
const stateId = diff!.state_id;
const roles = diff!.roles;
if (!requestedStateId.includes(stateId)) { if (!requestedStateId.includes(stateId)) {
await service.requestDataFromPeers(processId, [stateId], [roles]); await service.requestDataFromPeers(processId, [stateId], [roles]);
requestedStateId.push(stateId); requestedStateId.push(stateId);

View File

@ -3,9 +3,10 @@ import { INotification } from '~/models/notification.model';
import { IProcess } from '~/models/process.model'; import { IProcess } from '~/models/process.model';
// import Database from './database'; // import Database from './database';
import { initWebsocket, sendMessage } from '../websockets'; 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 ModalService from './modal.service';
import Database from './database.service'; import Database from './database.service';
import { navigate } from '../router';
import { storeData, retrieveData, testData } from './storage.service'; import { storeData, retrieveData, testData } from './storage.service';
import { BackUp } from '~/models/backup.model'; import { BackUp } from '~/models/backup.model';
@ -23,7 +24,7 @@ export default class Services {
private processId: string | null = null; private processId: string | null = null;
private stateId: string | null = null; private stateId: string | null = null;
private sdkClient: any; private sdkClient: any;
private myProcesses: Set = new Set(); private myProcesses: Set<string> = new Set();
private notifications: any[] | null = null; private notifications: any[] | null = null;
private subscriptions: { element: Element; event: string; eventHandler: string }[] = []; private subscriptions: { element: Element; event: string; eventHandler: string }[] = [];
private database: any; private database: any;
@ -331,7 +332,7 @@ export default class Services {
}, },
], ],
storages: [STORAGEURL] storages: [STORAGEURL]
} },
dm: { dm: {
members: [ members: [
{ sp_addresses: myAddresses }, { sp_addresses: myAddresses },
@ -378,7 +379,7 @@ export default class Services {
} }
public async createNotaryProcess(notaryTokens: string[]): Promise<ApiReturn> { public async createNotaryProcess(notaryTokens: string[]): Promise<ApiReturn> {
const notaryProcess = this.lookForNotaryProcess(); const notaryProcess = await this.lookForNotaryProcess();
if (notaryProcess) { if (notaryProcess) {
throw new Error('There is already a notary process'); throw new Error('There is already a notary process');
} }
@ -466,12 +467,18 @@ export default class Services {
private async lookForNotaryProcess(): Promise<string | null> { private async lookForNotaryProcess(): Promise<string | null> {
const processes = await this.getMyProcesses(); const processes = await this.getMyProcesses();
if (processes === null) {
return null;
}
for (const processId of processes) { for (const processId of processes) {
try { try {
const process = await this.getProcess(processId); const process = await this.getProcess(processId);
const roles = this.getRoles(process); 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")) { if (roleKeys.includes("notary")) {
let publicData; let publicData;
@ -504,7 +511,7 @@ export default class Services {
return null; return null;
} }
public async updateProcess(process: Process, new_state: any, roles: Record<string, RoleDefinition> | null): Promise<ApiReturn> { public async updateProcess(process: Process, privateData: Record<string, any>, publicData: Record<string, any>, roles: Record<string, RoleDefinition> | null): Promise<ApiReturn> {
// If roles is null, we just take the last commited state roles // If roles is null, we just take the last commited state roles
if (!roles) { if (!roles) {
roles = this.getRoles(process); 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 // 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)); console.log('Provided new roles:', JSON.stringify(roles));
} }
let members = new Set(); let members: Set<Member> = new Set();
for (const role of Object.values(roles)) { for (const role of Object.values(roles!)) {
for (const member of role.members) { for (const member of role.members) {
members.add(member) members.add(member)
} }
} }
console.log(members);
await this.checkConnections([...members]); await this.checkConnections([...members]);
const membersList = this.getAllMembers(); const membersList = this.getAllMembers();
try { try {
console.log(process); 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) { } catch (e) {
throw new Error(`Failed to update process: ${e}`); throw new Error(`Failed to update process: ${e}`);
} }
@ -547,7 +553,7 @@ export default class Services {
throw new Error('Unknown process'); throw new Error('Unknown process');
} }
try { try {
return this.sdkClient.create_response_prd(process, pcdMerkleRoot, this.getAllMembers()); return this.sdkClient.create_response_prd(process, stateId, this.getAllMembers());
} catch (e) { } catch (e) {
throw new Error(`Failed to create response prd: ${e}`); throw new Error(`Failed to create response prd: ${e}`);
} }
@ -777,7 +783,7 @@ export default class Services {
const newDevice = this.dumpDeviceFromMemory(); const newDevice = this.dumpDeviceFromMemory();
console.log(newDevice); console.log(newDevice);
await this.saveDeviceInDatabase(newDevice); await this.saveDeviceInDatabase(newDevice);
navigate('account'); await navigate('account');
} }
public async pairDevice() { public async pairDevice() {
@ -1046,26 +1052,27 @@ export default class Services {
return processes; return processes;
} }
public async getChildrenOfProcess(processId: string): Promise<string[]> { // TODO rewrite that it's a mess and we don't use it now
const processes = await this.getProcesses(); // public async getChildrenOfProcess(processId: string): Promise<string[]> {
// const processes = await this.getProcesses();
const res = []; // const res = [];
for (const [hash, process] of Object.entries(processes)) { // for (const [hash, process] of Object.entries(processes)) {
const firstState = process.states[0]; // const firstState = process.states[0];
const pcdCommitment = firstState['pcd_commitment']; // const pcdCommitment = firstState['pcd_commitment'];
try { // try {
const parentIdHash = pcdCommitment['parent_id']; // const parentIdHash = pcdCommitment['parent_id'];
const diff = await this.getDiffByValue(parentIdHash); // const diff = await this.getDiffByValue(parentIdHash);
if (diff && diff['new_value'] === processId) { // if (diff && diff['new_value'] === processId) {
res.push(JSON.stringify(process)); // res.push(JSON.stringify(process));
} // }
} catch (e) { // } catch (e) {
continue; // continue;
} // }
} // }
return res; // return res;
} // }
public async restoreProcessesFromBackUp(processes: Record<string, Process>) { public async restoreProcessesFromBackUp(processes: Record<string, Process>) {
const db = await Database.getInstance(); const db = await Database.getInstance();
@ -1283,7 +1290,7 @@ export default class Services {
} }
setTimeout(async () => { setTimeout(async () => {
const newProcesses = handshakeMsg.processes_list; const newProcesses: OutPointProcessMap = handshakeMsg.processes_list;
if (newProcesses && Object.keys(newProcesses).length !== 0) { if (newProcesses && Object.keys(newProcesses).length !== 0) {
for (const [processId, process] of Object.entries(newProcesses)) { for (const [processId, process] of Object.entries(newProcesses)) {
const existing = await this.getProcess(processId); const existing = await this.getProcess(processId);
@ -1350,7 +1357,7 @@ export default class Services {
} }
public getAddressesForMemberId(memberId: string): string[] | null { public getAddressesForMemberId(memberId: string): string[] | null {
return this.membersList[memberId]; return this.membersList[memberId].sp_addresses;
} }
public compareMembers(memberA: string[], memberB: string[]): boolean { 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) { if (firstState && firstState.roles && Object.keys(firstState.roles).length != 0) {
return firstState!.roles; return firstState!.roles;
} }
} else {
return null;
} }
return null;
} }
public getPublicData(process: Process): Record<string, any> | null { public getPublicData(process: Process): Record<string, any> | null {
@ -1399,9 +1405,8 @@ export default class Services {
if (firstState && firstState.public_data && Object.keys(firstState.public_data).length != 0) { if (firstState && firstState.public_data && Object.keys(firstState.public_data).length != 0) {
return firstState!.public_data; return firstState!.public_data;
} }
} else {
return null;
} }
return null;
} }
public getProcessName(process: Process): string | null { public getProcessName(process: Process): string | null {
@ -1415,7 +1420,7 @@ export default class Services {
} }
} }
public async getMyProcesses(): Promise<string[]> { public async getMyProcesses(): Promise<string[] | null> {
try { try {
const processes = await this.getProcesses(); const processes = await this.getProcesses();
@ -1437,6 +1442,7 @@ export default class Services {
return Array.from(this.myProcesses); return Array.from(this.myProcesses);
} catch (e) { } catch (e) {
console.error("Failed to get processes:", 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<ApiReturn> { public async updateMemberPublicName(process: Process, newName: string): Promise<ApiReturn> {
const lastState = this.getLastCommitedState(process); const publicData = {
if (!lastState) { 'memberPublicName': newName
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
}
}; };
// Update the process with new state return await this.updateProcess(process, {}, publicData, null);
return await this.updateProcess(process, newState, null);
} }
} }

View File

@ -23,7 +23,7 @@ export async function storeData(servers: string[], key: string, value: Blob, ttl
} }
return response; return response;
} catch (error) { } catch (error) {
if (error?.response?.status === 409) { if (axios.isAxiosError(error) && error.response?.status === 409) {
return null; return null;
} }
console.error('Error storing data:', error); console.error('Error storing data:', error);
@ -58,7 +58,7 @@ interface TestResponse {
} }
export async function testData(servers: string[], key: string): Promise<Record<string, boolean | null> | null> { export async function testData(servers: string[], key: string): Promise<Record<string, boolean | null> | null> {
const res = {}; const res: Record<string, boolean | null> = {};
for (const server of servers) { for (const server of servers) {
res[server] = null; res[server] = null;
try { try {

View File

@ -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() { async function onOkButtonClick() {
const container = getCorrectDOM('login-4nk-component') as HTMLElement
const secondDeviceAddress = (container.querySelector('#addressInput') as HTMLInputElement).value;
try { try {
// Connect to target, if necessary await prepareAndSendPairingTx();
await prepareAndSendPairingTx(secondDeviceAddress);
} catch (e) { } catch (e) {
console.error(`onOkButtonClick error: ${e}`); console.error(`onOkButtonClick error: ${e}`);
} }
@ -175,7 +173,7 @@ async function onCreateButtonClick() {
} }
} }
export async function prepareAndSendPairingTx(promptName: boolean = false): Promise<void> { export async function prepareAndSendPairingTx(): Promise<void> {
const service = await Services.getInstance(); const service = await Services.getInstance();
try { try {
@ -184,22 +182,13 @@ export async function prepareAndSendPairingTx(promptName: boolean = false): Prom
throw e; throw e;
} }
// Prompt the user for a username.
let userName;
if (promptName) {
userName = prompt("Please enter your user name:");
} else {
userName = "";
}
try { try {
const relayAddress = service.getAllRelays(); const relayAddress = service.getAllRelays();
const createPairingProcessReturn = await service.createPairingProcess( const createPairingProcessReturn = await service.createPairingProcess(
userName, "",
[], [],
relayAddress[0].spAddress, relayAddress[0].spAddress,
1, 1,
userName
); );
if (!createPairingProcessReturn.updated_process) { if (!createPairingProcessReturn.updated_process) {