From 51ed21f7daff11878262bcd365dc95b720884f91 Mon Sep 17 00:00:00 2001 From: Sai Ranjit Tummalapalli Date: Tue, 31 Aug 2021 18:25:16 +0530 Subject: [PATCH 1/5] refactor: removed 2 wallet parameters from all the methods Signed-off-by: Sai Ranjit Tummalapalli --- .../main/java/com/arnimasdk/ArnimaSdk.java | 125 +++++++++--------- src/agent/index.ts | 69 +++++----- src/pool/index.ts | 29 +--- .../basicMessage/BasicMessageService.ts | 28 +--- src/protocols/connection/ConnectionService.ts | 65 +++------ src/protocols/credential/CredentialService.ts | 53 +++----- .../mediator/ConnectWithMediatorService.ts | 2 - .../presentation/PresentationService.ts | 113 ++++++---------- src/protocols/trustPing/TrustPingService.ts | 19 +-- src/transports/index.ts | 65 +++++---- src/utils/Helpers.ts | 48 +++---- src/wallet/WalletService.ts | 2 - src/wallet/WalletStorageService.ts | 29 ++-- 13 files changed, 250 insertions(+), 397 deletions(-) diff --git a/android/src/main/java/com/arnimasdk/ArnimaSdk.java b/android/src/main/java/com/arnimasdk/ArnimaSdk.java index cbdb7a2..ac5ada1 100644 --- a/android/src/main/java/com/arnimasdk/ArnimaSdk.java +++ b/android/src/main/java/com/arnimasdk/ArnimaSdk.java @@ -50,10 +50,10 @@ public class ArnimaSdk extends ReactContextBaseJavaModule { - private final ReactApplicationContext reactContext; public static final int PROTOCOL_VERSION = 2; + private final ReactApplicationContext reactContext; private final Map walletMap; - private Map credentialSearchMap; + private final Map credentialSearchMap; private int credentialSearchIterator = 0; public ArnimaSdk(ReactApplicationContext reactContext) { @@ -101,32 +101,15 @@ public void createPoolLedgerConfig(String poolName, String poolConfig, Promise p @ReactMethod public void createWallet(String walletConfig, String walletCredentials, Promise promise) { - new CreateWallet().execute(walletConfig, walletCredentials, promise); - } - - private class CreateWallet extends AsyncTask { - Promise promise = null; - - @Override - protected Object doInBackground(Object[] objects) { - try { - promise = (Promise) objects[2]; - Wallet.createWallet(objects[0].toString(), objects[1].toString()).get(); - promise.resolve(null); - } catch (Exception e) { - IndySdkRejectResponse rejectResponse = new IndySdkRejectResponse(e); - promise.reject(rejectResponse.getCode(), rejectResponse.toJson(), e); - } - return promise; - } - - @Override - protected void onPreExecute() { - super.onPreExecute(); + try { + Wallet.createWallet(walletConfig, walletCredentials).get(); + promise.resolve(null); + } catch (Exception e) { + IndySdkRejectResponse rejectResponse = new IndySdkRejectResponse(e); + promise.reject(rejectResponse.getCode(), rejectResponse.toJson(), e); } } - @ReactMethod public void openInitWallet(String walletConfig, String walletCredentials, Promise promise) { Wallet wallet = null; @@ -162,6 +145,19 @@ public Wallet openWallet(String walletConfig, String walletCredentials, Promise } } + @ReactMethod + public Wallet getWalletHandle(Promise promise) { + Wallet wallet = null; + try { + wallet = walletMap.get(1); + } catch (Exception e) { + IndySdkRejectResponse rejectResponse = new IndySdkRejectResponse(e); + promise.reject(rejectResponse.getCode(), rejectResponse.toJson(), e); + } finally { + return wallet; + } + } + public Pool openPoolLedger(String poolName, String poolConfig, Promise promise) { Pool pool = null; try { @@ -173,6 +169,7 @@ public Pool openPoolLedger(String poolName, String poolConfig, Promise promise) return null; } } + public void closePoolLedger(Pool pool) { try { pool.closePoolLedger().get(); @@ -187,10 +184,10 @@ public void closePoolLedger(Pool pool) { @ReactMethod public void createAndStoreMyDid(String walletConfig, String walletCredentials, String didJson, - Boolean createMasterSecret, Promise promise) { + Boolean createMasterSecret, Promise promise) { Wallet wallet = null; try { - wallet = openWallet(walletConfig, walletCredentials, promise); + wallet = getWalletHandle(promise); if (wallet != null) { DidResults.CreateAndStoreMyDidResult createMyDidResult = Did .createAndStoreMyDid(wallet, didJson).get(); @@ -200,7 +197,7 @@ public void createAndStoreMyDid(String walletConfig, String walletCredentials, S JSONObject config = new JSONObject(walletConfig); response.pushString(myDid); response.pushString(myVerkey); - if ((Boolean) createMasterSecret) { + if (createMasterSecret) { String outputMasterSecretId = Anoncreds .proverCreateMasterSecret(wallet, config.get("id").toString()).get(); response.pushString(outputMasterSecretId); @@ -214,11 +211,11 @@ public void createAndStoreMyDid(String walletConfig, String walletCredentials, S } @ReactMethod - public void addWalletRecord(String walletConfig, String walletCredentials, String recordType, String id, String value, String tags, + public void addWalletRecord(String recordType, String id, String value, String tags, Promise promise) { Wallet wallet = null; try { - wallet = openWallet(walletConfig, walletCredentials, promise); + wallet = getWalletHandle(promise); if (wallet != null) { WalletRecord.add(wallet, recordType, id, value, tags).get(); promise.resolve("true"); @@ -230,17 +227,17 @@ public void addWalletRecord(String walletConfig, String walletCredentials, Strin } @ReactMethod - public void updateWalletRecord(String walletConfig, String walletCredentials, String recordType, String id, String value, String tags, + public void updateWalletRecord(String recordType, String id, String value, String tags, Promise promise) { Wallet wallet = null; try { - wallet = openWallet(walletConfig, walletCredentials, promise); + wallet = getWalletHandle(promise); if (wallet != null) { WalletRecord.updateValue(wallet, recordType, id, value) .get(); if (!tags.equalsIgnoreCase("{}")) { - WalletRecord.updateTags(wallet, recordType, id,tags); + WalletRecord.updateTags(wallet, recordType, id, tags); } promise.resolve("true"); } @@ -251,11 +248,11 @@ public void updateWalletRecord(String walletConfig, String walletCredentials, St } @ReactMethod - public void deleteWalletRecord(String walletConfig, String walletCredentials, String recordType, String id, + public void deleteWalletRecord(String recordType, String id, Promise promise) { Wallet wallet = null; try { - wallet = openWallet(walletConfig, walletCredentials, promise); + wallet = getWalletHandle(promise); if (wallet != null) { WalletRecord.delete(wallet, recordType, id) .get(); @@ -268,11 +265,11 @@ public void deleteWalletRecord(String walletConfig, String walletCredentials, St } @ReactMethod - public void getWalletRecordFromQuery(String walletConfig, String walletCredentials, String recordType, String query, - Promise promise) { + public void getWalletHandleRecordFromQuery(String recordType, String query, + Promise promise) { Wallet wallet = null; try { - wallet = openWallet(walletConfig, walletCredentials, promise); + wallet = getWalletHandle(promise); if (wallet != null) { WalletSearch search = WalletSearch.open(wallet, recordType, query, "{\"retrieveTags\":true,\"retrieveType \":true, \"retrieveType\": true }") .get(); @@ -287,15 +284,15 @@ public void getWalletRecordFromQuery(String walletConfig, String walletCredentia } @ReactMethod - public void packMessage(String walletConfig, String walletCredentials, ReadableArray message, + public void packMessage(ReadableArray message, ReadableArray receiverKeyArray, String senderVk, Promise promise) { Wallet wallet = null; try { - wallet = openWallet(walletConfig, walletCredentials, promise); + wallet = getWalletHandle(promise); if (wallet != null) { - byte[] buffer = readableArrayToBuffer((ReadableArray) message); + byte[] buffer = readableArrayToBuffer(message); - ReadableArray receiverKeys = (ReadableArray) receiverKeyArray; + ReadableArray receiverKeys = receiverKeyArray; String[] keys = new String[receiverKeys.size()]; for (int i = 0; i < receiverKeys.size(); i++) { keys[i] = receiverKeys.getString(i); @@ -318,10 +315,10 @@ public void packMessage(String walletConfig, String walletCredentials, ReadableA } @ReactMethod - public void unpackMessage(String walletConfig, String walletCredentials, ReadableArray jwe, Promise promise) { + public void unpackMessage(ReadableArray jwe, Promise promise) { Wallet wallet = null; try { - wallet = openWallet(walletConfig, walletCredentials, promise); + wallet = getWalletHandle(promise); if (wallet != null) { byte[] buffer = readableArrayToBuffer(jwe); byte[] res = Crypto.unpackMessage(wallet, buffer).get(); @@ -339,11 +336,11 @@ public void unpackMessage(String walletConfig, String walletCredentials, Readabl } @ReactMethod - public void cryptoSign(String walletConfig, String walletCredentials, String signerVk, ReadableArray messageRaw, + public void cryptoSign(String signerVk, ReadableArray messageRaw, Promise promise) { Wallet wallet = null; try { - wallet = openWallet(walletConfig, walletCredentials, promise); + wallet = getWalletHandle(promise); if (wallet != null) { byte[] messageBuf = readableArrayToBuffer(messageRaw); byte[] signature = Crypto.cryptoSign(wallet, signerVk, messageBuf).get(); @@ -360,11 +357,11 @@ public void cryptoSign(String walletConfig, String walletCredentials, String sig } @ReactMethod - public void cryptoVerify(String walletConfig, String walletCredentials, String signerVk, ReadableArray messageRaw, + public void cryptoVerify(String signerVk, ReadableArray messageRaw, ReadableArray signatureRaw, Promise promise) { Wallet wallet = null; try { - wallet = openWallet(walletConfig, walletCredentials, promise); + wallet = getWalletHandle(promise); if (wallet != null) { byte[] messageBuf = readableArrayToBuffer(messageRaw); byte[] sigBuf = readableArrayToBuffer(signatureRaw); @@ -378,11 +375,11 @@ public void cryptoVerify(String walletConfig, String walletCredentials, String s } @ReactMethod - public void proverCreateCredentialReq(String walletConfig, String walletCredentials, String proverDid, + public void proverCreateCredentialReq(String proverDid, String credentialOfferJson, String credentialDefJson, String masterSecret, Promise promise) { Wallet wallet = null; try { - wallet = openWallet(walletConfig, walletCredentials, promise); + wallet = getWalletHandle(promise); if (wallet != null) { AnoncredsResults.ProverCreateCredentialRequestResult credentialRequestResult = Anoncreds .proverCreateCredentialReq(wallet, proverDid, credentialOfferJson, @@ -400,14 +397,14 @@ public void proverCreateCredentialReq(String walletConfig, String walletCredenti } @ReactMethod - public void proverStoreCredential(String walletConfig, String walletCredentials, String credId, + public void proverStoreCredential(String credId, String credReqMetadataJson, String credJson, String credDefJson, String revRegDefJson, Promise promise) { Wallet wallet = null; try { - wallet = openWallet(walletConfig, walletCredentials, promise); + wallet = getWalletHandle(promise); if (wallet != null) { - String newCredId = Anoncreds.proverStoreCredential(wallet, credId, credReqMetadataJson, - credJson, credDefJson, revRegDefJson).get(); + String newCredId = Anoncreds.proverStoreCredential(wallet, credId, credReqMetadataJson, + credJson, credDefJson, revRegDefJson).get(); promise.resolve(newCredId); } } catch (Exception e) { @@ -467,10 +464,10 @@ public void verifierVerifyProof(String proofRequest, String proof, } @ReactMethod - public void proverGetCredentials(String walletConfig, String walletCredentials, String filter, Promise promise) { + public void proverGetCredentials(String filter, Promise promise) { Wallet wallet = null; try { - wallet = openWallet(walletConfig, walletCredentials, promise); + wallet = getWalletHandle(promise); if (wallet != null) { String credentials = Anoncreds.proverGetCredentials(wallet, filter).get(); promise.resolve(credentials); @@ -482,10 +479,10 @@ public void proverGetCredentials(String walletConfig, String walletCredentials, } @ReactMethod - public void proverGetCredential(String walletConfig, String walletCredentials, String credId, Promise promise) { + public void proverGetCredential(String credId, Promise promise) { Wallet wallet = null; try { - wallet = openWallet(walletConfig, walletCredentials, promise); + wallet = getWalletHandle(promise); if (wallet != null) { String credential = Anoncreds.proverGetCredential(wallet, credId).get(); promise.resolve(credential); @@ -503,7 +500,7 @@ public void getCredDef(String submitterDid, String id, String poolName, String p String credDefRequest = Ledger.buildGetCredDefRequest(submitterDid, id).get(); pool = openPoolLedger(poolName, poolConfig, promise); if (pool != null) { - String credDefResponse = Ledger.submitRequest(pool, credDefRequest).get(); + String credDefResponse = Ledger.submitRequest(pool, credDefRequest).get(); LedgerResults.ParseResponseResult responseResult = Ledger.parseGetCredDefResponse(credDefResponse).get(); promise.resolve(responseResult.getObjectJson()); @@ -577,11 +574,11 @@ public void getSchemasJson(String poolName, String poolConfig, String submitterD } @ReactMethod - public void proverCreateProof(String walletConfig, String walletCredentials, String proofRequest, + public void proverCreateProof(String proofRequest, String requestedCredentials, String masterSecret, String schemas, String credentialDefs, String revocObject, Promise promise) { Wallet wallet = null; try { - wallet = openWallet(walletConfig, walletCredentials, promise); + wallet = getWalletHandle(promise); if (wallet != null) { String cred_proof = Anoncreds.proverCreateProof(wallet, proofRequest, String.valueOf(requestedCredentials), masterSecret, String.valueOf(schemas), @@ -670,7 +667,7 @@ private JSONObject getSchemaJson(Pool pool, String submitterDid, String schemaId } @ReactMethod - public void createRevocationStateObject(String poolName, String poolConfig, String submitterDid, String revRegId, String credRevId,Promise promise) + public void createRevocationStateObject(String poolName, String poolConfig, String submitterDid, String revRegId, String credRevId, Promise promise) throws Exception { Pool pool = null; JSONObject revocState = new JSONObject(); @@ -745,10 +742,10 @@ public void createRevocationStateObject(String poolName, String poolConfig, Stri } @ReactMethod - public void exportWallet(String walletConfig, String walletCredentials, String config, Promise promise) { + public void exportWallet(String config, Promise promise) { Wallet wallet = null; try { - wallet = openWallet(walletConfig, walletCredentials, promise); + wallet = getWalletHandle(promise); if (wallet != null) { Wallet.exportWallet(wallet, config).get(); promise.resolve("true"); diff --git a/src/agent/index.ts b/src/agent/index.ts index ec399cf..dfb644c 100644 --- a/src/agent/index.ts +++ b/src/agent/index.ts @@ -63,7 +63,6 @@ class Agent { console.log('Agent - Get wallet error = ', error); throw error; } - } openWallet = async () => { @@ -77,7 +76,7 @@ class Agent { getAllPool = async () => { try { - return await PoolService.getAllPool(JSON.parse(this.wallet.walletConfig), JSON.parse(this.wallet.walletCredentials)); + return await PoolService.getAllPool(); } catch (error) { console.log("Agent - Get all pool error = ", error); throw error; @@ -86,7 +85,7 @@ class Agent { createPool = async (poolName: string, poolConfig: string, defaultPool?: boolean) => { try { - return await PoolService.createPool(JSON.parse(this.wallet.walletConfig), JSON.parse(this.wallet.walletCredentials), poolName, poolConfig, defaultPool); + return await PoolService.createPool(poolName, poolConfig, defaultPool); } catch (error) { console.log("Agent - Create pool error = ", error); throw error; @@ -95,7 +94,7 @@ class Agent { selectDefaultPool = async (poolName: string) => { try { - return await PoolService.selectDefaultPool(JSON.parse(this.wallet.walletConfig), JSON.parse(this.wallet.walletCredentials), poolName) + return await PoolService.selectDefaultPool(poolName) } catch (error) { console.log("Agent - Select default pool error = ", error); throw error; @@ -104,7 +103,7 @@ class Agent { createInvitation = async (didJson: Object, logo: string) => { try { - return await ConnectionService.createInvitation(JSON.parse(this.wallet.walletConfig), JSON.parse(this.wallet.walletCredentials), didJson, logo); + return await ConnectionService.createInvitation(didJson, logo); } catch (error) { console.log("Agent - Create invitation error = ", error); throw error; @@ -114,7 +113,7 @@ class Agent { acceptInvitation = async (didJson: Object, message: any, logo: string,) => { try { const invitation = decodeInvitationFromUrl(message); - return await ConnectionService.acceptInvitation(JSON.parse(this.wallet.walletConfig), JSON.parse(this.wallet.walletCredentials), didJson, invitation, logo); + return await ConnectionService.acceptInvitation(didJson, invitation, logo); } catch (error) { console.log("Agent - Accept invitation error = ", error); @@ -124,7 +123,7 @@ class Agent { getConnectionRecord = async (query: Object) => { try { - return await WalletStorageService.getWalletRecordsFromQuery(JSON.parse(this.wallet.walletConfig), JSON.parse(this.wallet.walletCredentials), RecordType.Connection, JSON.stringify(query)); + return await WalletStorageService.getWalletRecordsFromQuery(RecordType.Connection, JSON.stringify(query)); } catch (error) { console.log("Agent - Get all connections error = ", error); @@ -134,7 +133,7 @@ class Agent { getPresentationRecord = async (query: Object) => { try { - return await WalletStorageService.getWalletRecordsFromQuery(JSON.parse(this.wallet.walletConfig), JSON.parse(this.wallet.walletCredentials), RecordType.Presentation, JSON.stringify(query)); + return await WalletStorageService.getWalletRecordsFromQuery(RecordType.Presentation, JSON.stringify(query)); } catch (error) { console.log("Agent - Get all connections error = ", error); @@ -144,7 +143,7 @@ class Agent { basicMessageHistory = async (query: Object) => { try { - return await WalletStorageService.getWalletRecordsFromQuery(JSON.parse(this.wallet.walletConfig), JSON.parse(this.wallet.walletCredentials), RecordType.BasicMessage, JSON.stringify(query)); + return await WalletStorageService.getWalletRecordsFromQuery(RecordType.BasicMessage, JSON.stringify(query)); } catch (error) { console.log("Agent - Get all connections error = ", error); @@ -154,9 +153,9 @@ class Agent { deleteConnection = async (connectionId: string) => { try { - const records = await WalletStorageService.getWalletRecordsFromQuery(JSON.parse(this.wallet.walletConfig), JSON.parse(this.wallet.walletCredentials), RecordType.Credential, JSON.stringify({ connectionId: connectionId })); + const records = await WalletStorageService.getWalletRecordsFromQuery(RecordType.Credential, JSON.stringify({ connectionId: connectionId })); if (records === null || records.length === 0) { - await WalletStorageService.deleteWalletRecord(JSON.parse(this.wallet.walletConfig), JSON.parse(this.wallet.walletCredentials), RecordType.Connection, connectionId); + await WalletStorageService.deleteWalletRecord(RecordType.Connection, connectionId); return true; } else { return false; @@ -170,7 +169,7 @@ class Agent { getAllActionMessages = async () => { try { const query = { autoProcessed: false } - return await WalletStorageService.getWalletRecordsFromQuery(JSON.parse(this.wallet.walletConfig), JSON.parse(this.wallet.walletCredentials), RecordType.SSIMessage, JSON.stringify(query)); + return await WalletStorageService.getWalletRecordsFromQuery(RecordType.SSIMessage, JSON.stringify(query)); } catch (error) { console.log("Agent - Get all action messages error= ", error); @@ -180,11 +179,11 @@ class Agent { getIssueCredentialByConnectionId = async (connectionId: string) => { try { - let query = {} + let query = { } if (connectionId !== null) { query = { connectionId: connectionId } } - return await WalletStorageService.getWalletRecordsFromQuery(JSON.parse(this.wallet.walletConfig), JSON.parse(this.wallet.walletCredentials), RecordType.Credential, JSON.stringify(query)); + return await WalletStorageService.getWalletRecordsFromQuery(RecordType.Credential, JSON.stringify(query)); } catch (error) { console.log('Agent - Get issue credential by connection id error = ', error); throw error; @@ -193,7 +192,7 @@ class Agent { getPresentationByConnectionId = async (connectionId: string) => { try { - return await WalletStorageService.getWalletRecordsFromQuery(JSON.parse(this.wallet.walletConfig), JSON.parse(this.wallet.walletCredentials), RecordType.Presentation, JSON.stringify({ connectionId: connectionId })); + return await WalletStorageService.getWalletRecordsFromQuery(RecordType.Presentation, JSON.stringify({ connectionId: connectionId })); } catch (error) { console.log('Agent - Get presentation by connection id error = ', error); throw error; @@ -202,7 +201,7 @@ class Agent { getAllActionMessagesById = async (thId: string) => { try { - return await WalletStorageService.getWalletRecordFromQuery(JSON.parse(this.wallet.walletConfig), JSON.parse(this.wallet.walletCredentials), RecordType.SSIMessage, JSON.stringify({ thId: thId })); + return await WalletStorageService.getWalletRecordFromQuery(RecordType.SSIMessage, JSON.stringify({ thId: thId })); } catch (error) { console.log('Agent - Get all action messages by id error = ', error); throw error; @@ -211,7 +210,7 @@ class Agent { getIssueCredentialByCredentialsId = async (referent: string) => { try { - return await WalletStorageService.getWalletRecordFromQuery(JSON.parse(this.wallet.walletConfig), JSON.parse(this.wallet.walletCredentials), RecordType.Credential, JSON.stringify({ credentialsId: referent })); + return await WalletStorageService.getWalletRecordFromQuery(RecordType.Credential, JSON.stringify({ credentialsId: referent })); } catch (error) { console.log('Agent - Get all issue credential by credentials id error = ', error); throw error; @@ -221,7 +220,6 @@ class Agent { sendCredentialProposal = async (connectionId: object, credentialProposal: string, schemaId: string, credDefId: string, issuerDid: string, comment: string) => { try { return await CredentialService.createProposal( - JSON.parse(this.wallet.walletConfig), JSON.parse(this.wallet.walletCredentials), connectionId, credentialProposal, schemaId, @@ -240,8 +238,8 @@ class Agent { let { message }: any = inboundMessage; message = JSON.stringify(message); inboundMessage['message'] = message; - const response: Boolean = await CredentialService.createRequest(JSON.parse(this.wallet.walletConfig), JSON.parse(this.wallet.walletCredentials), inboundMessage); - if (response) await WalletStorageService.deleteWalletRecord(JSON.parse(this.wallet.walletConfig), JSON.parse(this.wallet.walletCredentials), RecordType.SSIMessage, messageId); + const response: Boolean = await CredentialService.createRequest(inboundMessage); + if (response) await WalletStorageService.deleteWalletRecord(RecordType.SSIMessage, messageId); return response; } catch (error) { console.log('Agent - Accept credential offer error = ', error); @@ -254,8 +252,8 @@ class Agent { let { message }: any = inboundMessage; message = JSON.stringify(message); inboundMessage['message'] = message; - const response: Boolean = await CredentialService.processCredential(JSON.parse(this.wallet.walletConfig), JSON.parse(this.wallet.walletCredentials), inboundMessage); - if (response) await WalletStorageService.deleteWalletRecord(JSON.parse(this.wallet.walletConfig), JSON.parse(this.wallet.walletCredentials), RecordType.SSIMessage, messageId); + const response: Boolean = await CredentialService.processCredential(inboundMessage); + if (response) await WalletStorageService.deleteWalletRecord(RecordType.SSIMessage, messageId); return response; } catch (error) { console.log('Agent - Store credential error = ', error); @@ -279,7 +277,7 @@ class Agent { sendBasicMessage = async (message: string, connectionId: string) => { try { - return await BasicMessageService.send(JSON.parse(this.wallet.walletConfig), JSON.parse(this.wallet.walletCredentials), message, connectionId); + return await BasicMessageService.send(message, connectionId); } catch (error) { console.log('Agent - Send message error = ', error); throw error; @@ -293,7 +291,6 @@ class Agent { try { presentationProposal["@type"] = MessageType.presentationPreview; return await PresentationService.createProposal( - JSON.parse(this.wallet.walletConfig), JSON.parse(this.wallet.walletCredentials), connectionId, presentationProposal, comment @@ -306,8 +303,8 @@ class Agent { sendProof = async (messageId: string, inboundMessage: InboundMessage, revealAttributes: boolean, presentationObj: object) => { try { - const response: Boolean = await PresentationService.createPresentation(JSON.parse(this.wallet.walletConfig), JSON.parse(this.wallet.walletCredentials), inboundMessage, revealAttributes, presentationObj); - if (response) { await WalletStorageService.deleteWalletRecord(JSON.parse(this.wallet.walletConfig), JSON.parse(this.wallet.walletCredentials), RecordType.SSIMessage, messageId) } + const response: Boolean = await PresentationService.createPresentation(inboundMessage, revealAttributes, presentationObj); + if (response) { await WalletStorageService.deleteWalletRecord(RecordType.SSIMessage, messageId) } return response; } catch (error) { console.log('Agent - Send proof error = ', error); @@ -320,8 +317,8 @@ class Agent { let { message }: any = inboundMessage; message = JSON.stringify(message); inboundMessage['message'] = message; - const response = await PresentationService.verifyProof(JSON.parse(this.wallet.walletConfig), JSON.parse(this.wallet.walletCredentials), messageId, inboundMessage); - await WalletStorageService.deleteWalletRecord(JSON.parse(this.wallet.walletConfig), JSON.parse(this.wallet.walletCredentials), RecordType.SSIMessage, messageId) + const response = await PresentationService.verifyProof(messageId, inboundMessage); + await WalletStorageService.deleteWalletRecord(RecordType.SSIMessage, messageId) return response; } catch (error) { console.log('Agent - Verify proof error = ', error); @@ -331,7 +328,7 @@ class Agent { sendPresentProofRequest = async (connectionId: string, proofRequest: object, comment: string) => { try { - return await PresentationService.createRequest(JSON.parse(this.wallet.walletConfig), JSON.parse(this.wallet.walletCredentials), connectionId, proofRequest, comment); + return await PresentationService.createRequest(connectionId, proofRequest, comment); } catch (error) { console.log('Agent - Send present proof request error = ', error); throw error; @@ -340,7 +337,7 @@ class Agent { getAllActionMessagesByMessageId = async (messageId: string) => { try { - return await WalletStorageService.getWalletRecordFromQuery(JSON.parse(this.wallet.walletConfig), JSON.parse(this.wallet.walletCredentials), RecordType.SSIMessage, JSON.stringify({ messageId: messageId })); + return await WalletStorageService.getWalletRecordFromQuery(RecordType.SSIMessage, JSON.stringify({ messageId: messageId })); } catch (error) { console.log('Agent - Get all action messages by message id error = ', error); throw error; @@ -349,7 +346,7 @@ class Agent { getConnection = async (connectionId: string) => { try { - return await WalletStorageService.getWalletRecordFromQuery(JSON.parse(this.wallet.walletConfig), JSON.parse(this.wallet.walletCredentials), RecordType.Connection, JSON.stringify({ connectionId: connectionId })); + return await WalletStorageService.getWalletRecordFromQuery(RecordType.Connection, JSON.stringify({ connectionId: connectionId })); } catch (error) { console.log('Agent - Get Connection from connection id error = ', error); throw error; @@ -368,13 +365,9 @@ class Agent { } const data = []; - await PoolService.deletePoolRecords(JSON.parse(this.wallet.walletConfig), JSON.parse(this.wallet.walletCredentials)); + await PoolService.deletePoolRecords(); - const response = await ArnimaSdk.exportWallet( - this.wallet.walletConfig, - this.wallet.walletCredentials, - JSON.stringify(config), - ); + const response = await ArnimaSdk.exportWallet(JSON.stringify(config)); return response; } catch (error) { @@ -397,7 +390,7 @@ class Agent { JSON.stringify([]) ); - const mediatorRecord = await WalletStorageService.getWalletRecordFromQuery(config, credentials, RecordType.MediatorAgent, '{}'); + const mediatorRecord = await WalletStorageService.getWalletRecordFromQuery(RecordType.MediatorAgent, '{}'); DatabaseServices.storeWallet({ walletConfig: JSON.stringify(config), diff --git a/src/pool/index.ts b/src/pool/index.ts index c7ab208..c1c74a2 100644 --- a/src/pool/index.ts +++ b/src/pool/index.ts @@ -16,15 +16,13 @@ class PoolService { /** * Create pool genesis file and set default pool * - * @param {WalletConfig} configJson - * @param {WalletCredentials} credentialsJson * @param {string} poolName * @param {string} poolConfig * @param {boolean} [defaultPool=false] * @return {*} {Promise} * @memberof PoolService */ - async createPool(configJson: WalletConfig, credentialsJson: WalletCredentials, poolName: string, poolConfig: string, defaultPool: boolean = false): Promise { + async createPool(poolName: string, poolConfig: string, defaultPool: boolean = false): Promise { try { const response: null = await ArnimaSdk.createPoolLedgerConfig( poolName, @@ -41,8 +39,6 @@ class PoolService { isSelected: JSON.stringify(defaultPool) } await WalletStorageService.addWalletRecord( - configJson, - credentialsJson, RecordType.Pool, poolName, JSON.stringify(poolRecord), @@ -59,14 +55,12 @@ class PoolService { /** * Return all the create pool records * - * @param {WalletConfig} configJson - * @param {WalletCredentials} credentialsJson * @return {*} {Promise} * @memberof PoolService */ - async getAllPool(configJson: WalletConfig, credentialsJson: WalletCredentials): Promise { + async getAllPool(): Promise { try { - return await WalletStorageService.getWalletRecordsFromQuery(configJson, credentialsJson, RecordType.Pool, '{}'); + return await WalletStorageService.getWalletRecordsFromQuery(RecordType.Pool, '{}'); } catch (error) { console.log("Pool - Get all pools error = ", error); throw error; @@ -76,15 +70,13 @@ class PoolService { /** * Update default select pool * - * @param {WalletConfig} configJson - * @param {WalletCredentials} credentialsJson * @param {string} poolName * @return {*} {Promise} * @memberof PoolService */ - async selectDefaultPool(configJson: WalletConfig, credentialsJson: WalletCredentials, poolName: string): Promise { + async selectDefaultPool(poolName: string): Promise { try { - const poolRecords: Array = await WalletStorageService.getWalletRecordsFromQuery(configJson, credentialsJson, RecordType.Pool, '{}'); + const poolRecords: Array = await WalletStorageService.getWalletRecordsFromQuery(RecordType.Pool, '{}'); for await (let record of poolRecords) { const pool: Pool = JSON.parse(record.value); const poolRecord: Pool = { @@ -100,8 +92,6 @@ class PoolService { } await WalletStorageService.updateWalletRecord( - configJson, - credentialsJson, RecordType.Pool, pool.poolName, JSON.stringify(poolRecord), @@ -118,20 +108,15 @@ class PoolService { /** * Delete all pool records * - * @param {WalletConfig} configJson - * @param {WalletCredentials} credentialsJson * @return {*} {Promise} * @memberof PoolService */ - async deletePoolRecords(configJson: WalletConfig, credentialsJson: WalletCredentials): Promise { + async deletePoolRecords(): Promise { try { - const poolRecords: Array = await WalletStorageService.getWalletRecordsFromQuery(configJson, credentialsJson, RecordType.Pool, '{}'); + const poolRecords: Array = await WalletStorageService.getWalletRecordsFromQuery(RecordType.Pool, '{}'); for await (let record of poolRecords) { const pool: Pool = JSON.parse(record.value); - await WalletStorageService.deleteWalletRecord( - configJson, - credentialsJson, RecordType.Pool, pool.poolName, ); diff --git a/src/protocols/basicMessage/BasicMessageService.ts b/src/protocols/basicMessage/BasicMessageService.ts index 623518f..2d4dde0 100644 --- a/src/protocols/basicMessage/BasicMessageService.ts +++ b/src/protocols/basicMessage/BasicMessageService.ts @@ -7,7 +7,6 @@ import { Connection } from '../connection/ConnectionInterface'; import { createBasicMessage } from './BasicMessageMessages'; import { InboundMessage } from '../../utils/Types'; import { RecordType, sendOutboundMessage } from '../../utils/Helpers'; -import { WalletConfig, WalletCredentials } from '../../wallet/WalletInterface'; import WalletStorageService from '../../wallet/WalletStorageService'; class BasicMessageService { @@ -15,20 +14,17 @@ class BasicMessageService { /** * @description Send basic message to exiting connection * - * @param {WalletConfig} configJson - * @param {WalletCredentials} credentialsJson * @param {string} message * @param {string} connectionId * @return {*} {Promise} * @memberof BasicMessageService */ - async send(configJson: WalletConfig, credentialsJson: WalletCredentials, message: string, connectionId: string): Promise { + async send(message: string, connectionId: string): Promise { try { const query = { connectionId: connectionId } - - const connection: Connection = await WalletStorageService.getWalletRecordFromQuery(configJson, credentialsJson, RecordType.Connection, JSON.stringify(query)); + const connection: Connection = await WalletStorageService.getWalletRecordFromQuery(RecordType.Connection, JSON.stringify(query)); const basicMessage = createBasicMessage(message); const chatBody = { type: 'sent', @@ -40,12 +36,10 @@ class BasicMessageService { connectionId: connectionId, lastUpdatedAt: new Date().toISOString() } - const chatThread: Array = await WalletStorageService.getWalletRecordFromQuery(configJson, credentialsJson, RecordType.BasicMessage, JSON.stringify(query)); + const chatThread: Array = await WalletStorageService.getWalletRecordFromQuery(RecordType.BasicMessage, JSON.stringify(query)); if (chatThread === undefined || chatThread === null || chatThread.length == 0) { await WalletStorageService.addWalletRecord( - configJson, - credentialsJson, RecordType.BasicMessage, connectionId, JSON.stringify([chatBody]), @@ -55,8 +49,6 @@ class BasicMessageService { else { chatThread.push(chatBody); await WalletStorageService.updateWalletRecord( - configJson, - credentialsJson, RecordType.BasicMessage, connectionId, JSON.stringify(chatThread), @@ -64,7 +56,7 @@ class BasicMessageService { ); } setTimeout(async ()=> { - await sendOutboundMessage(configJson, credentialsJson, connection, basicMessage) + await sendOutboundMessage(connection, basicMessage) },50) return true; } catch (error) { @@ -77,14 +69,12 @@ class BasicMessageService { /** * @description Process basic message and update the record * - * @param {WalletConfig} configJson - * @param {WalletCredentials} credentialsJson * @param {InboundMessage} inboundMessage * @param {string} connectionId * @return {*} {Promise} * @memberof BasicMessageService */ - async save(configJson: WalletConfig, credentialsJson: WalletCredentials, inboundMessage: InboundMessage, connectionId: string): Promise { + async save(inboundMessage: InboundMessage, connectionId: string): Promise { try { const { message } = inboundMessage; const chatBody = { @@ -95,8 +85,8 @@ class BasicMessageService { const query = { connectionId: connectionId } - const chatThread: Array = await WalletStorageService.getWalletRecordFromQuery(configJson, credentialsJson, RecordType.BasicMessage, JSON.stringify(query)); - const connection: Connection = await WalletStorageService.getWalletRecordFromQuery(configJson, credentialsJson, RecordType.Connection, JSON.stringify(query)); + const chatThread: Array = await WalletStorageService.getWalletRecordFromQuery(RecordType.BasicMessage, JSON.stringify(query)); + const connection: Connection = await WalletStorageService.getWalletRecordFromQuery(RecordType.Connection, JSON.stringify(query)); const basicMessageTags: Object = { connectionId: connectionId, lastUpdatedAt: new Date().toISOString() @@ -104,8 +94,6 @@ class BasicMessageService { if (chatThread.length == 0) { await WalletStorageService.addWalletRecord( - configJson, - credentialsJson, RecordType.BasicMessage, connectionId, JSON.stringify([chatBody]), @@ -115,8 +103,6 @@ class BasicMessageService { else { chatThread.push(chatBody); await WalletStorageService.updateWalletRecord( - configJson, - credentialsJson, RecordType.BasicMessage, connectionId, JSON.stringify(chatThread), diff --git a/src/protocols/connection/ConnectionService.ts b/src/protocols/connection/ConnectionService.ts index 051d676..516f8f0 100644 --- a/src/protocols/connection/ConnectionService.ts +++ b/src/protocols/connection/ConnectionService.ts @@ -6,7 +6,6 @@ import { Authentication, DidDoc, PublicKey, PublicKeyType, Service } from '../../utils/DidDoc'; import { InboundMessage, Message } from '../../utils/Types'; import { RecordType, encodeInvitationToUrl, getServiceEndpoint, sendOutboundMessage, sign, verify } from '../../utils/Helpers'; -import { WalletConfig, WalletCredentials } from '../../wallet/WalletInterface'; import { createConnectionRequestMessage, createConnectionResponseMessage, @@ -54,25 +53,18 @@ class ConnectionService { /** * @description Create a new connection record containing a connection invitation message * - * @param {WalletConfig} configJson - * @param {WalletCredentials} credentialsJson * @param {Object} didJson * @param {string} logo * @return {*} {Promise} * @memberof ConnectionService */ - async createInvitation(configJson: WalletConfig, - credentialsJson: WalletCredentials, - didJson: Object, - logo: string): Promise { - const connection: Connection = await this.createConnection(configJson, credentialsJson, didJson); + async createInvitation(didJson: Object, logo: string): Promise { + const connection: Connection = await this.createConnection(didJson); const connectionTags: Object = { connectionId: connection.verkey, } await WalletStorageService.addWalletRecord( - configJson, - credentialsJson, RecordType.Connection, connection.verkey, JSON.stringify(connection), @@ -90,35 +82,30 @@ class ConnectionService { /** * @description Process a received invitation message. * - * @param {WalletConfig} configJson - * @param {WalletCredentials} credentialsJson * @param {Object} didJson * @param {Message} invitation * @param {string} logo * @return {*} {Promise} * @memberof ConnectionService */ - async acceptInvitation(configJson: WalletConfig, - credentialsJson: WalletCredentials, - didJson: Object, - invitation: Message, - logo: string): Promise { + async acceptInvitation(didJson: Object, invitation: Message, logo: string): Promise { try { - const connection: Connection = await this.createConnection(configJson, credentialsJson, didJson, invitation.label, + const connection: Connection = await this.createConnection( + didJson, + invitation.label, invitation.hasOwnProperty('alias') ? invitation.alias.logoUrl : '', - invitation.hasOwnProperty('alias') ? invitation.alias.organizationId : ''); + invitation.hasOwnProperty('alias') ? invitation.alias.organizationId : '' + ); const connectionRequest = createConnectionRequestMessage(connection, DatabaseServices.getLabel(), logo); connection.state = ConnectionState.REQUESTED; - await sendOutboundMessage(configJson, credentialsJson, connection, connectionRequest, invitation) + await sendOutboundMessage(connection, connectionRequest, invitation) const connectionTags: Object = { connectionId: connection.verkey, } await WalletStorageService.addWalletRecord( - configJson, - credentialsJson, RecordType.Connection, connection.verkey, JSON.stringify(connection), @@ -134,19 +121,17 @@ class ConnectionService { /** * @description Process a received connection request message. This will not accept the connection request * - * @param {WalletConfig} configJson - * @param {WalletCredentials} credentialsJson * @param {InboundMessage} inboundMessage * @return {*} * @memberof ConnectionService */ - async processRequest(configJson: WalletConfig, credentialsJson: WalletCredentials, inboundMessage: InboundMessage) { + async processRequest(inboundMessage: InboundMessage) { const { message, recipient_verkey } = inboundMessage; const query = { connectionId: recipient_verkey } - const connection: Connection = await WalletStorageService.getWalletRecordFromQuery(configJson, credentialsJson, RecordType.Connection, JSON.stringify(query)); + const connection: Connection = await WalletStorageService.getWalletRecordFromQuery(RecordType.Connection, JSON.stringify(query)); if (!connection) { throw new Error(`Connection for verkey ${recipient_verkey} not found!`); @@ -156,7 +141,7 @@ class ConnectionService { throw new Error('Invalid message'); } try { - const receivedMessage: Message = await verify(configJson, credentialsJson, typeMessage, 'connection'); + const receivedMessage: Message = await verify(typeMessage, 'connection'); connection.theirDid = receivedMessage.connection.DID; connection.theirDidDoc = receivedMessage.connection.DIDDoc; if (!connection.theirDidDoc.service[0].recipientKeys[0]) { @@ -181,10 +166,9 @@ class ConnectionService { status: TrustPingState.SENT, } - await sendOutboundMessage(configJson, credentialsJson, connection, trustPingMessage) + await sendOutboundMessage(connection, trustPingMessage) await WalletStorageService.updateWalletRecord( - configJson, credentialsJson, RecordType.Connection, connection.verkey, JSON.stringify(connection), @@ -192,8 +176,6 @@ class ConnectionService { ); await WalletStorageService.addWalletRecord( - configJson, - credentialsJson, RecordType.TrustPing, recipient_verkey, JSON.stringify(trustPing), @@ -201,7 +183,7 @@ class ConnectionService { ); const event: EventInterface = { message: `You are now connected with ${connection.theirLabel}`, - messageData: JSON.stringify({}) + messageData: JSON.stringify({ }) } EventRegister.emit('SDKEvent', event); return true; @@ -215,21 +197,18 @@ class ConnectionService { /** * @description Create a connection response message for the connection with the specified connection id. * - * @param {WalletConfig} configJson - * @param {WalletCredentials} credentialsJson * @param {InboundMessage} inboundMessage * @return {*} * @memberof ConnectionService */ - async createResponse(configJson: WalletConfig, credentialsJson: WalletCredentials, inboundMessage: InboundMessage) { + async createResponse(inboundMessage: InboundMessage) { try { const { message, recipient_verkey } = inboundMessage; const query = { connectionId: recipient_verkey } - const connection: Connection = await WalletStorageService.getWalletRecordFromQuery(configJson, credentialsJson, RecordType.Connection, JSON.stringify(query)); - + const connection: Connection = await WalletStorageService.getWalletRecordFromQuery(RecordType.Connection, JSON.stringify(query)); if (!connection) { throw new Error(`Connection for verkey ${recipient_verkey} not found!`); @@ -251,12 +230,11 @@ class ConnectionService { } const connectionResponse = createConnectionResponseMessage(connection, typeMessage['@id']); - const signedConnectionResponse = await sign(configJson, credentialsJson, connection.verkey, connectionResponse, 'connection'); + const signedConnectionResponse = await sign(connection.verkey, connectionResponse, 'connection'); - await sendOutboundMessage(configJson, credentialsJson, connection, signedConnectionResponse) + await sendOutboundMessage(connection, signedConnectionResponse) await WalletStorageService.updateWalletRecord( - configJson, credentialsJson, RecordType.Connection, connection.verkey, JSON.stringify(connection), @@ -272,8 +250,6 @@ class ConnectionService { /** * @description Create connection and DidDoc. Also register the verkey on mediator agent * - * @param {WalletConfig} configJson - * @param {WalletCredentials} credentialsJson * @param {Object} didJson * @param {string} [label] * @param {string} [logo] @@ -281,15 +257,14 @@ class ConnectionService { * @return {*} {Promise} * @memberof ConnectionService */ - async createConnection(configJson: WalletConfig, - credentialsJson: WalletCredentials, + async createConnection( didJson: Object, label?: string, logo?: string, organizationId?: string, ): Promise { try { - const [pairwiseDid, verkey]: string[] = await ArnimaSdk.createAndStoreMyDid(JSON.stringify(configJson), JSON.stringify(credentialsJson), JSON.stringify(didJson), false); + const [pairwiseDid, verkey]: string[] = await ArnimaSdk.createAndStoreMyDid(JSON.stringify(didJson), false); const apiBody = { publicVerkey: DatabaseServices.getVerKey(), diff --git a/src/protocols/credential/CredentialService.ts b/src/protocols/credential/CredentialService.ts index 7592c55..0fee6bc 100644 --- a/src/protocols/credential/CredentialService.ts +++ b/src/protocols/credential/CredentialService.ts @@ -13,7 +13,6 @@ import { InboundMessage, Message } from '../../utils/Types'; import { NativeModules } from 'react-native'; import { Pool } from '../../pool/PoolInterface'; import { RecordType, decodeBase64, sendOutboundMessage } from '../../utils/Helpers'; -import { WalletConfig, WalletCredentials } from '../../wallet/WalletInterface'; import DatabaseServices from '../../storage'; import WalletStorageService from '../../wallet/WalletStorageService'; @@ -23,21 +22,19 @@ class CredentialService { /** * @description Process a received offer message, This will only store credential record. * - * @param {WalletConfig} configJson - * @param {WalletCredentials} credentialsJson * @param {InboundMessage} inboundMessage * @param {string} messageId * @return {*} {Promise} * @memberof CredentialService */ - async requestReceived(configJson: WalletConfig, credentialsJson: WalletCredentials, inboundMessage: InboundMessage, messageId: string): Promise { + async requestReceived(inboundMessage: InboundMessage, messageId: string): Promise { try { const { recipient_verkey } = inboundMessage; const query = { connectionId: recipient_verkey } - const connection: Connection = await WalletStorageService.getWalletRecordFromQuery(configJson, credentialsJson, RecordType.Connection, JSON.stringify(query)); + const connection: Connection = await WalletStorageService.getWalletRecordFromQuery(RecordType.Connection, JSON.stringify(query)); const message: Message = (inboundMessage.message); const offersAttach = message['offers~attach']; @@ -61,8 +58,6 @@ class CredentialService { if (message.hasOwnProperty('~thread') && Object.keys(message['~thread']).length > 0) { await WalletStorageService.updateWalletRecord( - configJson, - credentialsJson, RecordType.Credential, message.hasOwnProperty('~thread') ? Object.keys(message['~thread']).length > 0 === false ? message['@id'] : message['~thread'].thid : message['@id'], JSON.stringify(issueCredential), @@ -71,8 +66,6 @@ class CredentialService { } else { issueCredential.createdAt = new Date().toISOString() await WalletStorageService.addWalletRecord( - configJson, - credentialsJson, RecordType.Credential, message['@id'], JSON.stringify(issueCredential), @@ -90,8 +83,6 @@ class CredentialService { /** * @description Create a credential proposal and send to particular connection not bound to an existing credential exchange. * - * @param {WalletConfig} configJson - * @param {WalletCredentials} credentialsJson * @param {object} connectionId * @param {string} proposeCredential * @param {string} schemaId @@ -101,7 +92,7 @@ class CredentialService { * @return {*} {Promise} * @memberof CredentialService */ - async createProposal(configJson: WalletConfig, credentialsJson: WalletCredentials, + async createProposal( connectionId: object, proposeCredential: string, schemaId: string, @@ -113,7 +104,7 @@ class CredentialService { try { const query = { connectionId: connectionId } - const connection: Connection = await WalletStorageService.getWalletRecordFromQuery(configJson, credentialsJson, RecordType.Connection, JSON.stringify(query)); + const connection: Connection = await WalletStorageService.getWalletRecordFromQuery(RecordType.Connection, JSON.stringify(query)); const credentialPreview = await credentialPreviewMessage(proposeCredential); const credentialProposal = await credentialProposalMessage(credentialPreview, @@ -130,7 +121,7 @@ class CredentialService { } if (proposeCredential !== '') { - await sendOutboundMessage(configJson, credentialsJson, connection, credentialProposal) + await sendOutboundMessage(connection, credentialProposal) const issueCredentialTags: Object = { connectionId: connection.verkey, @@ -138,8 +129,6 @@ class CredentialService { } await WalletStorageService.addWalletRecord( - configJson, - credentialsJson, RecordType.Credential, credentialProposal["@id"], JSON.stringify(issueCredential), @@ -160,19 +149,17 @@ class CredentialService { /** * @description Create a request credential message as response to a received credential offer. * - * @param {WalletConfig} configJson - * @param {WalletCredentials} credentialsJson * @param {InboundMessage} inboundMessage * @return {*} {Promise} * @memberof CredentialService */ - async createRequest(configJson: WalletConfig, credentialsJson: WalletCredentials, inboundMessage: InboundMessage): Promise { + async createRequest(inboundMessage: InboundMessage): Promise { try { const { recipient_verkey } = inboundMessage; const query = { connectionId: recipient_verkey } - const connection: Connection = await WalletStorageService.getWalletRecordFromQuery(configJson, credentialsJson, RecordType.Connection, JSON.stringify(query)); + const connection: Connection = await WalletStorageService.getWalletRecordFromQuery(RecordType.Connection, JSON.stringify(query)); const message: Message = JSON.parse(inboundMessage.message); const offersAttach = message['offers~attach']; @@ -182,7 +169,7 @@ class CredentialService { isSelected: JSON.stringify(true) } - const poolRecord: Pool = await WalletStorageService.getWalletRecordFromQuery(configJson, credentialsJson, RecordType.Pool, JSON.stringify(queryPool)); + const poolRecord: Pool = await WalletStorageService.getWalletRecordFromQuery(RecordType.Pool, JSON.stringify(queryPool)); const credDefJson: string = await ArnimaSdk.getCredDef( connection.did, credOfferJson.cred_def_id, @@ -191,8 +178,6 @@ class CredentialService { ); const credentialRequest = await ArnimaSdk.proverCreateCredentialReq( - JSON.stringify(configJson), - JSON.stringify(credentialsJson), connection.did, JSON.stringify(credOfferJson), credDefJson, @@ -219,7 +204,7 @@ class CredentialService { message.hasOwnProperty('~thread') ? Object.keys(message['~thread']).length > 0 === false ? message['@id'] : message['~thread'].thid : message['@id'], ); - await sendOutboundMessage(configJson, credentialsJson, connection, credentialRequestMessage) + await sendOutboundMessage(connection, credentialRequestMessage) const issueCredentialTags: Object = { issueCredentialId: message.hasOwnProperty('~thread') ? Object.keys(message['~thread']).length > 0 === false ? message['@id'] : message['~thread'].thid : message['@id'], @@ -228,8 +213,6 @@ class CredentialService { issueCredential.updatedAt = new Date().toISOString() await WalletStorageService.updateWalletRecord( - configJson, - credentialsJson, RecordType.Credential, message.hasOwnProperty('~thread') ? Object.keys(message['~thread']).length > 0 === false ? message['@id'] : message['~thread'].thid : message['@id'], JSON.stringify(issueCredential), @@ -246,13 +229,11 @@ class CredentialService { /** * @description Process a received credential message. This will store the credential and send a credential acknowledgement. * - * @param {WalletConfig} configJson - * @param {WalletCredentials} credentialsJson * @param {InboundMessage} inboundMessage * @return {*} {Promise} * @memberof CredentialService */ - async processCredential(configJson: WalletConfig, credentialsJson: WalletCredentials, inboundMessage: InboundMessage): Promise { + async processCredential(inboundMessage: InboundMessage): Promise { try { const { recipient_verkey } = inboundMessage; const message: Message = JSON.parse(inboundMessage.message); @@ -260,12 +241,12 @@ class CredentialService { const issueCredentialQuery = { issueCredentialId: message.hasOwnProperty('~thread') ? Object.keys(message['~thread']).length > 0 === false ? message['@id'] : message['~thread'].thid : message['@id'] } - const issueCredentialRecord: Credential = await WalletStorageService.getWalletRecordFromQuery(configJson, credentialsJson, RecordType.Credential, JSON.stringify(issueCredentialQuery)); + const issueCredentialRecord: Credential = await WalletStorageService.getWalletRecordFromQuery(RecordType.Credential, JSON.stringify(issueCredentialQuery)); const query = { connectionId: recipient_verkey } - const connection: Connection = await WalletStorageService.getWalletRecordFromQuery(configJson, credentialsJson, RecordType.Connection, JSON.stringify(query)); + const connection: Connection = await WalletStorageService.getWalletRecordFromQuery(RecordType.Connection, JSON.stringify(query)); const credentialsAttach = message['credentials~attach']; const credCertificate = await decodeBase64(credentialsAttach[0].data.base64); @@ -275,7 +256,7 @@ class CredentialService { isSelected: JSON.stringify(true) } - const poolRecord: Pool = await WalletStorageService.getWalletRecordFromQuery(configJson, credentialsJson, RecordType.Pool, JSON.stringify(queryPool)); + const poolRecord: Pool = await WalletStorageService.getWalletRecordFromQuery(RecordType.Pool, JSON.stringify(queryPool)); if (credCertificate.rev_reg_id !== null) { revocRegDefJson = await ArnimaSdk.getRevocRegDef( connection.did, @@ -285,8 +266,6 @@ class CredentialService { ); } const storedCredentialId = await ArnimaSdk.proverStoreCredential( - JSON.stringify(configJson), - JSON.stringify(credentialsJson), null, JSON.stringify(issueCredentialRecord.credentialRequestMetadata), JSON.stringify(credCertificate), @@ -297,7 +276,7 @@ class CredentialService { if (storedCredentialId.length !== '') { issueCredentialRecord.state = CredentialState.STATE_ACKED; issueCredentialRecord.revocRegId = credCertificate.rev_reg_id; - issueCredentialRecord.revocRegDefJson = revocRegDefJson === null ? {} : JSON.parse(revocRegDefJson); + issueCredentialRecord.revocRegDefJson = revocRegDefJson === null ? { } : JSON.parse(revocRegDefJson); issueCredentialRecord.updatedAt = new Date().toISOString(); issueCredentialRecord.credentialId = storedCredentialId; } else { @@ -308,7 +287,7 @@ class CredentialService { message.hasOwnProperty('~thread') ? Object.keys(message['~thread']).length > 0 === false ? message['@id'] : message['~thread'].thid : message['@id'] ); - await sendOutboundMessage(configJson, credentialsJson, connection, credentialRequestMessage) + await sendOutboundMessage(connection, credentialRequestMessage) const issueCredentialTags: Object = { issueCredentialId: message.hasOwnProperty('~thread') ? Object.keys(message['~thread']).length > 0 === false ? message['@id'] : message['~thread'].thid : message['@id'], @@ -316,8 +295,6 @@ class CredentialService { credentialsId: storedCredentialId, } await WalletStorageService.updateWalletRecord( - configJson, - credentialsJson, RecordType.Credential, message['~thread'].thid, JSON.stringify(issueCredentialRecord), diff --git a/src/protocols/mediator/ConnectWithMediatorService.ts b/src/protocols/mediator/ConnectWithMediatorService.ts index 8df37c6..c92203a 100644 --- a/src/protocols/mediator/ConnectWithMediatorService.ts +++ b/src/protocols/mediator/ConnectWithMediatorService.ts @@ -51,8 +51,6 @@ class MediatorService { } await WalletStorageService.updateWalletRecord( - myWallet.walletConfig, - myWallet.walletConfig, RecordType.MediatorAgent, '1', JSON.stringify(walletRecord), diff --git a/src/protocols/presentation/PresentationService.ts b/src/protocols/presentation/PresentationService.ts index cb5fdab..40dd569 100644 --- a/src/protocols/presentation/PresentationService.ts +++ b/src/protocols/presentation/PresentationService.ts @@ -11,7 +11,6 @@ import { Pool } from '../../pool/PoolInterface'; import { Presentation } from './PresentationInterface'; import { PresentationState } from './PresentationState'; import { RecordType, decodeBase64, sendOutboundMessage } from '../../utils/Helpers'; -import { WalletConfig, WalletCredentials } from '../../wallet/WalletInterface'; import DatabaseServices from '../../storage'; import WalletStorageService from '../../wallet/WalletStorageService'; @@ -20,25 +19,23 @@ class PresentationService { /** * @description Process a received presentation message, This will only store record. * - * @param {WalletConfig} configJson - * @param {WalletCredentials} credentialsJson * @param {string} messageId * @param {InboundMessage} inboundMessage * @return {*} {Promise} * @memberof PresentationService */ - async requestReceived(configJson: WalletConfig, credentialsJson: WalletCredentials, messageId: string, inboundMessage: InboundMessage): Promise { + async requestReceived(messageId: string, inboundMessage: InboundMessage): Promise { try { const { recipient_verkey } = inboundMessage; const query = { connectionId: recipient_verkey } - const connection: Connection = await WalletStorageService.getWalletRecordFromQuery(configJson, credentialsJson, RecordType.Connection, JSON.stringify(query)); + const connection: Connection = await WalletStorageService.getWalletRecordFromQuery(RecordType.Connection, JSON.stringify(query)); const message: Message = (inboundMessage.message); const presentationQuery = { presentationId: message.hasOwnProperty('~thread') ? Object.keys(message['~thread']).length > 0 === false ? message['@id'] : message['~thread'].thid : message['@id'] } - const presentation: Presentation = await WalletStorageService.getWalletRecordFromQuery(configJson, credentialsJson, RecordType.Presentation, JSON.stringify(presentationQuery)); + const presentation: Presentation = await WalletStorageService.getWalletRecordFromQuery(RecordType.Presentation, JSON.stringify(presentationQuery)); const presentationsAttach = message['presentations~attach']; const presentationJson = await decodeBase64(presentationsAttach[0].data.base64); const presentProofRecord: Presentation = { @@ -59,8 +56,6 @@ class PresentationService { if (message.hasOwnProperty('~thread') && Object.keys(message['~thread']).length > 0) { await WalletStorageService.updateWalletRecord( - configJson, - credentialsJson, RecordType.Presentation, message.hasOwnProperty('~thread') ? Object.keys(message['~thread']).length > 0 === false ? message['@id'] : message['~thread'].thid : message['@id'], JSON.stringify(presentProofRecord), @@ -69,8 +64,6 @@ class PresentationService { } else { presentProofRecord.createdAt = new Date().toISOString(); await WalletStorageService.addWalletRecord( - configJson, - credentialsJson, RecordType.Presentation, message['@id'], JSON.stringify(presentProofRecord), @@ -87,25 +80,19 @@ class PresentationService { /** * @description Create a propose presentation message not bound to an existing presentation exchange. * - * @param {WalletConfig} configJson - * @param {WalletCredentials} credentialsJson * @param {string} connectionId * @param {object} proposePresentation * @param {string} comment * @return {*} {Promise} * @memberof PresentationService */ - async createProposal(configJson: WalletConfig, credentialsJson: WalletCredentials, - connectionId: string, - proposePresentation: object, - comment: string): Promise { - + async createProposal(connectionId: string, proposePresentation: object, comment: string): Promise { try { const query = { connectionId: connectionId } - const connection: Connection = await WalletStorageService.getWalletRecordFromQuery(configJson, credentialsJson, RecordType.Connection, JSON.stringify(query)); + const connection: Connection = await WalletStorageService.getWalletRecordFromQuery(RecordType.Connection, JSON.stringify(query)); const presentationProposal = await presentationProposalMessage(proposePresentation, comment); const presentProofRecord: Presentation = await { @@ -124,11 +111,9 @@ class PresentationService { if (presentProofRecord) { - await sendOutboundMessage(configJson, credentialsJson, connection, presentationProposal) + await sendOutboundMessage(connection, presentationProposal) await WalletStorageService.addWalletRecord( - configJson, - credentialsJson, RecordType.Presentation, presentationProposal['@id'], JSON.stringify(presentationProposal), @@ -148,23 +133,21 @@ class PresentationService { /** * @description Process a received request presentation message.It will only create a new, or update the existing proof record * - * @param {WalletConfig} configJson - * @param {WalletCredentials} credentialsJson * @param {string} messageId * @param {InboundMessage} inboundMessage * @return {*} {Promise} * @memberof PresentationService */ - async processRequest(configJson: WalletConfig, credentialsJson: WalletCredentials, messageId: string, inboundMessage: InboundMessage): Promise { + async processRequest(messageId: string, inboundMessage: InboundMessage): Promise { try { const { recipient_verkey } = inboundMessage; const query = { connectionId: recipient_verkey } - const connection: Connection = await WalletStorageService.getWalletRecordFromQuery(configJson, credentialsJson, RecordType.Connection, JSON.stringify(query)); + const connection: Connection = await WalletStorageService.getWalletRecordFromQuery(RecordType.Connection, JSON.stringify(query)); const message: Message = inboundMessage.message; if (message.hasOwnProperty('comment') && message.comment.includes(':::auto:::')) { - const response = await this.createPresentation(configJson, credentialsJson, inboundMessage, true); - if (response) { await WalletStorageService.deleteWalletRecord(configJson, credentialsJson, RecordType.SSIMessage, messageId) } + const response = await this.createPresentation(inboundMessage, true); + if (response) { await WalletStorageService.deleteWalletRecord(RecordType.SSIMessage, messageId) } return connection; } else { @@ -186,8 +169,6 @@ class PresentationService { if (message.hasOwnProperty('~thread') && Object.keys(message['~thread']).length > 0) { await WalletStorageService.updateWalletRecord( - configJson, - credentialsJson, RecordType.Presentation, message.hasOwnProperty('~thread') ? Object.keys(message['~thread']).length > 0 === false ? message['@id'] : message['~thread'].thid : message['@id'], JSON.stringify(presentProofRecord), @@ -196,8 +177,6 @@ class PresentationService { } else { presentProofRecord.createdAt = new Date().toISOString(); await WalletStorageService.addWalletRecord( - configJson, - credentialsJson, RecordType.Presentation, message.hasOwnProperty('~thread') ? Object.keys(message['~thread']).length > 0 === false ? message['@id'] : message['~thread'].thid : message['@id'], JSON.stringify(presentProofRecord), @@ -216,14 +195,12 @@ class PresentationService { /** * @description Create a presentation message as response to a received presentation request. * - * @param {WalletConfig} configJson - * @param {WalletCredentials} credentialsJson * @param {InboundMessage} inboundMessage * @param {boolean} [revealAttributes=true] * @return {*} {Promise} * @memberof PresentationService */ - async createPresentation(configJson: WalletConfig, credentialsJson: WalletCredentials, inboundMessage: InboundMessage, revealAttributes: boolean = true, presentationObj?: object): Promise { + async createPresentation(inboundMessage: InboundMessage, revealAttributes: boolean = true, presentationObj?: object): Promise { try { // TODO : Need to find a way for realm db typing @@ -232,14 +209,14 @@ class PresentationService { const query = { connectionId: recipient_verkey } - const connection: Connection = await WalletStorageService.getWalletRecordFromQuery(configJson, credentialsJson, RecordType.Connection, JSON.stringify(query)); + const connection: Connection = await WalletStorageService.getWalletRecordFromQuery(RecordType.Connection, JSON.stringify(query)); const message: Message = inboundMessage.message; const presentationRequest = message['request_presentations~attach']; const proofRequest = await decodeBase64(presentationRequest[0].data.base64); const queryPool = { isSelected: JSON.stringify(true) } - const { poolName, poolConfig }: Pool = await WalletStorageService.getWalletRecordFromQuery(configJson, credentialsJson, RecordType.Pool, JSON.stringify(queryPool)); + const { poolName, poolConfig }: Pool = await WalletStorageService.getWalletRecordFromQuery(RecordType.Pool, JSON.stringify(queryPool)); const [requestedCredentials, revocStates] = await this.getRequestedCredentialsForProofRequest(proofRequest, presentationObj, poolName, poolConfig, sdkDB.publicDid, revealAttributes) const credentialObjects: Array = [] const credIds = [] @@ -254,14 +231,10 @@ class PresentationService { } for (const credentialId of new Set(credIds)) { - const credentialInfo = await ArnimaSdk.proverGetCredential( - JSON.stringify(configJson), - JSON.stringify(credentialsJson), - credentialId - ) + const credentialInfo = await ArnimaSdk.proverGetCredential(credentialId) credentialObjects.push(JSON.parse(credentialInfo)) } - + const [schemas, credDefs] = await Promise.all([ this.generateSchemaJson(credentialObjects, poolName, poolConfig, sdkDB.publicDid), this.generateCredDefJson(credentialObjects, poolName, poolConfig, sdkDB.publicDid)] @@ -269,8 +242,6 @@ class PresentationService { const presentation = await ArnimaSdk.proverCreateProof( - JSON.stringify(configJson), - JSON.stringify(credentialsJson), JSON.stringify(proofRequest), JSON.stringify(requestedCredentials), sdkDB.masterSecretId, @@ -293,11 +264,9 @@ class PresentationService { message.hasOwnProperty('~thread') ? Object.keys(message['~thread']).length > 0 === false ? message['@id'] : message['~thread'].thid : message['@id'], ); - await sendOutboundMessage(configJson, credentialsJson, connection, creatPresentationMessageObject) + await sendOutboundMessage(connection, creatPresentationMessageObject) await WalletStorageService.updateWalletRecord( - configJson, - credentialsJson, RecordType.Presentation, message.hasOwnProperty('~thread') ? Object.keys(message['~thread']).length > 0 === false ? message['@id'] : message['~thread'].thid : message['@id'], JSON.stringify(presentProofRecord), @@ -313,7 +282,7 @@ class PresentationService { public async generateSchemaJson(credentialObjects: any[], poolName: string, poolConfig: string, publicDid: string): Promise { try { - let schemas = {}; + let schemas = { }; const schemaIds = credentialObjects.map((c) => c.schema_id) for (const schemaId of schemaIds) { const schema = await ArnimaSdk.getSchemasJson(poolName, poolConfig, publicDid, schemaId) @@ -327,7 +296,7 @@ class PresentationService { public async generateCredDefJson(credentialObjects: any[], poolName: string, poolConfig: string, publicDid: string): Promise { try { - let credDefs = {}; + let credDefs = { }; const credDefIds = credentialObjects.map((c) => c.cred_def_id) for (const credDefId of credDefIds) { const credDef = await ArnimaSdk.getCredDef(publicDid, credDefId, poolName, poolConfig) @@ -348,14 +317,14 @@ class PresentationService { revealAttributes?: boolean, ): Promise { try { - const revocStates: Object = {} + const revocStates: Object = { } const requestedCredentials = { - self_attested_attributes: {}, - requested_attributes: {}, - requested_predicates: {}, + self_attested_attributes: { }, + requested_attributes: { }, + requested_predicates: { }, } let revRegIdMatcher: string = ''; - let revRegIdJsonMatcher: Object = {}; + let revRegIdJsonMatcher: Object = { }; for (const [referent, requestedAttribute] of Object.entries(proofRequest.requested_attributes)) { let credentialMatch: Credential | null = null const credentials = await this.getCredentialsForProofRequest(proofRequest, referent) @@ -398,7 +367,7 @@ class PresentationService { if (requestedAttribute.restrictions) { let timestampObj: { timestamp?: number - } = {}; + } = { }; if (credentialMatch.cred_info.rev_reg_id !== null) { if (credentialMatch.cred_info.rev_reg_id !== revRegIdMatcher) { @@ -475,7 +444,7 @@ class PresentationService { if (requestedPredicate.restrictions) { let timestampObj: { timestamp?: number - } = {}; + } = { }; if (credMatch.cred_info.rev_reg_id !== null) { if (credMatch.cred_info.rev_reg_id !== revRegIdMatcher) { @@ -555,18 +524,16 @@ class PresentationService { /** * @description Create a request presentation message not bound to an existing presentation exchange. * - * @param {WalletConfig} configJson - * @param {WalletCredentials} credentialsJson * @param {string} connectionId * @param {object} proofRequest * @param {string} comment * @return {*} {Promise} * @memberof PresentationService */ - async createRequest(configJson: WalletConfig, credentialsJson: WalletCredentials, connectionId: string, proofRequest: object, comment: string): Promise { + async createRequest(connectionId: string, proofRequest: object, comment: string): Promise { try { const query = { connectionId: connectionId } - const connection: Connection = await WalletStorageService.getWalletRecordFromQuery(configJson, credentialsJson, RecordType.Connection, JSON.stringify(query)); + const connection: Connection = await WalletStorageService.getWalletRecordFromQuery(RecordType.Connection, JSON.stringify(query)); const requestPresentation = await requestPresentationMessage( JSON.stringify(proofRequest), comment, @@ -581,15 +548,13 @@ class PresentationService { updatedAt: new Date().toISOString(), } - await sendOutboundMessage(configJson, credentialsJson, connection, requestPresentation) + await sendOutboundMessage(connection, requestPresentation) const presentationProofTags: Object = { presentationId: requestPresentation['@id'], connectionId: connection.verkey, } await WalletStorageService.addWalletRecord( - configJson, - credentialsJson, RecordType.Presentation, requestPresentation['@id'], JSON.stringify(presentProofRecord), @@ -607,37 +572,35 @@ class PresentationService { /** * @description Verify an indy proof object. Will also ack to sender. * - * @param {WalletConfig} configJson - * @param {WalletCredentials} credentialsJson * @param {string} messageId * @param {InboundMessage} inboundMessage * @return {*} {Promise} * @memberof PresentationService */ - async verifyProof(configJson: WalletConfig, credentialsJson: WalletCredentials, messageId: string, inboundMessage: InboundMessage): Promise { + async verifyProof(messageId: string, inboundMessage: InboundMessage): Promise { try { // TODO : Need to find a way for realm db typing const sdkDB: any = DatabaseServices.getWallet(); const message: Message = JSON.parse(inboundMessage.message); const presentationQuery = { messageId: messageId } - const presentationRecord = await WalletStorageService.getWalletRecordFromQuery(configJson, credentialsJson, RecordType.Presentation, JSON.stringify(presentationQuery)); + const presentationRecord = await WalletStorageService.getWalletRecordFromQuery(RecordType.Presentation, JSON.stringify(presentationQuery)); const presentProofRecord = presentationRecord.presentation; const presentationRequest = presentationRecord.presentationRequest; const { recipient_verkey } = inboundMessage; const query = { connectionId: recipient_verkey } - const connection: Connection = await WalletStorageService.getWalletRecordFromQuery(configJson, credentialsJson, RecordType.Connection, JSON.stringify(query)); + const connection: Connection = await WalletStorageService.getWalletRecordFromQuery(RecordType.Connection, JSON.stringify(query)); const queryPool = { isSelected: JSON.stringify(true) } - const { poolName, poolConfig }: Pool = await WalletStorageService.getWalletRecordFromQuery(configJson, credentialsJson, RecordType.Pool, JSON.stringify(queryPool)); + const { poolName, poolConfig }: Pool = await WalletStorageService.getWalletRecordFromQuery(RecordType.Pool, JSON.stringify(queryPool)); - const schemas: Object = {} - const credDefs: Object = {} - const revRegDefs: Object = {} - const revRegsObj: Object = {} + const schemas: Object = { } + const credDefs: Object = { } + const revRegDefs: Object = { } + const revRegsObj: Object = { } const identifiers = JSON.parse(presentationRequest).identifiers for (const identifier of new Set(identifiers)) { @@ -680,11 +643,9 @@ class PresentationService { message.hasOwnProperty('~thread') ? Object.keys(message['~thread']).length > 0 === false ? message['@id'] : message['~thread'].thid : message['@id'] ); - await sendOutboundMessage(configJson, credentialsJson, connection, presentationAcknowledgeMessage) + await sendOutboundMessage(connection, presentationAcknowledgeMessage) await WalletStorageService.updateWalletRecord( - configJson, - credentialsJson, RecordType.Presentation, message.hasOwnProperty('~thread') ? Object.keys(message['~thread']).length > 0 === false ? message['@id'] : message['~thread'].thid : message['@id'], JSON.stringify(presentationRecord), diff --git a/src/protocols/trustPing/TrustPingService.ts b/src/protocols/trustPing/TrustPingService.ts index 50a9148..43e7150 100644 --- a/src/protocols/trustPing/TrustPingService.ts +++ b/src/protocols/trustPing/TrustPingService.ts @@ -9,7 +9,6 @@ import { createTrustPingResponseMessage } from './TrustPingMessages'; import { InboundMessage, Message } from '../../utils/Types'; import { RecordType, sendOutboundMessage } from '../../utils/Helpers'; import { TrustPingState } from './TrustPingState'; -import { WalletConfig, WalletCredentials } from '../../wallet/WalletInterface'; import WalletStorageService from '../../wallet/WalletStorageService'; class TrustPingService { @@ -17,17 +16,15 @@ class TrustPingService { /** * @description Process trust ping response message and update the status * - * @param {WalletConfig} configJson - * @param {WalletCredentials} credentialsJson * @param {InboundMessage} inboundMessage * @return {*} {Promise} * @memberof TrustPingService */ - async saveTrustPingResponse(configJson: WalletConfig, credentialsJson: WalletCredentials, inboundMessage: InboundMessage): Promise { + async saveTrustPingResponse(inboundMessage: InboundMessage): Promise { try { const { recipient_verkey } = inboundMessage; const query = { connectionId: recipient_verkey } - const connection: Connection = await WalletStorageService.getWalletRecordFromQuery(configJson, credentialsJson, RecordType.Connection, JSON.stringify(query)); + const connection: Connection = await WalletStorageService.getWalletRecordFromQuery(RecordType.Connection, JSON.stringify(query)); const message: Message = JSON.parse(inboundMessage.message); const trustPingId = message['~thread'].thid; const trustPingTags = { @@ -37,8 +34,6 @@ class TrustPingService { } await WalletStorageService.updateWalletRecord( - configJson, - credentialsJson, RecordType.TrustPing, recipient_verkey, JSON.stringify(message), @@ -54,19 +49,17 @@ class TrustPingService { /** * @description Process trust ping message * - * @param {WalletConfig} configJson - * @param {WalletCredentials} credentialsJson * @param {InboundMessage} inboundMessage * @return {*} {Promise} * @memberof TrustPingService */ - async processPing(configJson: WalletConfig, credentialsJson: WalletCredentials, inboundMessage: InboundMessage): Promise { + async processPing(inboundMessage: InboundMessage): Promise { try { const { recipient_verkey, message } = inboundMessage; const query = { connectionId: recipient_verkey } - const connection: Connection = await WalletStorageService.getWalletRecordFromQuery(configJson, credentialsJson, RecordType.Connection, JSON.stringify(query)); + const connection: Connection = await WalletStorageService.getWalletRecordFromQuery(RecordType.Connection, JSON.stringify(query)); const parseMessage: Message = JSON.parse(message); if (connection.state != ConnectionState.COMPLETE) { @@ -77,11 +70,9 @@ class TrustPingService { if (parseMessage['responseRequested']) { const reply = createTrustPingResponseMessage(parseMessage['@id']); - await sendOutboundMessage(configJson, credentialsJson, connection, reply) + await sendOutboundMessage(connection, reply) await WalletStorageService.updateWalletRecord( - configJson, - credentialsJson, RecordType.Connection, connection.verkey, JSON.stringify(connection), diff --git a/src/transports/index.ts b/src/transports/index.ts index 603519f..fae4bae 100644 --- a/src/transports/index.ts +++ b/src/transports/index.ts @@ -65,10 +65,9 @@ class InboundMessageHandler { isProcessed: JSON.stringify(false), message: typeof message.message == 'string' ? message.message : JSON.stringify(message.message) } - const walletRecords = await WalletStorageService.getWalletRecordsFromQuery(JSON.parse(this.wallet.walletConfig), JSON.parse(this.wallet.walletCredentials), RecordType.SSIMessage, JSON.stringify({ 'messageId': message.id + '' })); + const walletRecords = await WalletStorageService.getWalletRecordsFromQuery(RecordType.SSIMessage, JSON.stringify({ 'messageId': message.id + '' })); if (walletRecords.length === 0) { await WalletStorageService.addWalletRecord( - JSON.parse(this.wallet.walletConfig), JSON.parse(this.wallet.walletCredentials), RecordType.SSIMessage, message.id + '', typeof message.message == 'string' ? message.message : JSON.stringify(message.message), @@ -96,7 +95,7 @@ class InboundMessageHandler { inboundMessageStatusListener = EventRegister.addEventListener('inboundMessageStatusListener', async () => { const query: Object = { isProcessed: JSON.stringify(false) } - const unprocessedMessages: Array = await WalletStorageService.getWalletRecordsFromQuery(JSON.parse(this.wallet.walletConfig), JSON.parse(this.wallet.walletCredentials), RecordType.SSIMessage, JSON.stringify(query)); + const unprocessedMessages: Array = await WalletStorageService.getWalletRecordsFromQuery(RecordType.SSIMessage, JSON.stringify(query)); if (this.isProcess === false && unprocessedMessages.length > 0) { await this.proceedInboundMessage(); } @@ -106,7 +105,7 @@ class InboundMessageHandler { try { const query: Object = { isProcessed: JSON.stringify(false) } - let unprocessedMessages: Array = await WalletStorageService.getWalletRecordsFromQuery(JSON.parse(this.wallet.walletConfig), JSON.parse(this.wallet.walletCredentials), RecordType.SSIMessage, JSON.stringify(query)); + let unprocessedMessages: Array = await WalletStorageService.getWalletRecordsFromQuery(RecordType.SSIMessage, JSON.stringify(query)); if (unprocessedMessages === null) { unprocessedMessages = [] } @@ -114,47 +113,47 @@ class InboundMessageHandler { this.isProcess = true; if (unprocessedMessages[i].tags.autoProcessed === 'true') { const messageRecord = JSON.parse(unprocessedMessages[i].value); - const unpackMessageResponse = await unpackMessage(JSON.parse(this.wallet.walletConfig), JSON.parse(this.wallet.walletCredentials), messageRecord.msg); + const unpackMessageResponse = await unpackMessage(messageRecord.msg); const message = JSON.parse(unpackMessageResponse.message); const query = { connectionId: unpackMessageResponse.recipient_verkey } - const connection = await WalletStorageService.getWalletRecordFromQuery(JSON.parse(this.wallet.walletConfig), JSON.parse(this.wallet.walletCredentials), RecordType.Connection, JSON.stringify(query)); + const connection = await WalletStorageService.getWalletRecordFromQuery(RecordType.Connection, JSON.stringify(query)); console.log('connection', typeof connection) if (connection.length === 0 || connection.verkey === '') { console.log('Connection not found') - await WalletStorageService.deleteWalletRecord(JSON.parse(this.wallet.walletConfig), JSON.parse(this.wallet.walletCredentials), RecordType.SSIMessage, unprocessedMessages[i].id); + await WalletStorageService.deleteWalletRecord(RecordType.SSIMessage, unprocessedMessages[i].id); this.isProcess = false; return; } switch (message['@type']) { case MessageType.ConnectionResponse: { - const isCompleted = await ConnectionService.processRequest(JSON.parse(this.wallet.walletConfig), JSON.parse(this.wallet.walletCredentials), unpackMessageResponse); - if (isCompleted === true) await WalletStorageService.deleteWalletRecord(JSON.parse(this.wallet.walletConfig), JSON.parse(this.wallet.walletCredentials), RecordType.SSIMessage, unprocessedMessages[i].id); + const isCompleted = await ConnectionService.processRequest(unpackMessageResponse); + if (isCompleted === true) await WalletStorageService.deleteWalletRecord(RecordType.SSIMessage, unprocessedMessages[i].id); break; } case MessageType.ConnectionRequest: { - const isCompleted = await ConnectionService.createResponse(JSON.parse(this.wallet.walletConfig), JSON.parse(this.wallet.walletCredentials), unpackMessageResponse); - if (isCompleted === true) await WalletStorageService.deleteWalletRecord(JSON.parse(this.wallet.walletConfig), JSON.parse(this.wallet.walletCredentials), RecordType.SSIMessage, unprocessedMessages[i].id); + const isCompleted = await ConnectionService.createResponse(unpackMessageResponse); + if (isCompleted === true) await WalletStorageService.deleteWalletRecord(RecordType.SSIMessage, unprocessedMessages[i].id); break; } case MessageType.TrustPingMessage: { - const connection: Connection = await TrustPingService.processPing(JSON.parse(this.wallet.walletConfig), JSON.parse(this.wallet.walletCredentials), unpackMessageResponse); - if (connection !== null) { await WalletStorageService.deleteWalletRecord(JSON.parse(this.wallet.walletConfig), JSON.parse(this.wallet.walletCredentials), RecordType.SSIMessage, unprocessedMessages[i].id) } + const connection: Connection = await TrustPingService.processPing(unpackMessageResponse); + if (connection !== null) { await WalletStorageService.deleteWalletRecord(RecordType.SSIMessage, unprocessedMessages[i].id) } const event: EventInterface = { message: `You are now connected with ${connection.theirLabel}`, - messageData: JSON.stringify({}) + messageData: JSON.stringify({ }) } EventRegister.emit('SDKEvent', event); console.log("Connected by scanning the QR code ..."); break; } case MessageType.TrustPingResponseMessage: { - const connection: Connection = await TrustPingService.saveTrustPingResponse(JSON.parse(this.wallet.walletConfig), JSON.parse(this.wallet.walletCredentials), unpackMessageResponse); - if (connection !== null) { await WalletStorageService.deleteWalletRecord(JSON.parse(this.wallet.walletConfig), JSON.parse(this.wallet.walletCredentials), RecordType.SSIMessage, unprocessedMessages[i].id) } + const connection: Connection = await TrustPingService.saveTrustPingResponse(unpackMessageResponse); + if (connection !== null) { await WalletStorageService.deleteWalletRecord(RecordType.SSIMessage, unprocessedMessages[i].id) } break; } case MessageType.OfferCredential: { @@ -168,24 +167,24 @@ class InboundMessageHandler { isProcessed: JSON.stringify(true), } await WalletStorageService.updateWalletRecord( - JSON.parse(this.wallet.walletConfig), JSON.parse(this.wallet.walletCredentials), + RecordType.SSIMessage, unprocessedMessages[i].id + '', JSON.stringify(unpackMessageResponse), JSON.stringify(ssiMessageTags) ); - const connection = await CredentialService.requestReceived(JSON.parse(this.wallet.walletConfig), JSON.parse(this.wallet.walletCredentials), unpackMessageResponse, unprocessedMessages[i].id); + const connection = await CredentialService.requestReceived(unpackMessageResponse, unprocessedMessages[i].id); const event: EventInterface = { message: `You have received a credential from ${connection.theirLabel}`, theirLabel: connection.theirLabel, - messageData: JSON.stringify({}) + messageData: JSON.stringify({ }) } EventRegister.emit('SDKEvent', event); break; } case MessageType.IssueCredential: { - const isCompleted = await CredentialService.processCredential(JSON.parse(this.wallet.walletConfig), JSON.parse(this.wallet.walletCredentials), unpackMessageResponse); - if (isCompleted) { await WalletStorageService.deleteWalletRecord(JSON.parse(this.wallet.walletConfig), JSON.parse(this.wallet.walletCredentials), RecordType.SSIMessage, unprocessedMessages[i].id) } + const isCompleted = await CredentialService.processCredential(unpackMessageResponse); + if (isCompleted) { await WalletStorageService.deleteWalletRecord(RecordType.SSIMessage, unprocessedMessages[i].id) } break; } case MessageType.RequestPresentation: { @@ -199,27 +198,27 @@ class InboundMessageHandler { isProcessed: JSON.stringify(true), } await WalletStorageService.updateWalletRecord( - JSON.parse(this.wallet.walletConfig), JSON.parse(this.wallet.walletCredentials), + RecordType.SSIMessage, unprocessedMessages[i].id + '', JSON.stringify(unpackMessageResponse), JSON.stringify(ssiMessageTags) ); - const connection = await PresentationService.processRequest(JSON.parse(this.wallet.walletConfig), JSON.parse(this.wallet.walletCredentials), unprocessedMessages[i].id, unpackMessageResponse); + const connection = await PresentationService.processRequest(unprocessedMessages[i].id, unpackMessageResponse); const event: EventInterface = { message: `You have received a proof request from ${connection.theirLabel}`, theirLabel: connection.theirLabel, - messageData: JSON.stringify({}) + messageData: JSON.stringify({ }) } EventRegister.emit('SDKEvent', event); break; } case MessageType.PresentationAck: { - await WalletStorageService.deleteWalletRecord(JSON.parse(this.wallet.walletConfig), JSON.parse(this.wallet.walletCredentials), RecordType.SSIMessage, unprocessedMessages[i].id) + await WalletStorageService.deleteWalletRecord(RecordType.SSIMessage, unprocessedMessages[i].id) const event: EventInterface = { message: 'Your proof is verified successfully', - messageData: JSON.stringify({}) + messageData: JSON.stringify({ }) } EventRegister.emit('SDKEvent', event); break; @@ -235,33 +234,33 @@ class InboundMessageHandler { isProcessed: JSON.stringify(true), } await WalletStorageService.updateWalletRecord( - JSON.parse(this.wallet.walletConfig), JSON.parse(this.wallet.walletCredentials), + RecordType.SSIMessage, unprocessedMessages[i].id + '', JSON.stringify(unpackMessageResponse), JSON.stringify(ssiMessageTags) ); - const connection = await PresentationService.requestReceived(JSON.parse(this.wallet.walletConfig), JSON.parse(this.wallet.walletCredentials), unprocessedMessages[i].id, unpackMessageResponse); + const connection = await PresentationService.requestReceived(unprocessedMessages[i].id, unpackMessageResponse); const event: EventInterface = { message: `You have received a proof request to verify from ${connection.theirLabel}`, - messageData: JSON.stringify({}) + messageData: JSON.stringify({ }) } EventRegister.emit('SDKEvent', event); break; } case MessageType.problemReport: { - await WalletStorageService.deleteWalletRecord(JSON.parse(this.wallet.walletConfig), JSON.parse(this.wallet.walletCredentials), RecordType.SSIMessage, unprocessedMessages[i].id) + await WalletStorageService.deleteWalletRecord(RecordType.SSIMessage, unprocessedMessages[i].id) break; } case MessageType.BasicMessage: { - const connection = await BasicMessageService.save(JSON.parse(this.wallet.walletConfig), JSON.parse(this.wallet.walletCredentials), unpackMessageResponse, unpackMessageResponse.recipient_verkey); - if (connection) { await WalletStorageService.deleteWalletRecord(JSON.parse(this.wallet.walletConfig), JSON.parse(this.wallet.walletCredentials), RecordType.SSIMessage, unprocessedMessages[i].id) } + const connection = await BasicMessageService.save(unpackMessageResponse, unpackMessageResponse.recipient_verkey); + if (connection) { await WalletStorageService.deleteWalletRecord(RecordType.SSIMessage, unprocessedMessages[i].id) } const event: EventInterface = { message: `You have received a message from ${connection.theirLabel}`, connectionId: connection.verkey, - messageData: JSON.stringify({}) + messageData: JSON.stringify({ }) } EventRegister.emit('SDKEvent', event); break; diff --git a/src/utils/Helpers.ts b/src/utils/Helpers.ts index be685a2..81e9d4d 100644 --- a/src/utils/Helpers.ts +++ b/src/utils/Helpers.ts @@ -40,7 +40,7 @@ function timestamp(): Uint8Array { return Uint8Array.from(bytes).reverse(); } -export async function verify(configJson: WalletConfig, credentialsJson: WalletCredentials, message: Message, field: string) { +export async function verify(message: Message, field: string) { try { const fieldKey = `${field}~sig` const { [fieldKey]: data, ...signedMessage } = message; @@ -51,18 +51,18 @@ export async function verify(configJson: WalletConfig, credentialsJson: WalletCr let valid; if (Platform.OS == 'android') { - valid = await ArnimaSdk.cryptoVerify(JSON.stringify(configJson), - JSON.stringify(credentialsJson), + valid = await ArnimaSdk.cryptoVerify( signerVerkey, Array.from(signedData), - Array.from(signature)); + Array.from(signature), + ); } else { - valid = await ArnimaSdk.cryptoVerify(JSON.stringify(configJson), - JSON.stringify(credentialsJson), + valid = await ArnimaSdk.cryptoVerify( signerVerkey, data.sig_data, - JSON.stringify(Array.from(signature))); + JSON.stringify(Array.from(signature)) + ); } // if (!valid) { @@ -82,7 +82,7 @@ export async function verify(configJson: WalletConfig, credentialsJson: WalletCr } } -export async function sign(configJson: WalletConfig, credentialsJson: WalletCredentials, signerVerkey: string, message: Message, field: string) { +export async function sign(signerVerkey: string, message: Message, field: string) { try { const { [field]: data, ...originalMessage } = message; @@ -91,15 +91,15 @@ export async function sign(configJson: WalletConfig, credentialsJson: WalletCred let signatureBuffer; if (Platform.OS === 'ios') { - signatureBuffer = await ArnimaSdk.cryptoSign(JSON.stringify(configJson), - JSON.stringify(credentialsJson), + signatureBuffer = await ArnimaSdk.cryptoSign( signerVerkey, - JSON.stringify(data)); + JSON.stringify(data) + ); } else { - signatureBuffer = await ArnimaSdk.cryptoSign(JSON.stringify(configJson), - JSON.stringify(credentialsJson), + signatureBuffer = await ArnimaSdk.cryptoSign( signerVerkey, - Array.from(dataBuffer)); + Array.from(dataBuffer) + ); } const signedMessage = { @@ -121,15 +121,15 @@ export async function sign(configJson: WalletConfig, credentialsJson: WalletCred } } -export async function unpackMessage(configJson: WalletConfig, credentialsJson: WalletCredentials, inboundMessage: InboundMessage) { +export async function unpackMessage(inboundMessage: InboundMessage) { try { const buf = Buffer.from(JSON.stringify(inboundMessage)); let unpackedBufferMessage; if (Platform.OS === 'ios') { - unpackedBufferMessage = await ArnimaSdk.unpackMessage(JSON.stringify(configJson), JSON.stringify(credentialsJson), JSON.stringify(inboundMessage)) + unpackedBufferMessage = await ArnimaSdk.unpackMessage(JSON.stringify(inboundMessage)) } else { - unpackedBufferMessage = await ArnimaSdk.unpackMessage(JSON.stringify(configJson), JSON.stringify(credentialsJson), Array.from(buf)) + unpackedBufferMessage = await ArnimaSdk.unpackMessage(Array.from(buf)) } const unpackedMessage = Buffer.from(unpackedBufferMessage); return JSON.parse(unpackedMessage.toString('utf-8')); @@ -139,16 +139,16 @@ export async function unpackMessage(configJson: WalletConfig, credentialsJson: W } } -export async function packMessage(configJson: WalletConfig, credentialsJson: WalletCredentials, outboundMessage: OutboundMessage) { +export async function packMessage(outboundMessage: OutboundMessage) { try { const { routingKeys, recipientKeys, senderVk, payload } = outboundMessage; const buf = Buffer.from(JSON.stringify(payload)); let packedBufferMessage; if (Platform.OS === 'ios') { - packedBufferMessage = await ArnimaSdk.packMessage(JSON.stringify(configJson), JSON.stringify(credentialsJson), JSON.stringify(payload), recipientKeys, senderVk) + packedBufferMessage = await ArnimaSdk.packMessage(JSON.stringify(payload), recipientKeys, senderVk) } else { - packedBufferMessage = await ArnimaSdk.packMessage(JSON.stringify(configJson), JSON.stringify(credentialsJson), Array.from(buf), recipientKeys, senderVk) + packedBufferMessage = await ArnimaSdk.packMessage(Array.from(buf), recipientKeys, senderVk) } const packedMessage = Buffer.from(packedBufferMessage); const outboundPackedMessage = JSON.parse(packedMessage.toString('utf-8')); @@ -161,10 +161,10 @@ export async function packMessage(configJson: WalletConfig, credentialsJson: Wal const forwardMessageBuffer = Buffer.from(JSON.stringify(forwardMessage)); let forwardBufferMessage; if (Platform.OS === 'ios') { - forwardBufferMessage = await ArnimaSdk.packMessage(JSON.stringify(configJson), JSON.stringify(credentialsJson), JSON.stringify(forwardMessage), [routingKey], senderVk) + forwardBufferMessage = await ArnimaSdk.packMessage(JSON.stringify(forwardMessage), [routingKey], senderVk) } else { - forwardBufferMessage = await ArnimaSdk.packMessage(JSON.stringify(configJson), JSON.stringify(credentialsJson), Array.from(forwardMessageBuffer), [routingKey], senderVk) + forwardBufferMessage = await ArnimaSdk.packMessage(Array.from(forwardMessageBuffer), [routingKey], senderVk) } const forwardPackedMessage = Buffer.from(forwardBufferMessage); message = JSON.parse(forwardPackedMessage.toString('utf-8')); @@ -233,8 +233,8 @@ export function createOutboundMessage(connection: Connection, payload: Object, i }; } -export async function sendOutboundMessage(configJson: WalletConfig, credentialsJson: WalletCredentials, connection: Connection, message: Object, invitation?: Message) { +export async function sendOutboundMessage(connection: Connection, message: Object, invitation?: Message) { const outboundMessage = await createOutboundMessage(connection, message, invitation); - const outboundPackMessage = await packMessage(configJson, credentialsJson, outboundMessage); + const outboundPackMessage = await packMessage(outboundMessage); await OutboundAgentMessage(outboundMessage.endpoint, 'POST', JSON.stringify(outboundPackMessage)); } diff --git a/src/wallet/WalletService.ts b/src/wallet/WalletService.ts index a61fbc8..c62f402 100644 --- a/src/wallet/WalletService.ts +++ b/src/wallet/WalletService.ts @@ -71,8 +71,6 @@ class WalletService { } await WalletStorageService.addWalletRecord( - config, - credentials, RecordType.MediatorAgent, '1', JSON.stringify(walletRecord), diff --git a/src/wallet/WalletStorageService.ts b/src/wallet/WalletStorageService.ts index c78dc69..894e71f 100644 --- a/src/wallet/WalletStorageService.ts +++ b/src/wallet/WalletStorageService.ts @@ -4,50 +4,43 @@ */ import { NativeModules } from "react-native"; -import { Record, WalletConfig, WalletCredentials, WalletStorageRecord } from "./WalletInterface"; +import { Record, WalletStorageRecord } from "./WalletInterface"; const { ArnimaSdk } = NativeModules; class WalletStorageService { - async addWalletRecord(config: WalletConfig, credentials: WalletCredentials, type: string, id: string, - value: string, tags: string) { + async addWalletRecord(type: string, id: string, value: string, tags: string) { try { - return await ArnimaSdk.addWalletRecord(JSON.stringify(config), JSON.stringify(credentials), - type, id, value, tags); + return await ArnimaSdk.addWalletRecord(type, id, value, tags); } catch (error) { console.log('WalletStorageService - ' + type + ' - Add wallet record = ', error); throw error; } } - async updateWalletRecord(config: WalletConfig, credentials: WalletCredentials, type: string, id: string, - value: string, tags: string) { - + async updateWalletRecord(type: string, id: string, value: string, tags: string) { try { - return await ArnimaSdk.updateWalletRecord(JSON.stringify(config), JSON.stringify(credentials), - type, id, value, tags); + return await ArnimaSdk.updateWalletRecord(type, id, value, tags); } catch (error) { console.log('WalletStorageService - ' + type + ' - Update wallet record = ', error); throw error; } } - async deleteWalletRecord(config: WalletConfig, credentials: WalletCredentials, type: string, id: string) { - + async deleteWalletRecord(type: string, id: string) { try { - return await ArnimaSdk.deleteWalletRecord(JSON.stringify(config), JSON.stringify(credentials), - type, id); + return await ArnimaSdk.deleteWalletRecord(type, id); } catch (error) { console.log('WalletStorageService - ' + type + ' - Delete wallet record = ', error); throw error; } } - async getWalletRecordFromQuery(config: WalletConfig, credentials: WalletCredentials, type: string, query: string) { + async getWalletRecordFromQuery(type: string, query: string) { try { - const queryResponse: string = await ArnimaSdk.getWalletRecordFromQuery(JSON.stringify(config), JSON.stringify(credentials), type, query); + const queryResponse: string = await ArnimaSdk.getWalletRecordFromQuery(type, query); const walletRecord: WalletStorageRecord = JSON.parse(queryResponse); if (walletRecord.records !== null) { @@ -63,9 +56,9 @@ class WalletStorageService { } } - async getWalletRecordsFromQuery(config: WalletConfig, credentials: WalletCredentials, type: string, query: string): Promise> { + async getWalletRecordsFromQuery(type: string, query: string): Promise> { try { - const queryResponse: string = await ArnimaSdk.getWalletRecordFromQuery(JSON.stringify(config), JSON.stringify(credentials), type, query); + const queryResponse: string = await ArnimaSdk.getWalletRecordFromQuery(type, query); const walletRecord: WalletStorageRecord = JSON.parse(queryResponse); return walletRecord.records === null ? [] : walletRecord.records; } catch (error) { From b90185e42c1bf640dfe06148e17e6255d7c57942 Mon Sep 17 00:00:00 2001 From: Sai Ranjit Tummalapalli Date: Wed, 1 Sep 2021 10:59:57 +0530 Subject: [PATCH 2/5] refactor: added config for create did and verkey method Signed-off-by: Sai Ranjit Tummalapalli --- src/agent/index.ts | 6 +----- src/protocols/connection/ConnectionService.ts | 9 ++++++++- src/wallet/WalletService.ts | 8 +++++--- 3 files changed, 14 insertions(+), 9 deletions(-) diff --git a/src/agent/index.ts b/src/agent/index.ts index dfb644c..f2bbe8d 100644 --- a/src/agent/index.ts +++ b/src/agent/index.ts @@ -263,11 +263,7 @@ class Agent { getAllCredential = async (filter?: Object) => { try { - const getCredentials = await ArnimaSdk.proverGetCredentials( - this.wallet.walletConfig, - this.wallet.walletCredentials, - JSON.stringify(filter) - ); + const getCredentials = await ArnimaSdk.proverGetCredentials(JSON.stringify(filter)); return JSON.parse(getCredentials); } catch (error) { console.log("Agent - List all credentials error = ", error); diff --git a/src/protocols/connection/ConnectionService.ts b/src/protocols/connection/ConnectionService.ts index 516f8f0..5eb625a 100644 --- a/src/protocols/connection/ConnectionService.ts +++ b/src/protocols/connection/ConnectionService.ts @@ -264,7 +264,14 @@ class ConnectionService { organizationId?: string, ): Promise { try { - const [pairwiseDid, verkey]: string[] = await ArnimaSdk.createAndStoreMyDid(JSON.stringify(didJson), false); + const wallet: any = await DatabaseServices.getWallet(); + + const [pairwiseDid, verkey]: string[] = await ArnimaSdk.createAndStoreMyDid( + wallet.walletConfig, + wallet.walletCredentials, + JSON.stringify(didJson), + false + ); const apiBody = { publicVerkey: DatabaseServices.getVerKey(), diff --git a/src/wallet/WalletService.ts b/src/wallet/WalletService.ts index c62f402..25d668d 100644 --- a/src/wallet/WalletService.ts +++ b/src/wallet/WalletService.ts @@ -19,18 +19,20 @@ class WalletService { JSON.stringify(config), JSON.stringify(credentials) ); - return await this.createWalletDidStore(config, credentials, {}, true, label); + return await this.createWalletDidStore(config, credentials, { }, true, label); } catch (error) { console.log('WalletService - Create wallet error = ', error); throw (error); } } - async createWalletDidStore(config: WalletConfig, + async createWalletDidStore( + config: WalletConfig, credentials: WalletCredentials, didJson: DidJson, createMasterSecret: boolean, - label: string): Promise { + label: string + ): Promise { const response: string[] = await ArnimaSdk.createAndStoreMyDid( JSON.stringify(config), From b6cded2cf9e8b963b896d7c95d47711c9fc2e8be Mon Sep 17 00:00:00 2001 From: Sai Ranjit Tummalapalli Date: Wed, 1 Sep 2021 11:11:51 +0530 Subject: [PATCH 3/5] refactor: renamed the method getwallet record query Signed-off-by: Sai Ranjit Tummalapalli --- .../main/java/com/arnimasdk/ArnimaSdk.java | 32 ++++++++++++++----- 1 file changed, 24 insertions(+), 8 deletions(-) diff --git a/android/src/main/java/com/arnimasdk/ArnimaSdk.java b/android/src/main/java/com/arnimasdk/ArnimaSdk.java index ac5ada1..9220c08 100644 --- a/android/src/main/java/com/arnimasdk/ArnimaSdk.java +++ b/android/src/main/java/com/arnimasdk/ArnimaSdk.java @@ -101,12 +101,28 @@ public void createPoolLedgerConfig(String poolName, String poolConfig, Promise p @ReactMethod public void createWallet(String walletConfig, String walletCredentials, Promise promise) { - try { - Wallet.createWallet(walletConfig, walletCredentials).get(); - promise.resolve(null); - } catch (Exception e) { - IndySdkRejectResponse rejectResponse = new IndySdkRejectResponse(e); - promise.reject(rejectResponse.getCode(), rejectResponse.toJson(), e); + new CreateWallet().execute(walletConfig, walletCredentials, promise); + } + + private class CreateWallet extends AsyncTask { + Promise promise = null; + + @Override + protected Object doInBackground(Object[] objects) { + try { + promise = (Promise) objects[2]; + Wallet.createWallet(objects[0].toString(), objects[1].toString()).get(); + promise.resolve(null); + } catch (Exception e) { + IndySdkRejectResponse rejectResponse = new IndySdkRejectResponse(e); + promise.reject(rejectResponse.getCode(), rejectResponse.toJson(), e); + } + return promise; + } + + @Override + protected void onPreExecute() { + super.onPreExecute(); } } @@ -187,7 +203,7 @@ public void createAndStoreMyDid(String walletConfig, String walletCredentials, S Boolean createMasterSecret, Promise promise) { Wallet wallet = null; try { - wallet = getWalletHandle(promise); + wallet = openWallet(walletConfig, walletCredentials ,promise); if (wallet != null) { DidResults.CreateAndStoreMyDidResult createMyDidResult = Did .createAndStoreMyDid(wallet, didJson).get(); @@ -265,7 +281,7 @@ public void deleteWalletRecord(String recordType, String id, } @ReactMethod - public void getWalletHandleRecordFromQuery(String recordType, String query, + public void getWalletRecordFromQuery(String recordType, String query, Promise promise) { Wallet wallet = null; try { From 6eb8ed6debe000f073a1a3857a8d4bde60e2938a Mon Sep 17 00:00:00 2001 From: Tushar Gore Date: Thu, 2 Sep 2021 17:23:42 +0530 Subject: [PATCH 4/5] Wallet config code refactor in iOS Signed-off-by: Tushar Gore --- ios/RNArnimaSdk.m | 139 ++++++++++++++++------------------------------ 1 file changed, 47 insertions(+), 92 deletions(-) diff --git a/ios/RNArnimaSdk.m b/ios/RNArnimaSdk.m index 2df089f..5ab2f0a 100644 --- a/ios/RNArnimaSdk.m +++ b/ios/RNArnimaSdk.m @@ -47,6 +47,11 @@ -(void) openWallet: (NSString *)config } } +-(IndyHandle) getWalletHandle +{ + return WalletHandleNumber; +} + RCT_EXPORT_METHOD(createWallet: (NSString *)config :(NSString *)walletCredentials @@ -62,16 +67,15 @@ -(void) openWallet: (NSString *)config }]; } -RCT_EXPORT_METHOD(exportWallet: - (NSString *)walletConfig - :(NSString *)walletCredentials +RCT_EXPORT_METHOD(exportWallet :(NSString *)config resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject) { - [self openWallet:walletConfig :walletCredentials completion:^(IndyHandle walletHandle) { - if (walletHandle > 0) { - [[IndyWallet sharedInstance] exportWalletWithHandle:walletHandle exportConfigJson:config completion:^(NSError *errorWhileExportWallet) { + IndyHandle wallet = [self getWalletHandle]; + + if (wallet > 0) { + [[IndyWallet sharedInstance] exportWalletWithHandle:wallet exportConfigJson:config completion:^(NSError *errorWhileExportWallet) { if(errorWhileExportWallet.code > 1) { [self rejectResult:errorWhileExportWallet reject:reject]; } @@ -80,7 +84,6 @@ -(void) openWallet: (NSString *)config } }]; } - }]; } RCT_EXPORT_METHOD(importWallet: @@ -199,17 +202,15 @@ -(void) openWallet: (NSString *)config }]; } -RCT_EXPORT_METHOD(addWalletRecord: - (NSString *)walletConfig - :(NSString *)walletCredentials - :(NSString *)Type +RCT_EXPORT_METHOD(addWalletRecord:(NSString *)Type :(NSString *)Id :(NSString *)value :(NSString *)tags resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject) { - [self openWallet:walletConfig :walletCredentials completion:^(IndyHandle walletHandle) { + IndyHandle walletHandle = [self getWalletHandle]; + if (walletHandle > 0) { [IndyNonSecrets addRecordInWallet:walletHandle type:Type id:Id value:value tagsJson:tags completion:^(NSError *errorWhileAddRecord) { if(errorWhileAddRecord.code > 1) { @@ -220,22 +221,16 @@ -(void) openWallet: (NSString *)config } }]; } - - }]; } -RCT_EXPORT_METHOD(updateWalletRecord: - (NSString *)walletConfig - :(NSString *)walletCredentials +RCT_EXPORT_METHOD(updateWalletRecord :(NSString *)type :(NSString *)Id :(NSString *)value :(NSString *)tag resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject) { - - - [self openWallet:walletConfig :walletCredentials completion:^(IndyHandle walletHandle) { + IndyHandle walletHandle = [self getWalletHandle]; if (walletHandle > 0) { [IndyNonSecrets updateRecordValueInWallet:walletHandle type:type id:Id value:value completion:^(NSError *errorWhileUpdateRecordValue) { if(errorWhileUpdateRecordValue.code > 1) { @@ -258,19 +253,17 @@ -(void) openWallet: (NSString *)config } }]; } - - }]; + } -RCT_EXPORT_METHOD(deleteWalletRecord: - (NSString *)walletConfig - :(NSString *)walletCredentials +RCT_EXPORT_METHOD(deleteWalletRecord :(NSString *)type :(NSString *)Id resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject){ - [self openWallet:walletConfig :walletCredentials completion:^(IndyHandle walletHandle) { + IndyHandle walletHandle = [self getWalletHandle]; + if (walletHandle > 0) { [IndyNonSecrets deleteRecordInWallet:walletHandle type:type id:Id completion:^(NSError *errorWhileDeleteREcord) { if(errorWhileDeleteREcord.code > 1) { @@ -281,21 +274,17 @@ -(void) openWallet: (NSString *)config } }]; } - }]; - - } -RCT_EXPORT_METHOD(getWalletRecordFromQuery: - (NSString *)walletConfig - :(NSString *)walletCredentials +RCT_EXPORT_METHOD(getWalletRecordFromQuery :(NSString *)type :(NSString *)query resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject) { - [self openWallet:walletConfig :walletCredentials completion:^(IndyHandle walletHandle) { + IndyHandle walletHandle = [self getWalletHandle]; + if (walletHandle > 0) { [IndyNonSecrets openSearchInWallet:walletHandle type:type queryJson:query optionsJson:@"{\"retrieveTags\":true,\"retrieveType \":true, \"retrieveType\": true }" completion:^(NSError *errorOS, IndyHandle searchHandle) { if(errorOS.code > 1) { @@ -313,20 +302,16 @@ -(void) openWallet: (NSString *)config } }]; } - - }]; - } -RCT_EXPORT_METHOD(cryptoSign: - (NSString *)walletConfig - :(NSString *)walletCredentials +RCT_EXPORT_METHOD(cryptoSign :(NSString *)signerKey :(NSString *)messageRaw resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject) { - [self openWallet:walletConfig :walletCredentials completion:^(IndyHandle walletHandle) { + IndyHandle walletHandle = [self getWalletHandle]; + if (walletHandle > 0) { NSData *jsonData = [messageRaw dataUsingEncoding:NSUTF8StringEncoding]; [IndyCrypto signMessage:jsonData key:signerKey walletHandle:walletHandle completion:^(NSError *errorWhileSignMessage, NSData *signature) { @@ -349,20 +334,16 @@ -(void) openWallet: (NSString *)config } }]; } - - }]; - } -RCT_EXPORT_METHOD(packMessage: - (NSString *)walletConfig - :(NSString *)walletCredentials +RCT_EXPORT_METHOD(packMessage :(NSString *)message :(NSArray *)receiverKeys :(NSString *)senderVerkey resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject) { - [self openWallet:walletConfig :walletCredentials completion:^(IndyHandle walletHandle) { + IndyHandle walletHandle = [self getWalletHandle]; + if (walletHandle > 0) { [IndyCrypto createKey:@"{}" walletHandle:walletHandle completion:^(NSError *errorWhileCreateKey, NSString *verkey1) { if(errorWhileCreateKey.code > 1) { @@ -387,19 +368,15 @@ -(void) openWallet: (NSString *)config } }]; } - }]; - - } -RCT_EXPORT_METHOD(unpackMessage: - (NSString *)walletConfig - :(NSString *)walletCredentials +RCT_EXPORT_METHOD(unpackMessage :(NSString *)message resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject) { - [self openWallet:walletConfig :walletCredentials completion:^(IndyHandle walletHandle) { + IndyHandle walletHandle = [self getWalletHandle]; + if (walletHandle > 0) { NSData *messageData = [message dataUsingEncoding:NSUTF8StringEncoding]; [IndyCrypto unpackMessage:messageData walletHandle:walletHandle completion:^(NSError *errorWhileUnpackMessage, NSData *unPackMessageData) { @@ -412,15 +389,9 @@ -(void) openWallet: (NSString *)config } }]; } - - }]; - - } -RCT_EXPORT_METHOD(cryptoVerify: - (NSString *)walletConfig - :(NSString *)walletCredentials +RCT_EXPORT_METHOD(cryptoVerify :(NSString *)signVerkey :(NSString *)message :(NSString *)signatureRaw @@ -428,7 +399,8 @@ -(void) openWallet: (NSString *)config reject:(RCTPromiseRejectBlock)reject) { NSData *messageData = [message dataUsingEncoding:NSUTF8StringEncoding]; - [self openWallet:walletConfig :walletCredentials completion:^(IndyHandle walletHandle) { + IndyHandle walletHandle = [self getWalletHandle]; + if (walletHandle > 0) { NSData *revocRegDefJsonData = [signatureRaw dataUsingEncoding:NSUTF8StringEncoding]; id generatedRevocRegDefJsonData = [NSJSONSerialization JSONObjectWithData:revocRegDefJsonData options:0 error:nil]; @@ -462,8 +434,6 @@ -(void) openWallet: (NSString *)config } }]; } - - }]; } RCT_EXPORT_METHOD(createPoolLedgerConfig: @@ -505,9 +475,7 @@ -(void) openWallet: (NSString *)config -RCT_EXPORT_METHOD(proverCreateCredentialReq: - (NSString *)walletConfig - :(NSString *)credentialsJson +RCT_EXPORT_METHOD(proverCreateCredentialReq :(NSString *)proverDid :(NSString *)credentialOfferJson :(NSString *)credentialDefJson @@ -515,7 +483,8 @@ -(void) openWallet: (NSString *)config resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject) { - [self openWallet:walletConfig :credentialsJson completion:^(IndyHandle walletHandle) { + IndyHandle walletHandle = [self getWalletHandle]; + if (walletHandle > 0) { [IndyAnoncreds proverCreateCredentialReqForCredentialOffer:credentialOfferJson credentialDefJSON:credentialDefJson proverDID:proverDid masterSecretID:masterSecretId walletHandle:walletHandle completion:^(NSError *errorWhileCreateRequest, NSString *credReqJSON, NSString *credReqMetadataJSON) { if(errorWhileCreateRequest.code > 1) { @@ -529,12 +498,9 @@ -(void) openWallet: (NSString *)config } }]; } - }]; } -RCT_EXPORT_METHOD(proverStoreCredential: - (NSString *)walletConfig - :(NSString *)credentialsJson +RCT_EXPORT_METHOD(proverStoreCredential :(NSString *)credId :(NSString *)credReqMetadataJson :(NSString *)credJson @@ -542,7 +508,8 @@ -(void) openWallet: (NSString *)config :(NSString *)revRegDefJson resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject){ - [self openWallet:walletConfig :credentialsJson completion:^(IndyHandle walletHandle) { + IndyHandle walletHandle = [self getWalletHandle]; + if (walletHandle > 0) { [IndyAnoncreds proverStoreCredential:credJson credID:credId credReqMetadataJSON:credReqMetadataJson credDefJSON:credDefJson revRegDefJSON:revRegDefJson walletHandle:walletHandle completion:^(NSError *errorWhileStoreCredential, NSString *outCredID) { if(errorWhileStoreCredential.code > 1) { @@ -553,16 +520,14 @@ -(void) openWallet: (NSString *)config } }]; } - }]; } -RCT_EXPORT_METHOD(proverGetCredentials: - (NSString *)walletConfig - :(NSString *)credentialsJson +RCT_EXPORT_METHOD(proverGetCredentials :(NSString *)filter resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject){ - [self openWallet:walletConfig :credentialsJson completion:^(IndyHandle walletHandle) { + IndyHandle walletHandle = [self getWalletHandle]; + if (walletHandle > 0) { [IndyAnoncreds proverGetCredentialsForFilter:filter walletHandle:walletHandle completion:^(NSError *errorWhileGetCredential, NSString *credentialsJSON) { if(errorWhileGetCredential.code > 1) { @@ -573,8 +538,6 @@ -(void) openWallet: (NSString *)config } }]; } - }]; - } RCT_EXPORT_METHOD(getRevocRegDef: @@ -850,13 +813,12 @@ -(void) openWallet: (NSString *)config } RCT_EXPORT_METHOD(proverGetCredential - :(NSString *) walletConfig - :(NSString *) walletCredentials :(NSString *) credId resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject) { - [self openWallet:walletConfig :walletCredentials completion:^(IndyHandle walletHandle) { + IndyHandle walletHandle = [self getWalletHandle]; + if (walletHandle > 0) { [IndyAnoncreds proverGetCredentialWithId:credId walletHandle:walletHandle completion:^(NSError *error, NSString *credentialJSON) { if(error.code > 1) { @@ -867,8 +829,6 @@ -(void) openWallet: (NSString *)config } }]; } - }]; - } RCT_EXPORT_METHOD(getSchemasJson @@ -1239,9 +1199,7 @@ -(void) openWallet: (NSString *)config } -RCT_EXPORT_METHOD(proverCreateProof: - (NSString *)walletConfig - :(NSString *)walletCredentials +RCT_EXPORT_METHOD(proverCreateProof :(NSString *)proofRequest :(NSString *)requestedCredentials :(NSString *)masterSecret @@ -1251,7 +1209,7 @@ -(void) openWallet: (NSString *)config resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject){ - [self openWallet:walletConfig :walletCredentials completion:^(IndyHandle walletHandle) { + IndyHandle walletHandle = [self getWalletHandle]; if (walletHandle > 0) { [IndyAnoncreds proverCreateProofForRequest:proofRequest requestedCredentialsJSON:requestedCredentials masterSecretID:masterSecret schemasJSON:schemas credentialDefsJSON:credentialDefs revocStatesJSON:revocObject walletHandle:walletHandle completion:^(NSError *errorWhileCreateProofRequest, NSString *proofJSON) { if(errorWhileCreateProofRequest.code > 1) { @@ -1259,12 +1217,9 @@ -(void) openWallet: (NSString *)config } else { resolve(proofJSON); - } }]; } - }]; - } @end From 9b64dadbaf7d4280dbb770f2777d6869143ccf84 Mon Sep 17 00:00:00 2001 From: Sai Ranjit Tummalapalli Date: Tue, 1 Feb 2022 13:33:30 +0530 Subject: [PATCH 5/5] refactor: ran prettier Signed-off-by: Sai Ranjit Tummalapalli --- .prettierrc.js | 1 + src/agent/index.ts | 510 +++++++++++------- src/core/index.ts | 4 +- src/network/index.ts | 54 +- src/pool/index.ts | 91 ++-- .../basicMessage/BasicMessageMessages.ts | 8 +- .../basicMessage/BasicMessageService.ts | 107 ++-- src/storage/index.ts | 46 +- src/utils/Helpers.ts | 177 +++--- src/utils/MessageType.ts | 12 +- src/wallet/WalletService.ts | 87 +-- src/wallet/WalletStorageService.ts | 85 ++- 12 files changed, 694 insertions(+), 488 deletions(-) diff --git a/.prettierrc.js b/.prettierrc.js index 355e7d1..0c73287 100644 --- a/.prettierrc.js +++ b/.prettierrc.js @@ -3,4 +3,5 @@ module.exports = { jsxBracketSameLine: true, singleQuote: true, trailingComma: 'all', + semi: false, }; diff --git a/src/agent/index.ts b/src/agent/index.ts index 3e6aa0b..7654ee5 100644 --- a/src/agent/index.ts +++ b/src/agent/index.ts @@ -3,225 +3,280 @@ SPDX-License-Identifier: Apache-2.0 */ - -import { decodeInvitationFromUrl, RecordType } from '../utils/Helpers'; -import { InboundMessage } from '../utils/Types'; -import { MessageType } from '../utils/MessageType'; -import { NativeModules } from 'react-native'; -import { WalletConfig, WalletCredentials } from '../wallet/WalletInterface'; -import BasicMessageService from '../protocols/basicMessage/BasicMessageService'; -import ConnectionService from '../protocols/connection/ConnectionService'; -import ConnectWithMediatorService from '../protocols/mediator/ConnectWithMediatorService'; -import CredentialService from '../protocols/credential/CredentialService'; -import DatabaseServices from '../storage'; -import InboundMessageService from '../transports'; -import PoolService from '../pool'; -import PresentationService from '../protocols/presentation/PresentationService'; -import WalletService from '../wallet/WalletService'; -import WalletStorageService from '../wallet/WalletStorageService'; - -const { ArnimaSdk } = NativeModules; +import { decodeInvitationFromUrl, RecordType } from '../utils/Helpers' +import { InboundMessage } from '../utils/Types' +import { MessageType } from '../utils/MessageType' +import { NativeModules } from 'react-native' +import { WalletConfig, WalletCredentials } from '../wallet/WalletInterface' +import BasicMessageService from '../protocols/basicMessage/BasicMessageService' +import ConnectionService from '../protocols/connection/ConnectionService' +import ConnectWithMediatorService from '../protocols/mediator/ConnectWithMediatorService' +import CredentialService from '../protocols/credential/CredentialService' +import DatabaseServices from '../storage' +import InboundMessageService from '../transports' +import PoolService from '../pool' +import PresentationService from '../protocols/presentation/PresentationService' +import WalletService from '../wallet/WalletService' +import WalletStorageService from '../wallet/WalletStorageService' + +const { ArnimaSdk } = NativeModules class Agent { - wallet: any = DatabaseServices.getWallet(); + wallet: any = DatabaseServices.getWallet() getRequestRedirectionUrl = async (url: string) => { return await ArnimaSdk.getRequestRedirectionUrl(url) } - createWallet = async (config: WalletConfig, credentials: WalletCredentials, label: string) => { + createWallet = async ( + config: WalletConfig, + credentials: WalletCredentials, + label: string, + ) => { try { - return await WalletService.createWallet(config, credentials, label); + return await WalletService.createWallet(config, credentials, label) } catch (error) { - console.log("Agent - Create wallet error= ", error); - throw error; + console.log('Agent - Create wallet error= ', error) + throw error } } - connectWithMediator = async (url: string, apiType: string, apiBody: string) => { + connectWithMediator = async ( + url: string, + apiType: string, + apiBody: string, + ) => { try { - const response = await ConnectWithMediatorService.ConnectWithMediator(url, apiType, apiBody); - this.wallet = await DatabaseServices.getWallet(); - return response; - } - catch (error) { - console.log("Agent - Connect with mediator error = ", error); - throw error; + const response = await ConnectWithMediatorService.ConnectWithMediator( + url, + apiType, + apiBody, + ) + this.wallet = await DatabaseServices.getWallet() + return response + } catch (error) { + console.log('Agent - Connect with mediator error = ', error) + throw error } } updateMediator = async (url: string, apiType: string, apiBody: string) => { try { - return await ConnectWithMediatorService.updateMediator(url, apiType, apiBody); - } - catch (error) { - console.log("Agent - Update mediator error = ", error); - throw error; + return await ConnectWithMediatorService.updateMediator( + url, + apiType, + apiBody, + ) + } catch (error) { + console.log('Agent - Update mediator error = ', error) + throw error } } getWallet = async () => { try { - return await WalletService.getWallet(); + return await WalletService.getWallet() } catch (error) { - console.log('Agent - Get wallet error = ', error); - throw error; + console.log('Agent - Get wallet error = ', error) + throw error } } openWallet = async () => { try { - return await WalletService.openWallet(); + return await WalletService.openWallet() } catch (error) { - console.log("Agent - Open wallet error = ", error); - throw error; + console.log('Agent - Open wallet error = ', error) + throw error } - }; + } getAllPool = async () => { try { - return await PoolService.getAllPool(); + return await PoolService.getAllPool() } catch (error) { - console.log("Agent - Get all pool error = ", error); - throw error; + console.log('Agent - Get all pool error = ', error) + throw error } - }; + } - createPool = async (poolName: string, poolConfig: string, defaultPool?: boolean) => { + createPool = async ( + poolName: string, + poolConfig: string, + defaultPool?: boolean, + ) => { try { - return await PoolService.createPool(poolName, poolConfig, defaultPool); + return await PoolService.createPool(poolName, poolConfig, defaultPool) } catch (error) { - console.log("Agent - Create pool error = ", error); - throw error; + console.log('Agent - Create pool error = ', error) + throw error } - }; + } selectDefaultPool = async (poolName: string) => { try { return await PoolService.selectDefaultPool(poolName) } catch (error) { - console.log("Agent - Select default pool error = ", error); - throw error; + console.log('Agent - Select default pool error = ', error) + throw error } - }; + } createInvitation = async (didJson: Object, logo: string) => { try { - return await ConnectionService.createInvitation(didJson, logo); + return await ConnectionService.createInvitation(didJson, logo) } catch (error) { - console.log("Agent - Create invitation error = ", error); - throw error; + console.log('Agent - Create invitation error = ', error) + throw error } } - acceptInvitation = async (didJson: Object, message: any, logo: string,) => { + acceptInvitation = async (didJson: Object, message: any, logo: string) => { try { - const invitation = decodeInvitationFromUrl(message); - return await ConnectionService.acceptInvitation(didJson, invitation, logo); - } - catch (error) { - console.log("Agent - Accept invitation error = ", error); - throw error; + const invitation = decodeInvitationFromUrl(message) + return await ConnectionService.acceptInvitation(didJson, invitation, logo) + } catch (error) { + console.log('Agent - Accept invitation error = ', error) + throw error } } getConnectionRecord = async (query: Object) => { try { - return await WalletStorageService.getWalletRecordsFromQuery(RecordType.Connection, JSON.stringify(query)); - } - catch (error) { - console.log("Agent - Get all connections error = ", error); - throw error; + return await WalletStorageService.getWalletRecordsFromQuery( + RecordType.Connection, + JSON.stringify(query), + ) + } catch (error) { + console.log('Agent - Get all connections error = ', error) + throw error } } getPresentationRecord = async (query: Object) => { try { - return await WalletStorageService.getWalletRecordsFromQuery(RecordType.Presentation, JSON.stringify(query)); - } - catch (error) { - console.log("Agent - Get all connections error = ", error); - throw error; + return await WalletStorageService.getWalletRecordsFromQuery( + RecordType.Presentation, + JSON.stringify(query), + ) + } catch (error) { + console.log('Agent - Get all connections error = ', error) + throw error } } basicMessageHistory = async (query: Object) => { try { - return await WalletStorageService.getWalletRecordsFromQuery(RecordType.BasicMessage, JSON.stringify(query)); - } - catch (error) { - console.log("Agent - Get all connections error = ", error); - throw error; + return await WalletStorageService.getWalletRecordsFromQuery( + RecordType.BasicMessage, + JSON.stringify(query), + ) + } catch (error) { + console.log('Agent - Get all connections error = ', error) + throw error } } deleteConnection = async (connectionId: string) => { try { - const records = await WalletStorageService.getWalletRecordsFromQuery(RecordType.Credential, JSON.stringify({ connectionId: connectionId })); + const records = await WalletStorageService.getWalletRecordsFromQuery( + RecordType.Credential, + JSON.stringify({ connectionId: connectionId }), + ) if (records === null || records.length === 0) { - await WalletStorageService.deleteWalletRecord(RecordType.Connection, connectionId); - return true; + await WalletStorageService.deleteWalletRecord( + RecordType.Connection, + connectionId, + ) + return true } else { - return false; + return false } } catch (error) { - console.log('Agent - Delete connection error = ', error); - throw error; + console.log('Agent - Delete connection error = ', error) + throw error } } getAllActionMessages = async () => { try { const query = { autoProcessed: false } - return await WalletStorageService.getWalletRecordsFromQuery(RecordType.SSIMessage, JSON.stringify(query)); - } - catch (error) { - console.log("Agent - Get all action messages error= ", error); - throw error; + return await WalletStorageService.getWalletRecordsFromQuery( + RecordType.SSIMessage, + JSON.stringify(query), + ) + } catch (error) { + console.log('Agent - Get all action messages error= ', error) + throw error } } getIssueCredentialByConnectionId = async (connectionId: string) => { try { - let query = { } + let query = {} if (connectionId !== null) { query = { connectionId: connectionId } } - return await WalletStorageService.getWalletRecordsFromQuery(RecordType.Credential, JSON.stringify(query)); + return await WalletStorageService.getWalletRecordsFromQuery( + RecordType.Credential, + JSON.stringify(query), + ) } catch (error) { - console.log('Agent - Get issue credential by connection id error = ', error); - throw error; + console.log( + 'Agent - Get issue credential by connection id error = ', + error, + ) + throw error } } getPresentationByConnectionId = async (connectionId: string) => { try { - return await WalletStorageService.getWalletRecordsFromQuery(RecordType.Presentation, JSON.stringify({ connectionId: connectionId })); + return await WalletStorageService.getWalletRecordsFromQuery( + RecordType.Presentation, + JSON.stringify({ connectionId: connectionId }), + ) } catch (error) { - console.log('Agent - Get presentation by connection id error = ', error); - throw error; + console.log('Agent - Get presentation by connection id error = ', error) + throw error } } getAllActionMessagesById = async (thId: string) => { try { - return await WalletStorageService.getWalletRecordFromQuery(RecordType.SSIMessage, JSON.stringify({ thId: thId })); + return await WalletStorageService.getWalletRecordFromQuery( + RecordType.SSIMessage, + JSON.stringify({ thId: thId }), + ) } catch (error) { - console.log('Agent - Get all action messages by id error = ', error); - throw error; + console.log('Agent - Get all action messages by id error = ', error) + throw error } } getIssueCredentialByCredentialsId = async (referent: string) => { try { - return await WalletStorageService.getWalletRecordFromQuery(RecordType.Credential, JSON.stringify({ credentialsId: referent })); + return await WalletStorageService.getWalletRecordFromQuery( + RecordType.Credential, + JSON.stringify({ credentialsId: referent }), + ) } catch (error) { - console.log('Agent - Get all issue credential by credentials id error = ', error); - throw error; + console.log( + 'Agent - Get all issue credential by credentials id error = ', + error, + ) + throw error } } - sendCredentialProposal = async (connectionId: object, credentialProposal: string, schemaId: string, credDefId: string, issuerDid: string, comment: string) => { + sendCredentialProposal = async ( + connectionId: object, + credentialProposal: string, + schemaId: string, + credDefId: string, + issuerDid: string, + comment: string, + ) => { try { return await CredentialService.createProposal( connectionId, @@ -229,137 +284,205 @@ class Agent { schemaId, credDefId, issuerDid, - comment - ); + comment, + ) } catch (error) { - console.log('Agent - Send credential proposal error = ', error); - throw error; + console.log('Agent - Send credential proposal error = ', error) + throw error } } - acceptCredentialOffer = async (messageId: string, inboundMessage: InboundMessage) => { + acceptCredentialOffer = async ( + messageId: string, + inboundMessage: InboundMessage, + ) => { try { - let { message }: any = inboundMessage; - message = JSON.stringify(message); - inboundMessage['message'] = message; - const response: Boolean = await CredentialService.createRequest(inboundMessage); - if (response) await WalletStorageService.deleteWalletRecord(RecordType.SSIMessage, messageId); - return response; + let { message }: any = inboundMessage + message = JSON.stringify(message) + inboundMessage['message'] = message + const response: Boolean = await CredentialService.createRequest( + inboundMessage, + ) + if (response) + await WalletStorageService.deleteWalletRecord( + RecordType.SSIMessage, + messageId, + ) + return response } catch (error) { - console.log('Agent - Accept credential offer error = ', error); - throw error; + console.log('Agent - Accept credential offer error = ', error) + throw error } } - storeCredential = async (messageId: string, inboundMessage: InboundMessage) => { + storeCredential = async ( + messageId: string, + inboundMessage: InboundMessage, + ) => { try { - let { message }: any = inboundMessage; - message = JSON.stringify(message); - inboundMessage['message'] = message; - const response: Boolean = await CredentialService.processCredential(inboundMessage); - if (response) await WalletStorageService.deleteWalletRecord(RecordType.SSIMessage, messageId); - return response; + let { message }: any = inboundMessage + message = JSON.stringify(message) + inboundMessage['message'] = message + const response: Boolean = await CredentialService.processCredential( + inboundMessage, + ) + if (response) + await WalletStorageService.deleteWalletRecord( + RecordType.SSIMessage, + messageId, + ) + return response } catch (error) { - console.log('Agent - Store credential error = ', error); - throw error; + console.log('Agent - Store credential error = ', error) + throw error } } getAllCredential = async (filter?: Object) => { try { - const getCredentials = await ArnimaSdk.proverGetCredentials(JSON.stringify(filter)); - return JSON.parse(getCredentials); + const getCredentials = await ArnimaSdk.proverGetCredentials( + JSON.stringify(filter), + ) + return JSON.parse(getCredentials) } catch (error) { - console.log("Agent - List all credentials error = ", error); - throw error; + console.log('Agent - List all credentials error = ', error) + throw error } - }; + } sendBasicMessage = async (message: string, connectionId: string) => { try { - return await BasicMessageService.send(message, connectionId); + return await BasicMessageService.send(message, connectionId) } catch (error) { - console.log('Agent - Send message error = ', error); - throw error; + console.log('Agent - Send message error = ', error) + throw error } } - sendProposePresentation = async (connectionId: string, + sendProposePresentation = async ( + connectionId: string, presentationProposal: object, - comment: string + comment: string, ) => { try { - presentationProposal["@type"] = MessageType.presentationPreview; + presentationProposal['@type'] = MessageType.presentationPreview return await PresentationService.createProposal( connectionId, presentationProposal, - comment - ); + comment, + ) } catch (error) { - console.log('Agent - Send propose presentation error = ', error); - throw error; + console.log('Agent - Send propose presentation error = ', error) + throw error } } - sendOutOfBandProof = async (inboundMessage: InboundMessage, revealAttributes: boolean, presentationObj: object) => { + sendOutOfBandProof = async ( + inboundMessage: InboundMessage, + revealAttributes: boolean, + presentationObj: object, + ) => { try { - const response: Boolean = await PresentationService.createPresentation(JSON.parse(this.wallet.walletConfig), JSON.parse(this.wallet.walletCredentials), inboundMessage, revealAttributes, presentationObj); - return response; + const response: Boolean = await PresentationService.createPresentation( + JSON.parse(this.wallet.walletConfig), + JSON.parse(this.wallet.walletCredentials), + inboundMessage, + revealAttributes, + presentationObj, + ) + return response } catch (error) { - console.log('Agent - Send proof error = ', error); - throw error; + console.log('Agent - Send proof error = ', error) + throw error } } - sendProof = async (messageId: string, inboundMessage: InboundMessage, revealAttributes: boolean, presentationObj: object) => { + sendProof = async ( + messageId: string, + inboundMessage: InboundMessage, + revealAttributes: boolean, + presentationObj: object, + ) => { try { - const response: Boolean = await PresentationService.createPresentation(inboundMessage, revealAttributes, presentationObj); - if (response) { await WalletStorageService.deleteWalletRecord(RecordType.SSIMessage, messageId) } - return response; + const response: Boolean = await PresentationService.createPresentation( + inboundMessage, + revealAttributes, + presentationObj, + ) + if (response) { + await WalletStorageService.deleteWalletRecord( + RecordType.SSIMessage, + messageId, + ) + } + return response } catch (error) { - console.log('Agent - Send proof error = ', error); - throw error; + console.log('Agent - Send proof error = ', error) + throw error } } verifyProof = async (messageId: string, inboundMessage: InboundMessage) => { try { - let { message }: any = inboundMessage; - message = JSON.stringify(message); - inboundMessage['message'] = message; - const response = await PresentationService.verifyProof(messageId, inboundMessage); - await WalletStorageService.deleteWalletRecord(RecordType.SSIMessage, messageId) - return response; + let { message }: any = inboundMessage + message = JSON.stringify(message) + inboundMessage['message'] = message + const response = await PresentationService.verifyProof( + messageId, + inboundMessage, + ) + await WalletStorageService.deleteWalletRecord( + RecordType.SSIMessage, + messageId, + ) + return response } catch (error) { - console.log('Agent - Verify proof error = ', error); - throw error; + console.log('Agent - Verify proof error = ', error) + throw error } } - sendPresentProofRequest = async (connectionId: string, proofRequest: object, comment: string) => { + sendPresentProofRequest = async ( + connectionId: string, + proofRequest: object, + comment: string, + ) => { try { - return await PresentationService.createRequest(connectionId, proofRequest, comment); + return await PresentationService.createRequest( + connectionId, + proofRequest, + comment, + ) } catch (error) { - console.log('Agent - Send present proof request error = ', error); - throw error; + console.log('Agent - Send present proof request error = ', error) + throw error } } getAllActionMessagesByMessageId = async (messageId: string) => { try { - return await WalletStorageService.getWalletRecordFromQuery(RecordType.SSIMessage, JSON.stringify({ messageId: messageId })); + return await WalletStorageService.getWalletRecordFromQuery( + RecordType.SSIMessage, + JSON.stringify({ messageId: messageId }), + ) } catch (error) { - console.log('Agent - Get all action messages by message id error = ', error); - throw error; + console.log( + 'Agent - Get all action messages by message id error = ', + error, + ) + throw error } } getConnection = async (connectionId: string) => { try { - return await WalletStorageService.getWalletRecordFromQuery(RecordType.Connection, JSON.stringify({ connectionId: connectionId })); + return await WalletStorageService.getWalletRecordFromQuery( + RecordType.Connection, + JSON.stringify({ connectionId: connectionId }), + ) } catch (error) { - console.log('Agent - Get Connection from connection id error = ', error); - throw error; + console.log('Agent - Get Connection from connection id error = ', error) + throw error } } @@ -371,36 +494,44 @@ class Agent { try { const config = { path: filePath, - key: key + key: key, } - const data = []; + const data = [] - await PoolService.deletePoolRecords(); + await PoolService.deletePoolRecords() - const response = await ArnimaSdk.exportWallet(JSON.stringify(config)); + const response = await ArnimaSdk.exportWallet(JSON.stringify(config)) - return response; + return response } catch (error) { - console.log('Agent - Export wallet error = ', error); - throw error; + console.log('Agent - Export wallet error = ', error) + throw error } } - importWallet = async (config: WalletConfig, credentials: WalletCredentials, filePath: string, key: string) => { + importWallet = async ( + config: WalletConfig, + credentials: WalletCredentials, + filePath: string, + key: string, + ) => { try { const importConfig = { path: filePath, - key: key + key: key, } await ArnimaSdk.importWallet( JSON.stringify(config), JSON.stringify(credentials), JSON.stringify(importConfig), - JSON.stringify([]) - ); + JSON.stringify([]), + ) - const mediatorRecord = await WalletStorageService.getWalletRecordFromQuery(RecordType.MediatorAgent, '{}'); + const mediatorRecord = await WalletStorageService.getWalletRecordFromQuery( + RecordType.MediatorAgent, + '{}', + ) DatabaseServices.storeWallet({ walletConfig: JSON.stringify(config), @@ -411,21 +542,20 @@ class Agent { publicDid: mediatorRecord.publicDid, verKey: mediatorRecord.verKey, masterSecretId: mediatorRecord.masterSecretId, - }); + }) const record = { mediatorRecord, } - this.wallet = await DatabaseServices.getWallet(); + this.wallet = await DatabaseServices.getWallet() - return record; + return record } catch (error) { - console.log('Agent - Import wallet error = ', error); - throw error; + console.log('Agent - Import wallet error = ', error) + throw error } } - } -export default new Agent(); \ No newline at end of file +export default new Agent() diff --git a/src/core/index.ts b/src/core/index.ts index df830f5..ba0dcd4 100644 --- a/src/core/index.ts +++ b/src/core/index.ts @@ -3,10 +3,10 @@ SPDX-License-Identifier: Apache-2.0 */ -import AgentServices from '../agent'; +import AgentServices from '../agent' const ARNIMASDK = { ...AgentServices, } -export default ARNIMASDK; \ No newline at end of file +export default ARNIMASDK diff --git a/src/network/index.ts b/src/network/index.ts index 0bbcb2d..f58ab09 100644 --- a/src/network/index.ts +++ b/src/network/index.ts @@ -3,7 +3,11 @@ SPDX-License-Identifier: Apache-2.0 */ -export const NetworkServices: Function = async (url: string, apiType: string, apiBody: string) => { +export const NetworkServices: Function = async ( + url: string, + apiType: string, + apiBody: string, +) => { try { const response = await fetch(url, { method: apiType, @@ -12,23 +16,25 @@ export const NetworkServices: Function = async (url: string, apiType: string, ap Accept: 'application/json', 'Content-Type': 'application/json', }, - }); - const responseJson = await response.json(); + }) + const responseJson = await response.json() if (responseJson.hasOwnProperty('success')) { - return responseJson; + return responseJson } else { - throw responseJson; + throw responseJson } } catch (error) { - throw error; + throw error } -}; +} -export const OutboundAgentMessage: Function = async (url: string, apiType: string, apiBody: string) => { +export const OutboundAgentMessage: Function = async ( + url: string, + apiType: string, + apiBody: string, +) => { try { - return new Promise(async function ( - resolve, reject - ) { + return new Promise(async function(resolve, reject) { const response = await fetch(url, { method: apiType, body: apiBody, @@ -36,18 +42,22 @@ export const OutboundAgentMessage: Function = async (url: string, apiType: strin Accept: 'application/json', 'Content-Type': 'application/ssi-agent-wire', }, - }).then((response) => { - response.json() }) - .then((json) => { - resolve(json); + .then(response => { + response.json() }) - .catch((error) => { - reject('We are not able to communicate with the agent at this moment, Please try again later'); - }); - } - ) + .then(json => { + resolve(json) + }) + .catch(error => { + reject( + 'We are not able to communicate with the agent at this moment, Please try again later', + ) + }) + }) } catch (error) { - throw new Error('We are not able to communicate with the agent at this moment, Please try again later'); + throw new Error( + 'We are not able to communicate with the agent at this moment, Please try again later', + ) } -}; \ No newline at end of file +} diff --git a/src/pool/index.ts b/src/pool/index.ts index c1c74a2..872d494 100644 --- a/src/pool/index.ts +++ b/src/pool/index.ts @@ -3,16 +3,15 @@ SPDX-License-Identifier: Apache-2.0 */ -import { NativeModules } from "react-native"; -import { Pool, PoolTags } from "./PoolInterface"; -import { Record, WalletConfig, WalletCredentials } from "../wallet/WalletInterface"; -import { RecordType } from "../utils/Helpers"; -import WalletStorageService from "../wallet/WalletStorageService"; +import { NativeModules } from 'react-native' +import { Pool, PoolTags } from './PoolInterface' +import { Record } from '../wallet/WalletInterface' +import { RecordType } from '../utils/Helpers' +import WalletStorageService from '../wallet/WalletStorageService' -const { ArnimaSdk } = NativeModules; +const { ArnimaSdk } = NativeModules class PoolService { - /** * Create pool genesis file and set default pool * @@ -22,35 +21,39 @@ class PoolService { * @return {*} {Promise} * @memberof PoolService */ - async createPool(poolName: string, poolConfig: string, defaultPool: boolean = false): Promise { + async createPool( + poolName: string, + poolConfig: string, + defaultPool: boolean = false, + ): Promise { try { const response: null = await ArnimaSdk.createPoolLedgerConfig( poolName, - poolConfig - ); + poolConfig, + ) if (response === null || response === 'NULL') { const poolRecord: Pool = { poolName: poolName, - poolConfig: poolConfig + poolConfig: poolConfig, } const poolTags: PoolTags = { poolName: poolName, - isSelected: JSON.stringify(defaultPool) + isSelected: JSON.stringify(defaultPool), } await WalletStorageService.addWalletRecord( RecordType.Pool, poolName, JSON.stringify(poolRecord), - JSON.stringify(poolTags) - ); + JSON.stringify(poolTags), + ) } - return response; + return response } catch (error) { - console.log("Pool - Create pool error = ", error); - throw error; + console.log('Pool - Create pool error = ', error) + throw error } - }; + } /** * Return all the create pool records @@ -60,15 +63,18 @@ class PoolService { */ async getAllPool(): Promise { try { - return await WalletStorageService.getWalletRecordsFromQuery(RecordType.Pool, '{}'); + return await WalletStorageService.getWalletRecordsFromQuery( + RecordType.Pool, + '{}', + ) } catch (error) { - console.log("Pool - Get all pools error = ", error); - throw error; + console.log('Pool - Get all pools error = ', error) + throw error } } /** - * Update default select pool + * Update default select pool * * @param {string} poolName * @return {*} {Promise} @@ -76,16 +82,21 @@ class PoolService { */ async selectDefaultPool(poolName: string): Promise { try { - const poolRecords: Array = await WalletStorageService.getWalletRecordsFromQuery(RecordType.Pool, '{}'); + const poolRecords: Array< + Record + > = await WalletStorageService.getWalletRecordsFromQuery( + RecordType.Pool, + '{}', + ) for await (let record of poolRecords) { - const pool: Pool = JSON.parse(record.value); + const pool: Pool = JSON.parse(record.value) const poolRecord: Pool = { poolName: pool.poolName, - poolConfig: pool.poolConfig + poolConfig: pool.poolConfig, } const poolTags: PoolTags = { poolName: pool.poolName, - isSelected: JSON.stringify(false) + isSelected: JSON.stringify(false), } if (pool.poolName === poolName) { poolTags.isSelected = JSON.stringify(true) @@ -95,13 +106,13 @@ class PoolService { RecordType.Pool, pool.poolName, JSON.stringify(poolRecord), - JSON.stringify(poolTags) - ); + JSON.stringify(poolTags), + ) } return true } catch (error) { - console.log("Pool - Select default pool error = ", error); - throw error; + console.log('Pool - Select default pool error = ', error) + throw error } } @@ -113,20 +124,24 @@ class PoolService { */ async deletePoolRecords(): Promise { try { - const poolRecords: Array = await WalletStorageService.getWalletRecordsFromQuery(RecordType.Pool, '{}'); + const poolRecords: Array< + Record + > = await WalletStorageService.getWalletRecordsFromQuery( + RecordType.Pool, + '{}', + ) for await (let record of poolRecords) { - const pool: Pool = JSON.parse(record.value); + const pool: Pool = JSON.parse(record.value) await WalletStorageService.deleteWalletRecord( RecordType.Pool, pool.poolName, - ); + ) } - return true; + return true } catch (error) { - console.log("Pool - Select default pool error = ", error); - throw error; + console.log('Pool - Select default pool error = ', error) + throw error } } - } -export default new PoolService(); \ No newline at end of file +export default new PoolService() diff --git a/src/protocols/basicMessage/BasicMessageMessages.ts b/src/protocols/basicMessage/BasicMessageMessages.ts index 8d0f290..d1caf1a 100644 --- a/src/protocols/basicMessage/BasicMessageMessages.ts +++ b/src/protocols/basicMessage/BasicMessageMessages.ts @@ -3,8 +3,8 @@ SPDX-License-Identifier: Apache-2.0 */ -import { MessageType } from '../../utils/MessageType'; -import { v4 as uuidv4 } from 'uuid'; +import { MessageType } from '../../utils/MessageType' +import { v4 as uuidv4 } from 'uuid' export function createBasicMessage(content: string) { return { @@ -13,5 +13,5 @@ export function createBasicMessage(content: string) { '~l10n': { locale: 'en' }, sent_time: new Date().toISOString(), content, - }; -} \ No newline at end of file + } +} diff --git a/src/protocols/basicMessage/BasicMessageService.ts b/src/protocols/basicMessage/BasicMessageService.ts index 2d4dde0..6aab692 100644 --- a/src/protocols/basicMessage/BasicMessageService.ts +++ b/src/protocols/basicMessage/BasicMessageService.ts @@ -3,14 +3,13 @@ SPDX-License-Identifier: Apache-2.0 */ -import { Connection } from '../connection/ConnectionInterface'; -import { createBasicMessage } from './BasicMessageMessages'; -import { InboundMessage } from '../../utils/Types'; -import { RecordType, sendOutboundMessage } from '../../utils/Helpers'; -import WalletStorageService from '../../wallet/WalletStorageService'; +import { Connection } from '../connection/ConnectionInterface' +import { createBasicMessage } from './BasicMessageMessages' +import { InboundMessage } from '../../utils/Types' +import { RecordType, sendOutboundMessage } from '../../utils/Helpers' +import WalletStorageService from '../../wallet/WalletStorageService' class BasicMessageService { - /** * @description Send basic message to exiting connection * @@ -22,50 +21,60 @@ class BasicMessageService { async send(message: string, connectionId: string): Promise { try { const query = { - connectionId: connectionId + connectionId: connectionId, } - const connection: Connection = await WalletStorageService.getWalletRecordFromQuery(RecordType.Connection, JSON.stringify(query)); - const basicMessage = createBasicMessage(message); + const connection: Connection = await WalletStorageService.getWalletRecordFromQuery( + RecordType.Connection, + JSON.stringify(query), + ) + const basicMessage = createBasicMessage(message) const chatBody = { type: 'sent', message, time: new Date().toISOString(), - }; + } const basicMessageTags: Object = { connectionId: connectionId, - lastUpdatedAt: new Date().toISOString() + lastUpdatedAt: new Date().toISOString(), } - const chatThread: Array = await WalletStorageService.getWalletRecordFromQuery(RecordType.BasicMessage, JSON.stringify(query)); + const chatThread: Array< + Object + > = await WalletStorageService.getWalletRecordFromQuery( + RecordType.BasicMessage, + JSON.stringify(query), + ) - if (chatThread === undefined || chatThread === null || chatThread.length == 0) { + if ( + chatThread === undefined || + chatThread === null || + chatThread.length == 0 + ) { await WalletStorageService.addWalletRecord( RecordType.BasicMessage, connectionId, JSON.stringify([chatBody]), - JSON.stringify(basicMessageTags) - ); - } - else { - chatThread.push(chatBody); + JSON.stringify(basicMessageTags), + ) + } else { + chatThread.push(chatBody) await WalletStorageService.updateWalletRecord( RecordType.BasicMessage, connectionId, JSON.stringify(chatThread), - JSON.stringify(basicMessageTags) - ); + JSON.stringify(basicMessageTags), + ) } - setTimeout(async ()=> { + setTimeout(async () => { await sendOutboundMessage(connection, basicMessage) - },50) - return true; + }, 50) + return true } catch (error) { - console.log('Basic message - Send message error = ', error); - throw error; + console.log('Basic message - Send message error = ', error) + throw error } } - /** * @description Process basic message and update the record * @@ -74,22 +83,33 @@ class BasicMessageService { * @return {*} {Promise} * @memberof BasicMessageService */ - async save(inboundMessage: InboundMessage, connectionId: string): Promise { + async save( + inboundMessage: InboundMessage, + connectionId: string, + ): Promise { try { - const { message } = inboundMessage; + const { message } = inboundMessage const chatBody = { type: 'receive', message: JSON.parse(message).content, time: JSON.parse(message).sent_time, - }; + } const query = { - connectionId: connectionId + connectionId: connectionId, } - const chatThread: Array = await WalletStorageService.getWalletRecordFromQuery(RecordType.BasicMessage, JSON.stringify(query)); - const connection: Connection = await WalletStorageService.getWalletRecordFromQuery(RecordType.Connection, JSON.stringify(query)); + const chatThread: Array< + Object + > = await WalletStorageService.getWalletRecordFromQuery( + RecordType.BasicMessage, + JSON.stringify(query), + ) + const connection: Connection = await WalletStorageService.getWalletRecordFromQuery( + RecordType.Connection, + JSON.stringify(query), + ) const basicMessageTags: Object = { connectionId: connectionId, - lastUpdatedAt: new Date().toISOString() + lastUpdatedAt: new Date().toISOString(), } if (chatThread.length == 0) { @@ -97,24 +117,23 @@ class BasicMessageService { RecordType.BasicMessage, connectionId, JSON.stringify([chatBody]), - JSON.stringify(basicMessageTags) - ); - } - else { - chatThread.push(chatBody); + JSON.stringify(basicMessageTags), + ) + } else { + chatThread.push(chatBody) await WalletStorageService.updateWalletRecord( RecordType.BasicMessage, connectionId, JSON.stringify(chatThread), - JSON.stringify(basicMessageTags) - ); + JSON.stringify(basicMessageTags), + ) } - return connection; + return connection } catch (error) { - console.log('Basic message - Save message error = ', error); - throw (error); + console.log('Basic message - Save message error = ', error) + throw error } } } -export default new BasicMessageService(); \ No newline at end of file +export default new BasicMessageService() diff --git a/src/storage/index.ts b/src/storage/index.ts index 72860de..a878e1e 100644 --- a/src/storage/index.ts +++ b/src/storage/index.ts @@ -2,7 +2,7 @@ Copyright AyanWorks Technology Solutions Pvt. Ltd. All Rights Reserved. SPDX-License-Identifier: Apache-2.0 */ -import Realm from 'realm'; +import Realm from 'realm' const agentDB = new Realm({ schemaVersion: 1, @@ -21,56 +21,52 @@ const agentDB = new Realm({ verKey: 'string', masterSecretId: 'string', }, - }] -}); + }, + ], +}) const DBServices = { storeWallet(data) { agentDB.write(() => { - agentDB.create( - 'wallet', - data, - true, - ); - }); + agentDB.create('wallet', data, true) + }) }, getWallet() { - const query = agentDB.objects('wallet'); - const wallet = Array.from(query)[0]; - return wallet; + const query = agentDB.objects('wallet') + const wallet = Array.from(query)[0] + return wallet }, getServiceEndpoint() { - const query = agentDB.objects('wallet'); - const wallet: any = Array.from(query)[0]; + const query = agentDB.objects('wallet') + const wallet: any = Array.from(query)[0] return wallet.serviceEndpoint }, getLabel() { - const query = agentDB.objects('wallet'); - const wallet: any = Array.from(query)[0]; + const query = agentDB.objects('wallet') + const wallet: any = Array.from(query)[0] return wallet.label }, getMasterSecretId() { - const query = agentDB.objects('wallet'); - const wallet: any = Array.from(query)[0]; + const query = agentDB.objects('wallet') + const wallet: any = Array.from(query)[0] return wallet.masterSecretId }, getRoutingKeys() { - const query = agentDB.objects('wallet'); - const wallet: any = Array.from(query)[0]; + const query = agentDB.objects('wallet') + const wallet: any = Array.from(query)[0] return wallet.routingKey }, getVerKey() { - const query = agentDB.objects('wallet'); - const wallet: any = Array.from(query)[0]; + const query = agentDB.objects('wallet') + const wallet: any = Array.from(query)[0] return wallet.verKey - }, -}; +} -export default DBServices; \ No newline at end of file +export default DBServices diff --git a/src/utils/Helpers.ts b/src/utils/Helpers.ts index f0bb58c..2a2f706 100644 --- a/src/utils/Helpers.ts +++ b/src/utils/Helpers.ts @@ -3,20 +3,19 @@ SPDX-License-Identifier: Apache-2.0 */ -import { Connection } from '../protocols/connection/ConnectionInterface'; -import { createForwardMessage } from '../protocols/connection/ConnectionMessages'; -import { InboundMessage, OutboundMessage } from './Types'; -import { InvitationDetails } from '../protocols/connection/InvitationInterface'; -import { Message } from './Types'; -import { NativeModules, Platform } from 'react-native'; -import { OutboundAgentMessage } from '../network'; -import { WalletConfig, WalletCredentials } from '../wallet/WalletInterface'; -import base64url from 'base64url'; -import DatabaseServices from '../storage'; +import { Connection } from '../protocols/connection/ConnectionInterface' +import { createForwardMessage } from '../protocols/connection/ConnectionMessages' +import { InboundMessage, OutboundMessage } from './Types' +import { InvitationDetails } from '../protocols/connection/InvitationInterface' +import { Message } from './Types' +import { NativeModules, Platform } from 'react-native' +import { OutboundAgentMessage } from '../network' +import base64url from 'base64url' +import DatabaseServices from '../storage' -const Buffer = require('buffer').Buffer; +const Buffer = require('buffer').Buffer -const { ArnimaSdk } = NativeModules; +const { ArnimaSdk } = NativeModules export enum RecordType { Connection = 'Connection', @@ -30,38 +29,38 @@ export enum RecordType { } function timestamp(): Uint8Array { - let time = Date.now(); - const bytes = []; + let time = Date.now() + const bytes = [] for (let i = 0; i < 8; i++) { - const byte = time & 0xff; - bytes.push(byte); - time = (time - byte) / 256; // Javascript right shift (>>>) only works on 32 bit integers + const byte = time & 0xff + bytes.push(byte) + time = (time - byte) / 256 // Javascript right shift (>>>) only works on 32 bit integers } - return Uint8Array.from(bytes).reverse(); + return Uint8Array.from(bytes).reverse() } export async function verify(message: Message, field: string) { try { - const fieldKey = `${field}~sig`; - const { [fieldKey]: data, ...signedMessage } = message; + const fieldKey = `${field}~sig` + const { [fieldKey]: data, ...signedMessage } = message - const signerVerkey = data.signer; - const signedData = base64url.toBuffer(data.sig_data); - const signature = base64url.toBuffer(data.signature); + const signerVerkey = data.signer + const signedData = base64url.toBuffer(data.sig_data) + const signature = base64url.toBuffer(data.signature) - let valid; + let valid if (Platform.OS == 'android') { valid = await ArnimaSdk.cryptoVerify( signerVerkey, Array.from(signedData), Array.from(signature), - ); + ) } else { valid = await ArnimaSdk.cryptoVerify( signerVerkey, data.sig_data, JSON.stringify(Array.from(signature)), - ); + ) } // if (!valid) { @@ -72,12 +71,12 @@ export async function verify(message: Message, field: string) { '@id': message['@id'], ...signedMessage, [`${field}`]: JSON.parse(signedData.slice(8).toString('utf-8')), - }; + } - return originalMessage; + return originalMessage } catch (error) { - console.log('verify = ', error); - throw error; + console.log('verify = ', error) + throw error } } @@ -87,24 +86,24 @@ export async function sign( field: string, ) { try { - const { [field]: data, ...originalMessage } = message; + const { [field]: data, ...originalMessage } = message const dataBuffer = Buffer.concat([ timestamp(), Buffer.from(JSON.stringify(data), 'utf8'), - ]); - let signatureBuffer; + ]) + let signatureBuffer if (Platform.OS === 'ios') { signatureBuffer = await ArnimaSdk.cryptoSign( signerVerkey, JSON.stringify(data), - ); + ) } else { signatureBuffer = await ArnimaSdk.cryptoSign( signerVerkey, Array.from(dataBuffer), - ); + ) } const signedMessage = { @@ -118,122 +117,120 @@ export async function sign( sig_data: base64url.encode(dataBuffer), signer: signerVerkey, }, - }; + } - return signedMessage; + return signedMessage } catch (error) { - console.log('sign message = ', error); - throw error; + console.log('sign message = ', error) + throw error } } export async function unpackMessage(inboundMessage: InboundMessage) { try { - const buf = Buffer.from(JSON.stringify(inboundMessage)); - let unpackedBufferMessage; + const buf = Buffer.from(JSON.stringify(inboundMessage)) + let unpackedBufferMessage if (Platform.OS === 'ios') { unpackedBufferMessage = await ArnimaSdk.unpackMessage( JSON.stringify(inboundMessage), - ); + ) } else { - unpackedBufferMessage = await ArnimaSdk.unpackMessage(Array.from(buf)); + unpackedBufferMessage = await ArnimaSdk.unpackMessage(Array.from(buf)) } - const unpackedMessage = Buffer.from(unpackedBufferMessage); - return JSON.parse(unpackedMessage.toString('utf-8')); + const unpackedMessage = Buffer.from(unpackedBufferMessage) + return JSON.parse(unpackedMessage.toString('utf-8')) } catch (error) { - console.log('unpackMessage = ', error); - throw error; + console.log('unpackMessage = ', error) + throw error } } export async function packMessage(outboundMessage: OutboundMessage) { try { - const { routingKeys, recipientKeys, senderVk, payload } = outboundMessage; - const buf = Buffer.from(JSON.stringify(payload)); - let packedBufferMessage; + const { routingKeys, recipientKeys, senderVk, payload } = outboundMessage + const buf = Buffer.from(JSON.stringify(payload)) + let packedBufferMessage if (Platform.OS === 'ios') { packedBufferMessage = await ArnimaSdk.packMessage( JSON.stringify(payload), recipientKeys, senderVk, - ); + ) } else { packedBufferMessage = await ArnimaSdk.packMessage( Array.from(buf), recipientKeys, senderVk, - ); + ) } - const packedMessage = Buffer.from(packedBufferMessage); - const outboundPackedMessage = JSON.parse(packedMessage.toString('utf-8')); + const packedMessage = Buffer.from(packedBufferMessage) + const outboundPackedMessage = JSON.parse(packedMessage.toString('utf-8')) - let message = outboundPackedMessage; + let message = outboundPackedMessage if (routingKeys && routingKeys.length > 0) { for (const routingKey of routingKeys) { - const [recipientKey] = recipientKeys; - const forwardMessage = createForwardMessage(recipientKey, message); - const forwardMessageBuffer = Buffer.from( - JSON.stringify(forwardMessage), - ); - let forwardBufferMessage; + const [recipientKey] = recipientKeys + const forwardMessage = createForwardMessage(recipientKey, message) + const forwardMessageBuffer = Buffer.from(JSON.stringify(forwardMessage)) + let forwardBufferMessage if (Platform.OS === 'ios') { forwardBufferMessage = await ArnimaSdk.packMessage( JSON.stringify(forwardMessage), [routingKey], senderVk, - ); + ) } else { forwardBufferMessage = await ArnimaSdk.packMessage( Array.from(forwardMessageBuffer), [routingKey], senderVk, - ); + ) } - const forwardPackedMessage = Buffer.from(forwardBufferMessage); - message = JSON.parse(forwardPackedMessage.toString('utf-8')); + const forwardPackedMessage = Buffer.from(forwardBufferMessage) + message = JSON.parse(forwardPackedMessage.toString('utf-8')) } } - return message; + return message } catch (error) { - console.log('packMessage = ', error); - throw error; + console.log('packMessage = ', error) + throw error } } export function getServiceEndpoint() { // TODO : Need to find a way for realm db typing - const sdkDB: any = DatabaseServices.getWallet(); + const sdkDB: any = DatabaseServices.getWallet() return `${sdkDB.serviceEndpoint.split('/')[0] + '/' + sdkDB.serviceEndpoint.split('/')[1] + '/' + - sdkDB.serviceEndpoint.split('/')[2]}/`; + sdkDB.serviceEndpoint.split('/')[2]}/` } export function decodeInvitationFromUrl(invitationUrl: string) { - const [, encodedInvitation] = invitationUrl.split('c_i='); - return JSON.parse(Buffer.from(encodedInvitation, 'base64').toString()); + const [, encodedInvitation] = invitationUrl.split('c_i=') + return JSON.parse(Buffer.from(encodedInvitation, 'base64').toString()) } export function encodeInvitationToUrl(invitation: InvitationDetails): string { const encodedInvitation = Buffer.from(JSON.stringify(invitation)).toString( 'base64', - ); + ) // TODO : Need to find a way for realm db typing - const sdkDB: any = DatabaseServices.getWallet(); + const sdkDB: any = DatabaseServices.getWallet() return `${sdkDB.serviceEndpoint.split('/')[0] + '/' + sdkDB.serviceEndpoint.split('/')[1] + '/' + - sdkDB.serviceEndpoint.split('/')[2]}/ssi?c_i=${encodedInvitation}`; + sdkDB.serviceEndpoint.split('/')[2]}/ssi?c_i=${encodedInvitation}` } export function decodeBase64(base64Data: string) { - return JSON.parse(Buffer.from(base64Data, 'base64').toString()); + return JSON.parse(Buffer.from(base64Data, 'base64').toString()) } export function encodeBase64(data: string) { - return Buffer.from(JSON.stringify(data)).toString('base64'); + return Buffer.from(JSON.stringify(data)).toString('base64') } export async function createOutboundMessage( @@ -244,7 +241,7 @@ export async function createOutboundMessage( ) { if (connection) { if (invitation) { - const { recipientKeys, routingKeys, serviceEndpoint } = invitation; + const { recipientKeys, routingKeys, serviceEndpoint } = invitation return { connection, endpoint: serviceEndpoint, @@ -252,17 +249,17 @@ export async function createOutboundMessage( recipientKeys: recipientKeys, routingKeys: routingKeys || [], senderVk: connection.verkey, - }; + } } - const { theirDidDoc } = connection; + const { theirDidDoc } = connection if (!theirDidDoc) { throw new Error( `DidDoc for connection with verkey ${connection.verkey} not found!`, - ); + ) } - const { service } = theirDidDoc; + const { service } = theirDidDoc return { connection, endpoint: service[0].serviceEndpoint, @@ -270,23 +267,23 @@ export async function createOutboundMessage( recipientKeys: service[0].recipientKeys, routingKeys: service[0].routingKeys, senderVk: connection.verkey, - }; + } } else { - const wallet = await DatabaseServices.getWallet(); + const wallet = await DatabaseServices.getWallet() const [pairwiseDid, verkey]: string[] = await ArnimaSdk.createAndStoreMyDid( wallet.walletConfig, wallet.walletCredentials, JSON.stringify({}), false, - ); - const { recipientKeys, routingKeys, serviceEndpoint } = oobService; + ) + const { recipientKeys, routingKeys, serviceEndpoint } = oobService return { payload, recipientKeys, routingKeys, endpoint: serviceEndpoint, senderVk: verkey, - }; + } } } @@ -301,11 +298,11 @@ export async function sendOutboundMessage( message, invitation, oobService, - ); - const outboundPackMessage = await packMessage(outboundMessage); + ) + const outboundPackMessage = await packMessage(outboundMessage) await OutboundAgentMessage( outboundMessage.endpoint, 'POST', JSON.stringify(outboundPackMessage), - ); + ) } diff --git a/src/utils/MessageType.ts b/src/utils/MessageType.ts index 4a58385..82bc097 100644 --- a/src/utils/MessageType.ts +++ b/src/utils/MessageType.ts @@ -10,7 +10,7 @@ export enum MessageType { TrustPingMessage = 'did:sov:BzCbsNYhMrjHiqZDTUASHg;spec/trust_ping/1.0/ping', TrustPingResponseMessage = 'did:sov:BzCbsNYhMrjHiqZDTUASHg;spec/trust_ping/1.0/ping_response', - + ProposeCredential = 'did:sov:BzCbsNYhMrjHiqZDTUASHg;spec/issue-credential/1.0/propose-credential', OfferCredential = 'did:sov:BzCbsNYhMrjHiqZDTUASHg;spec/issue-credential/1.0/offer-credential', RequestCredential = 'did:sov:BzCbsNYhMrjHiqZDTUASHg;spec/issue-credential/1.0/request-credential', @@ -22,13 +22,13 @@ export enum MessageType { RequestPresentation = 'did:sov:BzCbsNYhMrjHiqZDTUASHg;spec/present-proof/1.0/request-presentation', Presentation = 'did:sov:BzCbsNYhMrjHiqZDTUASHg;spec/present-proof/1.0/presentation', PresentationAck = 'did:sov:BzCbsNYhMrjHiqZDTUASHg;spec/present-proof/1.0/ack', - presentationPreview = "did:sov:BzCbsNYhMrjHiqZDTUASHg;spec/present-proof/1.0/presentation-preview", - + presentationPreview = 'did:sov:BzCbsNYhMrjHiqZDTUASHg;spec/present-proof/1.0/presentation-preview', + BasicMessage = 'did:sov:BzCbsNYhMrjHiqZDTUASHg;spec/basicmessage/1.0/message', - + ForwardMessage = 'did:sov:BzCbsNYhMrjHiqZDTUASHg;spec/routing/1.0/forward', - + Ack = 'did:sov:BzCbsNYhMrjHiqZDTUASHg;spec/notification/1.0/ack', - problemReport = "did:sov:BzCbsNYhMrjHiqZDTUASHg;spec/notification/1.0/problem-report" + problemReport = 'did:sov:BzCbsNYhMrjHiqZDTUASHg;spec/notification/1.0/problem-report', } diff --git a/src/wallet/WalletService.ts b/src/wallet/WalletService.ts index 25d668d..7a08554 100644 --- a/src/wallet/WalletService.ts +++ b/src/wallet/WalletService.ts @@ -3,26 +3,40 @@ SPDX-License-Identifier: Apache-2.0 */ -import { DidJson, WalletConfig, WalletCredentials, WalletRecord } from "./WalletInterface"; -import { NativeModules } from "react-native"; -import { RecordType } from "../utils/Helpers"; -import DatabaseServices from '../storage'; -import WalletStorageService from "./WalletStorageService"; +import { + DidJson, + WalletConfig, + WalletCredentials, + WalletRecord, +} from './WalletInterface' +import { NativeModules } from 'react-native' +import { RecordType } from '../utils/Helpers' +import DatabaseServices from '../storage' +import WalletStorageService from './WalletStorageService' -const { ArnimaSdk } = NativeModules; +const { ArnimaSdk } = NativeModules class WalletService { - - async createWallet(config: WalletConfig, credentials: WalletCredentials, label: string): Promise { + async createWallet( + config: WalletConfig, + credentials: WalletCredentials, + label: string, + ): Promise { try { await ArnimaSdk.createWallet( JSON.stringify(config), - JSON.stringify(credentials) - ); - return await this.createWalletDidStore(config, credentials, { }, true, label); + JSON.stringify(credentials), + ) + return await this.createWalletDidStore( + config, + credentials, + {}, + true, + label, + ) } catch (error) { - console.log('WalletService - Create wallet error = ', error); - throw (error); + console.log('WalletService - Create wallet error = ', error) + throw error } } @@ -31,15 +45,14 @@ class WalletService { credentials: WalletCredentials, didJson: DidJson, createMasterSecret: boolean, - label: string + label: string, ): Promise { - const response: string[] = await ArnimaSdk.createAndStoreMyDid( JSON.stringify(config), JSON.stringify(credentials), JSON.stringify(didJson), - createMasterSecret - ); + createMasterSecret, + ) if (response.length > 0) { const [did, verkey, masterSecretId] = response @@ -48,19 +61,19 @@ class WalletService { walletConfig: JSON.stringify(config), walletCredentials: JSON.stringify(credentials), label: label, - serviceEndpoint: "", - routingKey: "", + serviceEndpoint: '', + routingKey: '', publicDid: did, verKey: verkey, masterSecretId: masterSecretId, - }); + }) const walletRecord: WalletRecord = { walletConfig: config, walletCredentials: credentials, label: label, - serviceEndpoint: "", - routingKey: "", + serviceEndpoint: '', + routingKey: '', publicDid: did, verKey: verkey, masterSecretId: masterSecretId, @@ -76,38 +89,36 @@ class WalletService { RecordType.MediatorAgent, '1', JSON.stringify(walletRecord), - JSON.stringify(walletRecordTags) - ); + JSON.stringify(walletRecordTags), + ) } - return response; + return response } async getWallet(): Promise { try { // TODO : Need to find a way for realm db typing - const response: any = await DatabaseServices.getWallet(); + const response: any = await DatabaseServices.getWallet() return response } catch (error) { - console.log('WalletService - Get wallet error = ', error); - throw error; + console.log('WalletService - Get wallet error = ', error) + throw error } - } async openWallet(): Promise { try { // TODO : Need to find a way for realm db typing - const sdkDB: any = DatabaseServices.getWallet(); + const sdkDB: any = DatabaseServices.getWallet() const response: boolean = await ArnimaSdk.openInitWallet( sdkDB.walletConfig, - sdkDB.walletCredentials - ); - return response; + sdkDB.walletCredentials, + ) + return response } catch (error) { - console.log('WalletService - Open wallet error = ', error); - throw error; + console.log('WalletService - Open wallet error = ', error) + throw error } - }; - + } } -export default new WalletService(); \ No newline at end of file +export default new WalletService() diff --git a/src/wallet/WalletStorageService.ts b/src/wallet/WalletStorageService.ts index 894e71f..b1e27d1 100644 --- a/src/wallet/WalletStorageService.ts +++ b/src/wallet/WalletStorageService.ts @@ -3,68 +3,95 @@ SPDX-License-Identifier: Apache-2.0 */ -import { NativeModules } from "react-native"; -import { Record, WalletStorageRecord } from "./WalletInterface"; +import { NativeModules } from 'react-native' +import { Record, WalletStorageRecord } from './WalletInterface' -const { ArnimaSdk } = NativeModules; +const { ArnimaSdk } = NativeModules class WalletStorageService { - async addWalletRecord(type: string, id: string, value: string, tags: string) { - try { - return await ArnimaSdk.addWalletRecord(type, id, value, tags); + return await ArnimaSdk.addWalletRecord(type, id, value, tags) } catch (error) { - console.log('WalletStorageService - ' + type + ' - Add wallet record = ', error); - throw error; + console.log( + 'WalletStorageService - ' + type + ' - Add wallet record = ', + error, + ) + throw error } } - async updateWalletRecord(type: string, id: string, value: string, tags: string) { + async updateWalletRecord( + type: string, + id: string, + value: string, + tags: string, + ) { try { - return await ArnimaSdk.updateWalletRecord(type, id, value, tags); + return await ArnimaSdk.updateWalletRecord(type, id, value, tags) } catch (error) { - console.log('WalletStorageService - ' + type + ' - Update wallet record = ', error); - throw error; + console.log( + 'WalletStorageService - ' + type + ' - Update wallet record = ', + error, + ) + throw error } } async deleteWalletRecord(type: string, id: string) { try { - return await ArnimaSdk.deleteWalletRecord(type, id); + return await ArnimaSdk.deleteWalletRecord(type, id) } catch (error) { - console.log('WalletStorageService - ' + type + ' - Delete wallet record = ', error); - throw error; + console.log( + 'WalletStorageService - ' + type + ' - Delete wallet record = ', + error, + ) + throw error } } async getWalletRecordFromQuery(type: string, query: string) { - try { - const queryResponse: string = await ArnimaSdk.getWalletRecordFromQuery(type, query); + const queryResponse: string = await ArnimaSdk.getWalletRecordFromQuery( + type, + query, + ) - const walletRecord: WalletStorageRecord = JSON.parse(queryResponse); + const walletRecord: WalletStorageRecord = JSON.parse(queryResponse) if (walletRecord.records !== null) { - return JSON.parse(walletRecord.records[0].value); + return JSON.parse(walletRecord.records[0].value) } else { // For basic message history, I am returning the empty object return [] } - } catch (error) { - console.log('WalletStorageService - ' + type + ' - Get wallet record from query = ', error); - throw error; + console.log( + 'WalletStorageService - ' + type + ' - Get wallet record from query = ', + error, + ) + throw error } } - async getWalletRecordsFromQuery(type: string, query: string): Promise> { + async getWalletRecordsFromQuery( + type: string, + query: string, + ): Promise> { try { - const queryResponse: string = await ArnimaSdk.getWalletRecordFromQuery(type, query); - const walletRecord: WalletStorageRecord = JSON.parse(queryResponse); - return walletRecord.records === null ? [] : walletRecord.records; + const queryResponse: string = await ArnimaSdk.getWalletRecordFromQuery( + type, + query, + ) + const walletRecord: WalletStorageRecord = JSON.parse(queryResponse) + return walletRecord.records === null ? [] : walletRecord.records } catch (error) { - console.log('WalletStorageService - ' + type + ' - Get wallet records from query = ', error); - throw error; + console.log( + 'WalletStorageService - ' + + type + + ' - Get wallet records from query = ', + error, + ) + throw error } } } -export default new WalletStorageService(); \ No newline at end of file +export default new WalletStorageService()