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() {
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<void> {
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;

View File

@ -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();

View File

@ -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);
}

View File

@ -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<any>;
}>;
}
class AccountElement extends HTMLElement {
private dom: Node;
@ -836,7 +853,9 @@ private async showProcess(): Promise<void> {
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<void> {
}
}
private updateProcessTableContent(processes: any[]): void {
private async updateProcessTableContent(processes: Process[] | any): Promise<void> {
const tbody = this.shadowRoot?.querySelector('#process-table tbody');
if (!tbody) return;
if (processes.length === 0) {
if (!processes || processes.length === 0) {
tbody.innerHTML = `
<tr>
<td colspan="3">No processes found</td>
@ -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) {
</div>
`;
// 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<void> {
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);

View File

@ -155,7 +155,7 @@ export async function init(): Promise<void> {
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<void> {
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);
}

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.
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<void> {
// 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);

View File

@ -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<string> = 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<ApiReturn> {
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<string | null> {
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<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) {
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<Member> = 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<string[]> {
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<string[]> {
// 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<string, Process>) {
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<string, any> | 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<string[]> {
public async getMyProcesses(): Promise<string[] | null> {
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<ApiReturn> {
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);
}
}

View File

@ -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<Record<string, boolean | null> | null> {
const res = {};
const res: Record<string, boolean | null> = {};
for (const server of servers) {
res[server] = null;
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() {
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<void> {
export async function prepareAndSendPairingTx(): Promise<void> {
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) {