Skip to content

Commit

Permalink
Merge branch 'DCKM-257-wallet-does-not-show-available-amount' of gith…
Browse files Browse the repository at this point in the history
…ub.com:docknetwork/react-native-sdk into DCKM-257-wallet-does-not-show-available-amount
  • Loading branch information
maycon-mello committed Oct 26, 2023
2 parents 37fdb03 + b0e2145 commit dab2b1b
Show file tree
Hide file tree
Showing 11 changed files with 195 additions and 237 deletions.
71 changes: 64 additions & 7 deletions packages/core/src/did-provider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,52 @@ export async function createDIDock({wallet, address, name}) {
await wallet.add(dockDIDResolution);
}

const createDIDKeyDocument = async (
async function editDID({wallet, id, name}){
if (typeof id === 'string' && id.length > 0) {
const docs = await wallet.query({
id,
});
if (docs.length === 1) {
const doc = docs[0];
await wallet.update({
...doc,
name,
});
}
} else {
throw new Error('Document ID is not set');
}
};

async function deleteDID({wallet, id}){
if (typeof id === 'string' && id.length > 0) {
return await wallet.remove(id);
} else {
throw Error('Document ID is not set');
}
}

async function exportDID({wallet, id, password }){
const existingDoc = await wallet.getDocumentById(id);
if (existingDoc) {
const allCorrelationDocuments = (
await wallet.resolveCorrelations(id)
).filter(doc => doc && doc?.id !== existingDoc.id);
const documentsToExport = [existingDoc, ...allCorrelationDocuments];

if (allCorrelationDocuments.length >= 1) {
return wallet.exportDocuments({
documents: documentsToExport,
password,
});
}
throw new Error('DID KeyPair not found');
}

throw new Error('DID Document not found');
}

export const createDIDKeyDocument = async (
keypairDoc: any,
didDocParams: any = {},
) => {
Expand All @@ -110,11 +155,11 @@ const createDIDKeyDocument = async (
};
};

export async function createDIKey({wallet, name}) {
export async function createDIDKey({wallet, name, derivePath=undefined, type=undefined}) {
assert(!!wallet, 'wallet is required');
assert(!!name, 'name is required');

const keyDoc = await didServiceRPC.generateKeyDoc({});
const keyDoc = await didServiceRPC.generateKeyDoc({derivePath, type});

const {didDocumentResolution} = await createDIDKeyDocument(keyDoc, {
name,
Expand Down Expand Up @@ -156,7 +201,7 @@ export async function ensureDID({wallet}) {
assert(!!wallet, 'wallet is required');
const dids = await getAll({wallet});
if (dids.length === 0) {
return createDIKey({wallet, name: 'Default DID'});
return createDIDKey({wallet, name: 'Default DID'});
}
}

Expand All @@ -166,7 +211,10 @@ export interface IDIDProvider {
password: string;
}): Promise<void>;
createDIDock(params: {address: string; name: string}): Promise<void>;
createDIDKey(params: {name: string}): Promise<any>;
createDIDKey(params: {name: string, derivePath?:string, type?: string}): Promise<any>;
editDID(params: {id: string; name: string}): Promise<void>;
deleteDID(params: {id: string;}): Promise<void>;
exportDID(params: {id: string; password: string}): Promise<void>;
getAll(): Promise<any>;
getDIDKeyPairs(): Promise<any>;
ensureDID(): Promise<any>;
Expand All @@ -180,8 +228,17 @@ export function createDIDProvider({wallet}): IDIDProvider {
async createDIDock({address, name}) {
return createDIDock({wallet, address, name});
},
async createDIDKey({name}) {
return createDIKey({wallet, name});
async createDIDKey({name, derivePath, type}) {
return createDIDKey({wallet, name, derivePath, type});
},
async editDID(params) {
return editDID({wallet, ...params});
},
async deleteDID(params) {
return deleteDID({wallet, ...params});
},
async exportDID(params) {
return exportDID({wallet, ...params});
},
async getAll() {
return getAll({wallet});
Expand Down
26 changes: 19 additions & 7 deletions packages/core/src/message-provider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,18 +47,30 @@ export function createMessageProvider({
}
},

async processDIDCommMessages() {
async processDIDCommMessages(limit = 1) {
try {
const messages = await wallet.getDocumentsByType(WalletDocumentTypes.DIDCommMessage);
const keyPairDocs = await getKeyPairDocs(didProvider);
for (const { encryptedMessage } of messages) {
let count = 0;
for (const message of messages) {
if (count >= limit) {
return;
}
try {
const decryptedMessage = await relayService.resolveDidcommMessage({ keyPairDocs, encryptedMessage });
wallet.eventManager.emit('didcomm-message-decrypted', decryptedMessage);
if (!message.encryptedMessage) {
await wallet.removeDocument(message.id);
throw new Error(`Message with payload ${JSON.stringify(message)} is invalid`);
}
const decryptedMessage = await relayService.resolveDidcommMessage({ keyPairDocs, message: message.encryptedMessage });
wallet.eventManager.emit('didcomm-message-decrypted', {
decryptedMessage,
messageId: message.id
});
// the wallet app will call markMessageAsRead after the message is processed
} catch(err) {
captureException(err);
}
count++;
}
} catch (error) {
captureException(error);
Expand Down Expand Up @@ -90,12 +102,12 @@ export function createMessageProvider({
skipMessageResolution: true,
});

for (const { _id, encryptedMessage } of encryptedMessages) {
for (const message of encryptedMessages) {
try {
await wallet.addDocument({
id: _id,
id: message._id,
type: WalletDocumentTypes.DIDCommMessage,
encryptedMessage,
encryptedMessage: message,
});
} catch(err) {
// this message will be lost if it fails to be stored in the wallet
Expand Down
4 changes: 2 additions & 2 deletions packages/data-store/src/configs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ export const DEFAULT_CONFIGS: DataStoreConfigs = {
id: 'mainnet',
credentialHostnames: ['creds.dock.io'],
configs: {
substrateUrl: 'wss://mainnet-node.dock.io',
substrateUrl: 'https://mainnet-node.dock.io/h',
addressPrefix: 22,
},
},
Expand All @@ -20,7 +20,7 @@ export const DEFAULT_CONFIGS: DataStoreConfigs = {
id: 'testnet',
credentialHostnames: ['creds-testnet.dock.io', 'creds-staging.dock.io'],
configs: {
substrateUrl: 'wss://knox-1.dock.io',
substrateUrl: 'https://knox-1.dock.io/h',
addressPrefix: 21,
},
},
Expand Down
7 changes: 5 additions & 2 deletions packages/data-store/src/entities/document/create-document.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,10 @@ export async function createDocument({
types: json.type,
});

const documentId = json.id || uuid();
if (!json.id) {
json.id = uuid()
}

let networkId;

if (json._networkId) {
Expand All @@ -48,7 +51,7 @@ export async function createDocument({

const entity: DocumentEntity = {
networkId,
id: documentId,
id: json.id,
type: json.type,
_typeRel,
correlation: json.correlation || [],
Expand Down
8 changes: 7 additions & 1 deletion packages/data-store/src/entities/document/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,13 @@ export function toWalletDocument(entity: DocumentEntity): WalletDocument {
return entity;
}

return JSON.parse(entity.data);
const result = JSON.parse(entity.data);

if (!result.id) {
result.id = entity.id;
}

return result;
}

/**
Expand Down
10 changes: 4 additions & 6 deletions packages/react-native/lib/accountsHooks.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import {getAccount, useWallet} from './index';
import {useMemo} from 'react';

export function useAccounts() {
const {documents, wallet} = useWallet({syncDocs: true});
const { documents, wallet } = useWallet();
const accounts = useMemo(() => {
if (Array.isArray(documents)) {
return documents
Expand All @@ -21,9 +21,7 @@ export function useAccounts() {
return [];
}, [documents, wallet?.accounts]);

return useMemo(() => {
return {
accounts,
};
}, [accounts]);
return {
accounts,
};
}
19 changes: 0 additions & 19 deletions packages/react-native/lib/credentialPresentHooks.js

This file was deleted.

55 changes: 24 additions & 31 deletions packages/react-native/lib/credentials/credentialHooks.js
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ async function getCredentialValidityStatus(credential) {
}

export function useCredentialUtils() {
const {documents, wallet} = useWallet({syncDocs: true});
const { documents, wallet } = useWallet();

const credentials = useMemo(() => {
if (Array.isArray(documents)) {
Expand All @@ -83,39 +83,31 @@ export function useCredentialUtils() {
return [];
}, [documents]);

const doesCredentialExist = useCallback((allCredentials, credentialToAdd) => {
const doesCredentialExist = (allCredentials, credentialToAdd) => {
return !!allCredentials.find(item => item.id === credentialToAdd.id);
}, []);
};

const saveCredential = useCallback(
async jsonData => {
validateCredential(jsonData);
if (doesCredentialExist(credentials, jsonData)) {
throw new Error('This credential already exists in the wallet');
}
await wallet.addDocument(jsonData);
},
[credentials, doesCredentialExist, wallet],
);
const deleteCredential = useCallback(
async credentialId => {
assert(
typeof credentialId === 'string' && credentialId.length > 0,
'Credential ID is not set',
);
return await wallet.remove(credentialId);
},
[wallet],
);
const saveCredential = async jsonData => {
validateCredential(jsonData);
if (doesCredentialExist(credentials, jsonData)) {
throw new Error('This credential already exists in the wallet');
}
await wallet.addDocument(jsonData);
};
const deleteCredential = async credentialId => {
assert(
typeof credentialId === 'string' && credentialId.length > 0,
'Credential ID is not set',
);
return await wallet.remove(credentialId);
};

return useMemo(() => {
return {
credentials,
doesCredentialExist,
saveCredential,
deleteCredential,
};
}, [credentials, doesCredentialExist, saveCredential, deleteCredential]);
return {
credentials,
doesCredentialExist,
saveCredential,
deleteCredential,
};
}
export function isInThePast(date) {
const today = new Date();
Expand Down Expand Up @@ -160,6 +152,7 @@ function buildStatusResponse(status, error = null) {
};
}

//TODO: Implement a caching mechanism that is attached to credentials context instead of global
export let cachedCredentialStatus = {};

export function useGetCredentialStatus({credential}) {
Expand Down
Loading

0 comments on commit dab2b1b

Please sign in to comment.