diff --git a/packages/examples/sdk-frontend-react/src/app/ChatUITest/ChatProfile.tsx b/packages/examples/sdk-frontend-react/src/app/ChatUITest/ChatProfile.tsx index e70b393ea..3c82c76f7 100644 --- a/packages/examples/sdk-frontend-react/src/app/ChatUITest/ChatProfile.tsx +++ b/packages/examples/sdk-frontend-react/src/app/ChatUITest/ChatProfile.tsx @@ -8,7 +8,7 @@ export const ChatProfileTest = () => { chatProfileLeftHelperComponent={
left component
} chatProfileRightHelperComponent={
right component
} chatId='monalisha.wallet' -// chatId='d9c2d6fa7132d49ea6d1b570f0ebd2bcc45c1ecac726eab993ad91c574fbe3c6' +// chatId='36baf37e441fdd94e23406c6c716fc4e91a93a9ee68e070cd5b054534dbe09a6' /> ) diff --git a/packages/restapi/CHANGELOG.md b/packages/restapi/CHANGELOG.md index f75386e99..f9557fc17 100644 --- a/packages/restapi/CHANGELOG.md +++ b/packages/restapi/CHANGELOG.md @@ -2,6 +2,172 @@ This file was generated using [@jscutlery/semver](https://github.com/jscutlery/semver). +## [0.0.1-alpha.82](https://github.com/push-protocol/push-sdk/compare/restapi-0.0.1-alpha.81...restapi-0.0.1-alpha.82) (2024-04-16) + + +### Bug Fixes + +* bug fixes ([fab3700](https://github.com/push-protocol/push-sdk/commit/fab370073224481b901351c00da43dc3bc99fa64)) +* fix fn definitions ([#1232](https://github.com/push-protocol/push-sdk/issues/1232)) ([7bbc443](https://github.com/push-protocol/push-sdk/commit/7bbc4434ec19c9969d0f1932c9cb08f74300a9b8)) +* fix tmp error ([bd70cda](https://github.com/push-protocol/push-sdk/commit/bd70cda0eb68a2329da743727c3b2a4b7f14589e)) +* Merge branch 'alpha' into alpha-deployment ([7e32f93](https://github.com/push-protocol/push-sdk/commit/7e32f93153b2ef338a1c18d4c1c6df7b9a1687cf)) +* renamed sender to account ([ce4af1a](https://github.com/push-protocol/push-sdk/commit/ce4af1a200e98de3c47055cc495f55a4a8e561cf)) + + + +## [0.0.1-alpha.81](https://github.com/push-protocol/push-sdk/compare/restapi-0.0.1-alpha.80...restapi-0.0.1-alpha.81) (2024-04-15) + + +### Bug Fixes + +* chat info changes ([6718648](https://github.com/push-protocol/push-sdk/commit/67186484a4dff605ef94df83b19bb2d4a220e546)) +* Merge branch 'alpha' into alpha-deployment ([97f8390](https://github.com/push-protocol/push-sdk/commit/97f839020e9b0313548753c364f01795e6bc7b3d)) + + + +## [0.0.1-alpha.80](https://github.com/push-protocol/push-sdk/compare/restapi-0.0.1-alpha.79...restapi-0.0.1-alpha.80) (2024-04-13) + + +### Bug Fixes + +* Merge branch 'alpha' into alpha-deployment ([ad37848](https://github.com/push-protocol/push-sdk/commit/ad3784890d97b09b7d6212cfcd6c868cb360cba2)) + + + +## [0.0.1-alpha.79](https://github.com/push-protocol/push-sdk/compare/restapi-0.0.1-alpha.78...restapi-0.0.1-alpha.79) (2024-04-12) + + +### Bug Fixes + +* added instanceids for push user and stream ([#1224](https://github.com/push-protocol/push-sdk/issues/1224)) ([34263c9](https://github.com/push-protocol/push-sdk/commit/34263c94ccfe674f915ce318a60cc21a77a0a5de)) +* Merge branch 'alpha' into alpha-deployment ([cb8d996](https://github.com/push-protocol/push-sdk/commit/cb8d996f868109a8e659a5654abfb265d2bb37ad)) + + + +## [0.0.1-alpha.78](https://github.com/push-protocol/push-sdk/compare/restapi-0.0.1-alpha.77...restapi-0.0.1-alpha.78) (2024-04-10) + + +### Bug Fixes + +* add decryptedPGPPrivateKey in options ([#1216](https://github.com/push-protocol/push-sdk/issues/1216)) ([ed9d3a7](https://github.com/push-protocol/push-sdk/commit/ed9d3a7e6ef3880fd897927e67d7db8e0a7b06c7)) +* fix testcases to take push node environment from .env rather tha… ([#1196](https://github.com/push-protocol/push-sdk/issues/1196)) ([7a4bd8d](https://github.com/push-protocol/push-sdk/commit/7a4bd8d7637fb17a714062a7b9ea055c889b0bf0)) +* Merge branch 'alpha' into alpha-deployment ([3d52b21](https://github.com/push-protocol/push-sdk/commit/3d52b21accc046b2133eaf15d13e0c945d793b1f)) +* tes cases and minor bugs ([#1212](https://github.com/push-protocol/push-sdk/issues/1212)) ([d30e095](https://github.com/push-protocol/push-sdk/commit/d30e095860ef20b8f8ef6a341d49f698227df998)) + + + +## [0.0.1-alpha.77](https://github.com/push-protocol/push-sdk/compare/restapi-0.0.1-alpha.76...restapi-0.0.1-alpha.77) (2024-04-02) + + + +## [0.0.1-alpha.75](https://github.com/push-protocol/push-sdk/compare/restapi-0.0.1-alpha.74...restapi-0.0.1-alpha.75) (2024-04-02) + + +### Bug Fixes + +* chat.info changes ([#1163](https://github.com/push-protocol/push-sdk/issues/1163)) ([b16b842](https://github.com/push-protocol/push-sdk/commit/b16b84289bc840d1a6a210726fe8350f0291ccf0)) +* error handling for chat ([#1110](https://github.com/push-protocol/push-sdk/issues/1110)) ([59f4c77](https://github.com/push-protocol/push-sdk/commit/59f4c7704c91653ac114baf75ea30cd0b839980f)) +* fix build ([#1176](https://github.com/push-protocol/push-sdk/issues/1176)) ([fefdf91](https://github.com/push-protocol/push-sdk/commit/fefdf912df6110cebbbaf8fbd47989ba727679b4)) +* fix channel notifications response ([#1166](https://github.com/push-protocol/push-sdk/issues/1166)) ([c01798a](https://github.com/push-protocol/push-sdk/commit/c01798af23f4f8cc2215fa9a529145d0c3bf349d)) +* fixed berachain issue ([6cd5dd8](https://github.com/push-protocol/push-sdk/commit/6cd5dd8ff77d7a916ce795b1238b381d20808786)) +* merge alpha ([4d1c5ef](https://github.com/push-protocol/push-sdk/commit/4d1c5ef2e0e6ce3382af6b811ffd6211ba15520d)) +* Merge branch 'main' into alpha ([53a795d](https://github.com/push-protocol/push-sdk/commit/53a795db5ec82d44597410dca670dfadd9199277)) +* **migrate goerli to sepolia:** migrate goerli to sepolia ([#1149](https://github.com/push-protocol/push-sdk/issues/1149)) ([490b104](https://github.com/push-protocol/push-sdk/commit/490b104902b9a509c6a8c68d5c5f33446e91e113)) +* pulled ([f22e9fb](https://github.com/push-protocol/push-sdk/commit/f22e9fb0bd7a1529d1f9ba79626ef37a32e76f31)) +* pulled main ([b7391b6](https://github.com/push-protocol/push-sdk/commit/b7391b6318b40117d61b86ea8163b116f757c94a)) + + + +## [0.0.1-alpha.75](https://github.com/push-protocol/push-sdk/compare/restapi-0.0.1-alpha.74...restapi-0.0.1-alpha.75) (2024-04-02) + + +### Bug Fixes + +* chat.info changes ([#1163](https://github.com/push-protocol/push-sdk/issues/1163)) ([b16b842](https://github.com/push-protocol/push-sdk/commit/b16b84289bc840d1a6a210726fe8350f0291ccf0)) +* error handling for chat ([#1110](https://github.com/push-protocol/push-sdk/issues/1110)) ([59f4c77](https://github.com/push-protocol/push-sdk/commit/59f4c7704c91653ac114baf75ea30cd0b839980f)) +* fix build ([#1176](https://github.com/push-protocol/push-sdk/issues/1176)) ([fefdf91](https://github.com/push-protocol/push-sdk/commit/fefdf912df6110cebbbaf8fbd47989ba727679b4)) +* fix channel notifications response ([#1166](https://github.com/push-protocol/push-sdk/issues/1166)) ([c01798a](https://github.com/push-protocol/push-sdk/commit/c01798af23f4f8cc2215fa9a529145d0c3bf349d)) +* fixed berachain issue ([6cd5dd8](https://github.com/push-protocol/push-sdk/commit/6cd5dd8ff77d7a916ce795b1238b381d20808786)) +* merge alpha ([4d1c5ef](https://github.com/push-protocol/push-sdk/commit/4d1c5ef2e0e6ce3382af6b811ffd6211ba15520d)) +* Merge branch 'main' into alpha ([53a795d](https://github.com/push-protocol/push-sdk/commit/53a795db5ec82d44597410dca670dfadd9199277)) +* **migrate goerli to sepolia:** migrate goerli to sepolia ([#1149](https://github.com/push-protocol/push-sdk/issues/1149)) ([490b104](https://github.com/push-protocol/push-sdk/commit/490b104902b9a509c6a8c68d5c5f33446e91e113)) +* pulled ([f22e9fb](https://github.com/push-protocol/push-sdk/commit/f22e9fb0bd7a1529d1f9ba79626ef37a32e76f31)) +* pulled main ([b7391b6](https://github.com/push-protocol/push-sdk/commit/b7391b6318b40117d61b86ea8163b116f757c94a)) + + + +## [0.0.1-alpha.75](https://github.com/push-protocol/push-sdk/compare/restapi-0.0.1-alpha.74...restapi-0.0.1-alpha.75) (2024-04-02) + + +### Bug Fixes + +* chat.info changes ([#1163](https://github.com/push-protocol/push-sdk/issues/1163)) ([b16b842](https://github.com/push-protocol/push-sdk/commit/b16b84289bc840d1a6a210726fe8350f0291ccf0)) +* error handling for chat ([#1110](https://github.com/push-protocol/push-sdk/issues/1110)) ([59f4c77](https://github.com/push-protocol/push-sdk/commit/59f4c7704c91653ac114baf75ea30cd0b839980f)) +* fix build ([#1176](https://github.com/push-protocol/push-sdk/issues/1176)) ([fefdf91](https://github.com/push-protocol/push-sdk/commit/fefdf912df6110cebbbaf8fbd47989ba727679b4)) +* fix channel notifications response ([#1166](https://github.com/push-protocol/push-sdk/issues/1166)) ([c01798a](https://github.com/push-protocol/push-sdk/commit/c01798af23f4f8cc2215fa9a529145d0c3bf349d)) +* fixed berachain issue ([6cd5dd8](https://github.com/push-protocol/push-sdk/commit/6cd5dd8ff77d7a916ce795b1238b381d20808786)) +* merge alpha ([4d1c5ef](https://github.com/push-protocol/push-sdk/commit/4d1c5ef2e0e6ce3382af6b811ffd6211ba15520d)) +* Merge branch 'main' into alpha ([53a795d](https://github.com/push-protocol/push-sdk/commit/53a795db5ec82d44597410dca670dfadd9199277)) +* **migrate goerli to sepolia:** migrate goerli to sepolia ([#1149](https://github.com/push-protocol/push-sdk/issues/1149)) ([490b104](https://github.com/push-protocol/push-sdk/commit/490b104902b9a509c6a8c68d5c5f33446e91e113)) +* pulled ([f22e9fb](https://github.com/push-protocol/push-sdk/commit/f22e9fb0bd7a1529d1f9ba79626ef37a32e76f31)) +* pulled main ([b7391b6](https://github.com/push-protocol/push-sdk/commit/b7391b6318b40117d61b86ea8163b116f757c94a)) + + + +## [0.0.1-alpha.75](https://github.com/push-protocol/push-sdk/compare/restapi-0.0.1-alpha.74...restapi-0.0.1-alpha.75) (2024-04-02) + + +### Bug Fixes + +* chat.info changes ([#1163](https://github.com/push-protocol/push-sdk/issues/1163)) ([b16b842](https://github.com/push-protocol/push-sdk/commit/b16b84289bc840d1a6a210726fe8350f0291ccf0)) +* error handling for chat ([#1110](https://github.com/push-protocol/push-sdk/issues/1110)) ([59f4c77](https://github.com/push-protocol/push-sdk/commit/59f4c7704c91653ac114baf75ea30cd0b839980f)) +* fix build ([#1176](https://github.com/push-protocol/push-sdk/issues/1176)) ([fefdf91](https://github.com/push-protocol/push-sdk/commit/fefdf912df6110cebbbaf8fbd47989ba727679b4)) +* fix channel notifications response ([#1166](https://github.com/push-protocol/push-sdk/issues/1166)) ([c01798a](https://github.com/push-protocol/push-sdk/commit/c01798af23f4f8cc2215fa9a529145d0c3bf349d)) +* fixed berachain issue ([6cd5dd8](https://github.com/push-protocol/push-sdk/commit/6cd5dd8ff77d7a916ce795b1238b381d20808786)) +* merge alpha ([4d1c5ef](https://github.com/push-protocol/push-sdk/commit/4d1c5ef2e0e6ce3382af6b811ffd6211ba15520d)) +* Merge branch 'main' into alpha ([53a795d](https://github.com/push-protocol/push-sdk/commit/53a795db5ec82d44597410dca670dfadd9199277)) +* **migrate goerli to sepolia:** migrate goerli to sepolia ([#1149](https://github.com/push-protocol/push-sdk/issues/1149)) ([490b104](https://github.com/push-protocol/push-sdk/commit/490b104902b9a509c6a8c68d5c5f33446e91e113)) +* pulled ([f22e9fb](https://github.com/push-protocol/push-sdk/commit/f22e9fb0bd7a1529d1f9ba79626ef37a32e76f31)) +* pulled main ([b7391b6](https://github.com/push-protocol/push-sdk/commit/b7391b6318b40117d61b86ea8163b116f757c94a)) + + + +## [0.0.1-alpha.75](https://github.com/push-protocol/push-sdk/compare/restapi-0.0.1-alpha.74...restapi-0.0.1-alpha.75) (2024-04-02) + + +### Bug Fixes + +* chat.info changes ([#1163](https://github.com/push-protocol/push-sdk/issues/1163)) ([b16b842](https://github.com/push-protocol/push-sdk/commit/b16b84289bc840d1a6a210726fe8350f0291ccf0)) +* error handling for chat ([#1110](https://github.com/push-protocol/push-sdk/issues/1110)) ([59f4c77](https://github.com/push-protocol/push-sdk/commit/59f4c7704c91653ac114baf75ea30cd0b839980f)) +* fix build ([#1176](https://github.com/push-protocol/push-sdk/issues/1176)) ([fefdf91](https://github.com/push-protocol/push-sdk/commit/fefdf912df6110cebbbaf8fbd47989ba727679b4)) +* fix channel notifications response ([#1166](https://github.com/push-protocol/push-sdk/issues/1166)) ([c01798a](https://github.com/push-protocol/push-sdk/commit/c01798af23f4f8cc2215fa9a529145d0c3bf349d)) +* fixed berachain issue ([6cd5dd8](https://github.com/push-protocol/push-sdk/commit/6cd5dd8ff77d7a916ce795b1238b381d20808786)) +* merge alpha ([4d1c5ef](https://github.com/push-protocol/push-sdk/commit/4d1c5ef2e0e6ce3382af6b811ffd6211ba15520d)) +* Merge branch 'main' into alpha ([53a795d](https://github.com/push-protocol/push-sdk/commit/53a795db5ec82d44597410dca670dfadd9199277)) +* **migrate goerli to sepolia:** migrate goerli to sepolia ([#1149](https://github.com/push-protocol/push-sdk/issues/1149)) ([490b104](https://github.com/push-protocol/push-sdk/commit/490b104902b9a509c6a8c68d5c5f33446e91e113)) +* pulled ([f22e9fb](https://github.com/push-protocol/push-sdk/commit/f22e9fb0bd7a1529d1f9ba79626ef37a32e76f31)) +* pulled main ([b7391b6](https://github.com/push-protocol/push-sdk/commit/b7391b6318b40117d61b86ea8163b116f757c94a)) + + + +## [0.0.1-alpha.75](https://github.com/push-protocol/push-sdk/compare/restapi-0.0.1-alpha.74...restapi-0.0.1-alpha.75) (2024-04-02) + + +### Bug Fixes + +* chat.info changes ([#1163](https://github.com/push-protocol/push-sdk/issues/1163)) ([b16b842](https://github.com/push-protocol/push-sdk/commit/b16b84289bc840d1a6a210726fe8350f0291ccf0)) +* error handling for chat ([#1110](https://github.com/push-protocol/push-sdk/issues/1110)) ([59f4c77](https://github.com/push-protocol/push-sdk/commit/59f4c7704c91653ac114baf75ea30cd0b839980f)) +* fix build ([#1176](https://github.com/push-protocol/push-sdk/issues/1176)) ([fefdf91](https://github.com/push-protocol/push-sdk/commit/fefdf912df6110cebbbaf8fbd47989ba727679b4)) +* fix channel notifications response ([#1166](https://github.com/push-protocol/push-sdk/issues/1166)) ([c01798a](https://github.com/push-protocol/push-sdk/commit/c01798af23f4f8cc2215fa9a529145d0c3bf349d)) +* fixed berachain issue ([6cd5dd8](https://github.com/push-protocol/push-sdk/commit/6cd5dd8ff77d7a916ce795b1238b381d20808786)) +* merge alpha ([4d1c5ef](https://github.com/push-protocol/push-sdk/commit/4d1c5ef2e0e6ce3382af6b811ffd6211ba15520d)) +* Merge branch 'main' into alpha ([53a795d](https://github.com/push-protocol/push-sdk/commit/53a795db5ec82d44597410dca670dfadd9199277)) +* **migrate goerli to sepolia:** migrate goerli to sepolia ([#1149](https://github.com/push-protocol/push-sdk/issues/1149)) ([490b104](https://github.com/push-protocol/push-sdk/commit/490b104902b9a509c6a8c68d5c5f33446e91e113)) +* pulled ([f22e9fb](https://github.com/push-protocol/push-sdk/commit/f22e9fb0bd7a1529d1f9ba79626ef37a32e76f31)) +* pulled main ([b7391b6](https://github.com/push-protocol/push-sdk/commit/b7391b6318b40117d61b86ea8163b116f757c94a)) + + + ## [1.7.2](https://github.com/ethereum-push-notification-service/push-sdk/compare/restapi-1.7.1...restapi-1.7.2) (2024-03-13) diff --git a/packages/restapi/package.json b/packages/restapi/package.json index 0209d6eaf..ca4b88618 100644 --- a/packages/restapi/package.json +++ b/packages/restapi/package.json @@ -1,6 +1,6 @@ { "name": "@pushprotocol/restapi", - "version": "0.0.1-alpha.74", + "version": "0.0.1-alpha.82", "type": "commonjs", "publishConfig": { "registry": "https://registry.npmjs.org/" @@ -43,4 +43,4 @@ "ts-node": "^10.9.1", "typescript": "^5.0.2" } -} \ No newline at end of file +} diff --git a/packages/restapi/src/lib/chat/approveRequest.ts b/packages/restapi/src/lib/chat/approveRequest.ts index 034b3acef..9a79b258d 100644 --- a/packages/restapi/src/lib/chat/approveRequest.ts +++ b/packages/restapi/src/lib/chat/approveRequest.ts @@ -1,10 +1,9 @@ -import { getAPIBaseUrls, isValidETHAddress } from '../helpers'; +import { convertToValidDID, getAPIBaseUrls, isValidPushCAIP } from '../helpers'; import Constants, { PACKAGE_BUILD } from '../constants'; import { EnvOptionsType, SignerType } from '../types'; import { getAccountAddress, getWallet, - getUserDID, getConnectedUserV2Core, PGPHelper, IPGPHelper, @@ -70,7 +69,8 @@ export const approveCore = async ( */ const wallet = getWallet({ account, signer }); const address = await getAccountAddress(wallet); - const isGroup = !isValidETHAddress(senderAddress); + + const isGroup = !isValidPushCAIP(senderAddress); const connectedUser = await getConnectedUserV2Core( wallet, @@ -79,12 +79,12 @@ export const approveCore = async ( pgpHelper ); const fromDID: string = isGroup - ? await getUserDID(address, env) - : await getUserDID(senderAddress, env); + ? await convertToValidDID(address, env) + : await convertToValidDID(senderAddress, env); const toDID: string = isGroup - ? await getUserDID(senderAddress, env) - : await getUserDID(address, env); + ? await convertToValidDID(senderAddress, env) + : await convertToValidDID(address, env); let encryptedSecret: string | null = null; /** diff --git a/packages/restapi/src/lib/chat/chat.ts b/packages/restapi/src/lib/chat/chat.ts index 4135452c5..ec68e6941 100644 --- a/packages/restapi/src/lib/chat/chat.ts +++ b/packages/restapi/src/lib/chat/chat.ts @@ -1,8 +1,8 @@ -import { getAPIBaseUrls, isValidETHAddress, walletToPCAIP10 } from '../helpers'; +import { convertToValidDID, getAPIBaseUrls, isValidPushCAIP } from '../helpers'; import Constants, { ENV } from '../constants'; import { IFeeds } from '../types'; import { axiosGet } from '../utils/axiosUtil'; -import { PGPHelper, addDeprecatedInfo, getInboxLists, getUserDID } from './helpers'; +import { PGPHelper, addDeprecatedInfo, getInboxLists } from './helpers'; import { handleError } from '../errors/validationError'; export const chat = async (options: { @@ -19,24 +19,27 @@ export const chat = async (options: { toDecrypt = false, recipient, } = options || {}; - const user = await getUserDID(account, env); - const recipientWallet = await getUserDID(recipient, env); - if (!isValidETHAddress(user)) throw new Error(`Invalid address ${user}`); + const user = await convertToValidDID(account, env); + const recipientWallet = await convertToValidDID(recipient, env); + if (!isValidPushCAIP(user)) throw new Error(`Invalid address ${user}`); const API_BASE_URL = getAPIBaseUrls(env); const apiEndpoint = `${API_BASE_URL}/v1/chat/users/${user}/chat/${recipientWallet}`; try { - const response = await axiosGet(apiEndpoint); + const response = await axiosGet(apiEndpoint); // If no chat between users, then returns {} const chat: IFeeds = response.data; if (Object.keys(chat).length !== 0) { const updatedChat = addDeprecatedInfo([chat]); - const [feed]: IFeeds[] = await getInboxLists({ - lists: updatedChat, - user, - toDecrypt, - pgpPrivateKey, - env, - },PGPHelper); + const [feed]: IFeeds[] = await getInboxLists( + { + lists: updatedChat, + user, + toDecrypt, + pgpPrivateKey, + env, + }, + PGPHelper + ); return feed; } else { return chat; diff --git a/packages/restapi/src/lib/chat/chats.ts b/packages/restapi/src/lib/chat/chats.ts index 79a55ec9b..395641eb0 100644 --- a/packages/restapi/src/lib/chat/chats.ts +++ b/packages/restapi/src/lib/chat/chats.ts @@ -1,7 +1,12 @@ -import { getAPIBaseUrls, isValidETHAddress } from '../helpers'; +import { convertToValidDID, getAPIBaseUrls, isValidPushCAIP } from '../helpers'; import Constants, { ENV } from '../constants'; import { IFeeds } from '../types'; -import { getInboxLists, getUserDID, addDeprecatedInfo, IPGPHelper, PGPHelper } from './helpers'; +import { + getInboxLists, + addDeprecatedInfo, + IPGPHelper, + PGPHelper, +} from './helpers'; import { axiosGet } from '../utils/axiosUtil'; import { handleError } from '../errors/validationError'; @@ -31,10 +36,13 @@ export type ChatsOptionsType = { */ export const chats = async (options: ChatsOptionsType): Promise => { - return await chatsCore(options,PGPHelper) -} + return await chatsCore(options, PGPHelper); +}; -export const chatsCore = async (options: ChatsOptionsType, pgpHelper: IPGPHelper): Promise => { +export const chatsCore = async ( + options: ChatsOptionsType, + pgpHelper: IPGPHelper +): Promise => { const { account, pgpPrivateKey, @@ -43,10 +51,10 @@ export const chatsCore = async (options: ChatsOptionsType, pgpHelper: IPGPHelper page = 1, limit = 10, } = options || {}; - if (!isValidETHAddress(account)) { + if (!isValidPushCAIP(account)) { throw new Error(`Invalid address!`); } - const user = await getUserDID(account, env); + const user = await convertToValidDID(account, env); const API_BASE_URL = getAPIBaseUrls(env); const apiEndpoint = `${API_BASE_URL}/v1/chat/users/${user}/chats?page=${page}&limit=${limit}`; const requestUrl = `${apiEndpoint}`; @@ -54,13 +62,16 @@ export const chatsCore = async (options: ChatsOptionsType, pgpHelper: IPGPHelper const response = await axiosGet(requestUrl); const chats: IFeeds[] = response.data.chats; const updatedChats = addDeprecatedInfo(chats); - const feeds: IFeeds[] = await getInboxLists({ - lists: updatedChats, - user: user, - toDecrypt, - pgpPrivateKey, - env, - },pgpHelper); + const feeds: IFeeds[] = await getInboxLists( + { + lists: updatedChats, + user: user, + toDecrypt, + pgpPrivateKey, + env, + }, + pgpHelper + ); return feeds; } catch (err) { throw handleError(err, chats.name); diff --git a/packages/restapi/src/lib/chat/conversationHash.ts b/packages/restapi/src/lib/chat/conversationHash.ts index ab4ddf6c9..54aa450d8 100644 --- a/packages/restapi/src/lib/chat/conversationHash.ts +++ b/packages/restapi/src/lib/chat/conversationHash.ts @@ -1,23 +1,25 @@ import Constants from '../constants'; import { handleError } from '../errors/validationError'; -import { isValidETHAddress } from '../helpers'; +import { convertToValidDID, isValidPushCAIP } from '../helpers'; import { ConversationHashOptionsType } from '../types'; -import { getConversationHashService, getUserDID } from './helpers'; +import { getConversationHashService } from './helpers'; /** * All chat messages are stored on IPFS. This function will return the latest message's CID (Content Identifier on IPFS). * Whenever a new message is sent or received, this CID will change. */ -export const conversationHash = async(options: ConversationHashOptionsType) => { +export const conversationHash = async ( + options: ConversationHashOptionsType +) => { const { conversationId, account, env = Constants.ENV.PROD } = options || {}; try { - if (!isValidETHAddress(account)) { + if (!isValidPushCAIP(account)) { throw new Error(`Invalid address!`); } - const updatedConversationId = await getUserDID(conversationId, env); - const accountDID = await getUserDID(account, env); + const updatedConversationId = await convertToValidDID(conversationId, env); + const accountDID = await convertToValidDID(account, env); const response = await getConversationHashService({ conversationId: updatedConversationId, account: accountDID, diff --git a/packages/restapi/src/lib/chat/createGroup.ts b/packages/restapi/src/lib/chat/createGroup.ts index 34775d2d0..c20c1862b 100644 --- a/packages/restapi/src/lib/chat/createGroup.ts +++ b/packages/restapi/src/lib/chat/createGroup.ts @@ -1,4 +1,4 @@ -import { getAPIBaseUrls } from '../helpers'; +import { convertToValidDID, getAPIBaseUrls } from '../helpers'; import Constants from '../constants'; import { EnvOptionsType, GroupDTO, SignerType, Rules } from '../types'; import { @@ -6,7 +6,6 @@ import { createGroupPayload, createGroupRequestValidator, getWallet, - getUserDID, IPGPHelper, PGPHelper, validateScheduleDates, @@ -88,10 +87,10 @@ export const createGroupCore = async ( ); const convertedMembersPromise = members.map(async (each) => { - return getUserDID(each, env); + return convertToValidDID(each, env); }); const convertedAdminsPromise = admins.map(async (each) => { - return getUserDID(each, env); + return convertToValidDID(each, env); }); const convertedMembers = await Promise.all(convertedMembersPromise); const convertedAdmins = await Promise.all(convertedAdminsPromise); @@ -153,6 +152,6 @@ export const createGroupCore = async ( const response = await axiosPost(apiEndpoint, body); return response.data; } catch (err) { - throw handleError(err, createGroup.name); + throw handleError(err, createGroup.name); } }; diff --git a/packages/restapi/src/lib/chat/createGroupV2.ts b/packages/restapi/src/lib/chat/createGroupV2.ts index a33b0233d..5063e90f6 100644 --- a/packages/restapi/src/lib/chat/createGroupV2.ts +++ b/packages/restapi/src/lib/chat/createGroupV2.ts @@ -1,10 +1,9 @@ import axios from 'axios'; -import { getAPIBaseUrls, isValidETHAddress } from '../helpers'; +import { convertToValidDID, getAPIBaseUrls, isValidPushCAIP } from '../helpers'; import Constants from '../constants'; import { EnvOptionsType, GroupInfoDTO, SignerType, Rules } from '../types'; import { getWallet, - getUserDID, IPGPHelper, PGPHelper, validateScheduleDates, @@ -73,10 +72,10 @@ export const createGroupCoreV2 = async ( pgpHelper ); const convertedMembersPromise = members.map(async (each) => { - return getUserDID(each, env); + return convertToValidDID(each, env); }); const convertedAdminsPromise = admins.map(async (each) => { - return getUserDID(each, env); + return convertToValidDID(each, env); }); const convertedMembers = await Promise.all(convertedMembersPromise); const convertedAdmins = await Promise.all(convertedAdminsPromise); @@ -199,13 +198,13 @@ const createGroupV2OptionsValidator = ( } for (let i = 0; i < members.length; i++) { - if (members[i] && !isValidETHAddress(members[i])) { + if (members[i] && !isValidPushCAIP(members[i])) { throw new Error(`Invalid member address!`); } } for (let i = 0; i < admins.length; i++) { - if (!isValidETHAddress(admins[i])) { + if (!isValidPushCAIP(admins[i])) { throw new Error(`Invalid admin address!`); } } diff --git a/packages/restapi/src/lib/chat/getChatInfo.ts b/packages/restapi/src/lib/chat/getChatInfo.ts index 907e39303..b7e0b77db 100644 --- a/packages/restapi/src/lib/chat/getChatInfo.ts +++ b/packages/restapi/src/lib/chat/getChatInfo.ts @@ -1,8 +1,7 @@ -import { getAPIBaseUrls } from '../helpers'; +import { convertToValidDID, getAPIBaseUrls } from '../helpers'; import Constants, { ENV } from '../constants'; import { axiosGet } from '../utils/axiosUtil'; import { handleError } from '../errors/validationError'; -import { getUserDID } from './helpers'; /** * Represents the response type for the chat status. @@ -14,15 +13,15 @@ export interface ChatInfoResponse { list: string; participants: string[]; chatId: string; - receipient: string; + recipient: string; } /** * Represents the input type for fetching chat status. */ export interface GetChatInfoType { - receipient: string; - sender: string; // Ethereum address or similar + recipient: string; + account: string; // Ethereum address or similar env?: ENV; } @@ -32,18 +31,18 @@ export interface GetChatInfoType { export const getChatInfo = async ( options: GetChatInfoType ): Promise => { - const { receipient, sender, env = Constants.ENV.PROD } = options; + const { recipient, account, env = Constants.ENV.PROD } = options; try { - if (!receipient || !sender) { - throw new Error('receipient and sender cannot be null or empty'); + if (!recipient || !account) { + throw new Error('receipient and account cannot be null or empty'); } const API_BASE_URL = getAPIBaseUrls(env); - const requestUrl = `${API_BASE_URL}/v1/chat/${await getUserDID( - receipient, + const requestUrl = `${API_BASE_URL}/v1/chat/${await convertToValidDID( + recipient, env - )}/address/${await getUserDID(sender, env)}`; + )}/address/${await convertToValidDID(account, env)}`; const response = await axiosGet(requestUrl); return response.data; } catch (err) { diff --git a/packages/restapi/src/lib/chat/getGroupAccess.ts b/packages/restapi/src/lib/chat/getGroupAccess.ts index 952a70e02..978f71008 100644 --- a/packages/restapi/src/lib/chat/getGroupAccess.ts +++ b/packages/restapi/src/lib/chat/getGroupAccess.ts @@ -1,7 +1,6 @@ -import { getAPIBaseUrls } from '../helpers'; +import { convertToValidDID, getAPIBaseUrls } from '../helpers'; import Constants, { ENV } from '../constants'; import { GroupAccess } from '../types'; -import { getUserDID } from './helpers'; import { axiosGet } from '../utils/axiosUtil'; import { handleError } from '../errors/validationError'; @@ -29,7 +28,7 @@ export const getGroupAccess = async ( throw new Error(`did cannot be null or empty`); } - const user = await getUserDID(did, env); + const user = await convertToValidDID(did, env); const API_BASE_URL = getAPIBaseUrls(env); const requestUrl = `${API_BASE_URL}/v1/chat/groups/${chatId}/access/${user}`; diff --git a/packages/restapi/src/lib/chat/getGroupMemberStatus.ts b/packages/restapi/src/lib/chat/getGroupMemberStatus.ts index 2caca5040..ea018b4c1 100644 --- a/packages/restapi/src/lib/chat/getGroupMemberStatus.ts +++ b/packages/restapi/src/lib/chat/getGroupMemberStatus.ts @@ -1,7 +1,6 @@ -import { getAPIBaseUrls } from '../helpers'; +import { convertToValidDID, getAPIBaseUrls } from '../helpers'; import Constants, { ENV } from '../constants'; -import { GroupMemberStatus } from '../types'; -import { getUserDID } from './helpers'; +import { GroupMemberStatus } from '../types'; import { axiosGet } from '../utils/axiosUtil'; import { handleError } from '../errors/validationError'; @@ -29,7 +28,7 @@ export const getGroupMemberStatus = async ( throw new Error(`did cannot be null or empty`); } - const user = await getUserDID(did, env); + const user = await convertToValidDID(did, env); const API_BASE_URL = getAPIBaseUrls(env); const requestUrl = `${API_BASE_URL}/v1/chat/groups/${chatId}/members/${user}/status`; @@ -37,6 +36,6 @@ export const getGroupMemberStatus = async ( const response = await axiosGet(requestUrl); return response.data; } catch (err) { - throw handleError(err, getGroupMemberStatus.name); + throw handleError(err, getGroupMemberStatus.name); } }; diff --git a/packages/restapi/src/lib/chat/helpers/crypto.ts b/packages/restapi/src/lib/chat/helpers/crypto.ts index 590b4d1fb..7d07e9693 100644 --- a/packages/restapi/src/lib/chat/helpers/crypto.ts +++ b/packages/restapi/src/lib/chat/helpers/crypto.ts @@ -16,7 +16,7 @@ import { Signer, decryptPGPKey, decryptWithWalletRPCMethod, - isValidETHAddress, + isValidPushCAIP, } from '../../helpers'; import { get as getUser } from '../../user'; import { createUserService } from './service'; @@ -247,7 +247,7 @@ export const getEncryptedRequestCore = async ( env, }); if (!receiverCreatedUser?.publicKey) { - if (!isValidETHAddress(receiverAddress)) { + if (!isValidPushCAIP(receiverAddress)) { throw new Error(`Invalid receiver address!`); } await createUserService({ diff --git a/packages/restapi/src/lib/chat/helpers/inbox.ts b/packages/restapi/src/lib/chat/helpers/inbox.ts index 6a3412600..c6e4322d0 100644 --- a/packages/restapi/src/lib/chat/helpers/inbox.ts +++ b/packages/restapi/src/lib/chat/helpers/inbox.ts @@ -1,6 +1,6 @@ import * as PGP from './pgp'; import Constants, { ENV } from '../../constants'; -import { isValidCAIP10NFTAddress, pCAIP10ToWallet } from '../../helpers'; +import { isValidNFTCAIP, pCAIP10ToWallet } from '../../helpers'; import { IFeeds, IMessageIPFS, IUser, SpaceIFeeds } from '../../types'; import { get as getUser } from '../../user'; import { getCID } from '../ipfs'; @@ -212,7 +212,7 @@ export const addDeprecatedInfo = (() => { const latestDIDs: { [key: string]: string } = {}; return (chats: IFeeds[]): IFeeds[] => { chats.forEach((chat) => { - if (isValidCAIP10NFTAddress(chat.did)) { + if (isValidNFTCAIP(chat.did)) { const didWithoutTimestamp = chat.did.split(':').slice(0, 5).join(':'); const timestamp = chat.did.split(':')[5]; if ( @@ -224,7 +224,7 @@ export const addDeprecatedInfo = (() => { } }); chats.forEach((chat) => { - if (isValidCAIP10NFTAddress(chat.did)) { + if (isValidNFTCAIP(chat.did)) { const didWithoutTimestamp = chat.did.split(':').slice(0, 5).join(':'); if (latestDIDs[didWithoutTimestamp] !== chat.did) { chat['deprecated'] = true; @@ -242,7 +242,7 @@ export const addDeprecatedInfoToMessages = (() => { const latestDIDs: { [key: string]: string } = {}; return (chats: IMessageIPFS[]): IMessageIPFS[] => { chats.forEach((chat) => { - if (isValidCAIP10NFTAddress(chat.fromDID)) { + if (isValidNFTCAIP(chat.fromDID)) { const didWithoutTimestamp = chat.fromDID .split(':') .slice(0, 5) @@ -257,7 +257,7 @@ export const addDeprecatedInfoToMessages = (() => { } }); chats.forEach((chat) => { - if (isValidCAIP10NFTAddress(chat.fromDID)) { + if (isValidNFTCAIP(chat.fromDID)) { const didWithoutTimestamp = chat.fromDID .split(':') .slice(0, 5) diff --git a/packages/restapi/src/lib/chat/helpers/payloadHelper.ts b/packages/restapi/src/lib/chat/helpers/payloadHelper.ts index 5455ff458..6ab762e1e 100644 --- a/packages/restapi/src/lib/chat/helpers/payloadHelper.ts +++ b/packages/restapi/src/lib/chat/helpers/payloadHelper.ts @@ -1,4 +1,4 @@ -import { isValidETHAddress, walletToPCAIP10 } from '../../helpers'; +import { isValidPushCAIP, walletToPCAIP10 } from '../../helpers'; import { getEncryptedRequestCore } from './crypto'; import { IConnectedUser, @@ -110,7 +110,7 @@ export const sendMessagePayloadCore = async ( env: ENV, pgpHelper: IPGPHelper ): Promise => { - const isGroup = !isValidETHAddress(receiverAddress); + const isGroup = !isValidPushCAIP(receiverAddress); let secretKey: string; if (isGroup && group?.encryptedSecret && group.sessionKey) { @@ -374,7 +374,9 @@ export const spaceDtoToSpaceInfoDto = (spaceDto: SpaceDTO): SpaceInfoDTO => { }; }; -export const mapSpaceListTypeToChatListType = (type: SpaceListType): ChatListType => { +export const mapSpaceListTypeToChatListType = ( + type: SpaceListType +): ChatListType => { switch (type) { case SpaceListType.SPACES: return ChatListType.CHATS; @@ -383,7 +385,7 @@ export const mapSpaceListTypeToChatListType = (type: SpaceListType): ChatListTyp default: throw new Error(`Unsupported SpaceListType: ${type}`); } -} +}; export const convertSpaceRulesToRules = (spaceRules: SpaceRules): Rules => { return { diff --git a/packages/restapi/src/lib/chat/helpers/service.ts b/packages/restapi/src/lib/chat/helpers/service.ts index 172be01e0..682b20a34 100644 --- a/packages/restapi/src/lib/chat/helpers/service.ts +++ b/packages/restapi/src/lib/chat/helpers/service.ts @@ -3,7 +3,7 @@ import { generateHash, getAPIBaseUrls, getQueryParams, - isValidCAIP10NFTAddress, + isValidNFTCAIP, verifyProfileKeys, walletToPCAIP10, } from '../../helpers'; @@ -22,7 +22,7 @@ type CreateUserOptionsType = { publicKey?: string; encryptedPrivateKey?: string; env?: ENV; - origin? : string | null; + origin?: string | null; }; export const createUserService = async (options: CreateUserOptionsType) => { @@ -39,7 +39,7 @@ export const createUserService = async (options: CreateUserOptionsType) => { const requestUrl = `${API_BASE_URL}/v2/users/`; - if (isValidCAIP10NFTAddress(user)) { + if (isValidNFTCAIP(user)) { const epoch = Math.floor(Date.now() / 1000); if (user.split(':').length !== 6) { user = `${user}:${epoch}`; @@ -49,7 +49,7 @@ export const createUserService = async (options: CreateUserOptionsType) => { caip10: walletToPCAIP10(user), did: walletToPCAIP10(user), publicKey, - encryptedPrivateKey + encryptedPrivateKey, }; const hash = generateHash(data); @@ -125,7 +125,7 @@ export const authUpdateUserService = async (options: CreateUserOptionsType) => { export const getConversationHashService = async ( options: ConversationHashOptionsType -): Promise<{ threadHash: string, intent: boolean }> => { +): Promise<{ threadHash: string; intent: boolean }> => { const { conversationId, account, env = Constants.ENV.PROD } = options || {}; const API_BASE_URL = getAPIBaseUrls(env); diff --git a/packages/restapi/src/lib/chat/helpers/user.ts b/packages/restapi/src/lib/chat/helpers/user.ts index 63e6aaa3e..b9e672d15 100644 --- a/packages/restapi/src/lib/chat/helpers/user.ts +++ b/packages/restapi/src/lib/chat/helpers/user.ts @@ -1,79 +1,8 @@ import Constants, { ENV } from '../../constants'; -import { get, create, createUserCore } from '../../user'; -import { IConnectedUser, IUser, SignerType, walletType } from '../../types'; +import { get, createUserCore } from '../../user'; +import { IConnectedUser, SignerType, walletType } from '../../types'; import { getAccountAddress } from './wallet'; import { IPGPHelper, PGPHelper, getDecryptedPrivateKey } from '.'; -import { - isValidCAIP10NFTAddress, - isValidETHAddress, - walletToPCAIP10, -} from '../../helpers'; - -export const createUserIfNecessary = async ( - wallet: walletType, - env: ENV -): Promise => { - const address = await getAccountAddress(wallet); - const connectedUser = await get({ account: address, env }); - if (!connectedUser?.encryptedPrivateKey) { - const createUserProps: { - account?: string; - signer?: SignerType; - env?: ENV; - } = {}; - if (wallet.account) { - createUserProps.account = wallet.account; - } - if (wallet.signer) { - createUserProps.signer = wallet.signer; - } - createUserProps.env = env; - const createdUser: IUser = await create(createUserProps); - return createdUser; - } else { - return connectedUser; - } -}; - -export const getConnectedUser = async ( - wallet: walletType, - privateKey: string | null, - env: ENV -): Promise => { - const address = await getAccountAddress(wallet); - const user = await get({ account: address, env: env || Constants.ENV.PROD }); - if (user?.encryptedPrivateKey) { - if (privateKey) { - return { ...user, privateKey }; - } else { - throw new Error(`Decrypted pgp private key required as input`); - } - } else { - const createUserProps: { - account?: string; - signer?: SignerType; - env?: ENV; - } = {}; - if (wallet.account) { - createUserProps.account = wallet.account; - } - if (user && user.did) { - createUserProps.account = user.did; - } - if (wallet.signer) { - createUserProps.signer = wallet.signer; - } - createUserProps.env = env; - const newUser = await create(createUserProps); - const decryptedPrivateKey = await getDecryptedPrivateKey( - wallet, - newUser, - address, - env - ); - return { ...newUser, privateKey: decryptedPrivateKey }; - } -}; export const getConnectedUserV2 = async ( wallet: walletType, @@ -132,18 +61,3 @@ export const getConnectedUserV2Core = async ( return { ...newUser, privateKey: decryptedPrivateKey }; } }; - -export const getUserDID = async ( - address: string, - env: ENV -): Promise => { - if (isValidCAIP10NFTAddress(address)) { - if (address.split(':').length === 6) return address; - const user = await get({ account: address, env: env }); - if (user && user.did) return user.did; - const epoch = Math.floor(Date.now() / 1000); - address = `${address}:${epoch}`; - } - if (isValidETHAddress(address)) return walletToPCAIP10(address); - return address; -}; diff --git a/packages/restapi/src/lib/chat/helpers/validator.ts b/packages/restapi/src/lib/chat/helpers/validator.ts index 78e4053eb..18c8df3a0 100644 --- a/packages/restapi/src/lib/chat/helpers/validator.ts +++ b/packages/restapi/src/lib/chat/helpers/validator.ts @@ -1,4 +1,4 @@ -import { isValidETHAddress, isValidNFTCAIP10Address } from '../../helpers'; +import { isValidPushCAIP, isValidFullCAIP10 } from '../../helpers'; import { GroupMemberUpdateOptions } from '../updateGroupMembers'; export const createGroupRequestValidator = ( @@ -28,7 +28,7 @@ export const createGroupRequestValidator = ( } for (let i = 0; i < members.length; i++) { - if (members[i] && !isValidETHAddress(members[i])) { + if (members[i] && !isValidPushCAIP(members[i])) { throw new Error(`Invalid member address!`); } } @@ -38,7 +38,7 @@ export const createGroupRequestValidator = ( } for (let i = 0; i < admins.length; i++) { - if (!isValidETHAddress(admins[i])) { + if (!isValidPushCAIP(admins[i])) { throw new Error(`Invalid admin address!`); } } @@ -46,7 +46,7 @@ export const createGroupRequestValidator = ( if ( contractAddressNFT != null && contractAddressNFT?.length > 0 && - !isValidNFTCAIP10Address(contractAddressNFT) + !isValidFullCAIP10(contractAddressNFT) ) { throw new Error(`Invalid contractAddressNFT address!`); } @@ -58,7 +58,7 @@ export const createGroupRequestValidator = ( if ( contractAddressERC20 != null && contractAddressERC20?.length > 0 && - !isValidNFTCAIP10Address(contractAddressERC20) + !isValidFullCAIP10(contractAddressERC20) ) { throw new Error(`Invalid contractAddressERC20 address!`); } @@ -95,7 +95,7 @@ export const createSpaceRequestValidator = ( } for (let i = 0; i < members.length; i++) { - if (members[i] && !isValidETHAddress(members[i])) { + if (members[i] && !isValidPushCAIP(members[i])) { throw new Error(`Invalid member address!`); } } @@ -105,7 +105,7 @@ export const createSpaceRequestValidator = ( } for (let i = 0; i < admins.length; i++) { - if (!isValidETHAddress(admins[i])) { + if (!isValidPushCAIP(admins[i])) { throw new Error(`Invalid admin address!`); } } @@ -113,7 +113,7 @@ export const createSpaceRequestValidator = ( if ( contractAddressNFT != null && contractAddressNFT?.length > 0 && - !isValidNFTCAIP10Address(contractAddressNFT) + !isValidFullCAIP10(contractAddressNFT) ) { throw new Error(`Invalid contractAddressNFT address!`); } @@ -125,7 +125,7 @@ export const createSpaceRequestValidator = ( if ( contractAddressERC20 != null && contractAddressERC20?.length > 0 && - !isValidNFTCAIP10Address(contractAddressERC20) + !isValidFullCAIP10(contractAddressERC20) ) { throw new Error(`Invalid contractAddressERC20 address!`); } @@ -191,7 +191,7 @@ export const updateGroupRequestValidator = ( if (members != null && members.length > 0) { for (let i = 0; i < members.length; i++) { - if (!isValidETHAddress(members[i])) { + if (!isValidPushCAIP(members[i])) { throw new Error(`Invalid member address in members list!`); } } @@ -199,13 +199,13 @@ export const updateGroupRequestValidator = ( if (admins != null && admins.length > 0) { for (let i = 0; i < admins.length; i++) { - if (!isValidETHAddress(admins[i])) { + if (!isValidPushCAIP(admins[i])) { throw new Error(`Invalid member address in admins list!`); } } } - if (address != null && !isValidETHAddress(address)) { + if (address != null && !isValidPushCAIP(address)) { throw new Error(`Invalid address field!`); } }; @@ -232,9 +232,9 @@ export const validateGroupMemberUpdateOptions = ( throw new Error(`${role} array cannot have more than 1000 addresses.`); } - // Assuming you have a function `isValidETHAddress` to validate Ethereum addresses + // Assuming you have a function `isValidPushCAIP` to validate Ethereum addresses upsert[role].forEach((address) => { - if (!isValidETHAddress(address)) { + if (!isValidPushCAIP(address)) { throw new Error(`Invalid address found in ${role} list.`); } }); @@ -245,7 +245,7 @@ export const validateGroupMemberUpdateOptions = ( throw new Error('Remove array cannot have more than 1000 addresses.'); } remove.forEach((address) => { - if (!isValidETHAddress(address)) { + if (!isValidPushCAIP(address)) { throw new Error('Invalid address found in remove list.'); } }); diff --git a/packages/restapi/src/lib/chat/rejectRequest.ts b/packages/restapi/src/lib/chat/rejectRequest.ts index 7b5900b5d..17ee20311 100644 --- a/packages/restapi/src/lib/chat/rejectRequest.ts +++ b/packages/restapi/src/lib/chat/rejectRequest.ts @@ -1,4 +1,4 @@ -import { getAPIBaseUrls, isValidETHAddress } from '../helpers'; +import { convertToValidDID, getAPIBaseUrls, isValidPushCAIP } from '../helpers'; import Constants from '../constants'; import { EnvOptionsType, SignerType } from '../types'; import { @@ -6,7 +6,6 @@ import { getConnectedUserV2, getAccountAddress, getWallet, - getUserDID, IRejectRequestPayload, rejectRequestPayload, } from './helpers'; @@ -50,17 +49,17 @@ export const reject = async ( const apiEndpoint = `${API_BASE_URL}/v1/chat/request/reject`; let isGroup = true; - if (isValidETHAddress(senderAddress)) { + if (isValidPushCAIP(senderAddress)) { isGroup = false; } const connectedUser = await getConnectedUserV2(wallet, pgpPrivateKey, env); - let fromDID = await getUserDID(senderAddress, env); - let toDID = await getUserDID(address, env); + let fromDID = await convertToValidDID(senderAddress, env); + let toDID = await convertToValidDID(address, env); if (isGroup) { - fromDID = await getUserDID(address, env); - toDID = await getUserDID(senderAddress, env); + fromDID = await convertToValidDID(address, env); + toDID = await convertToValidDID(senderAddress, env); } const bodyToBeHashed = { diff --git a/packages/restapi/src/lib/chat/requests.ts b/packages/restapi/src/lib/chat/requests.ts index 43cc694e0..9c4a8e07c 100644 --- a/packages/restapi/src/lib/chat/requests.ts +++ b/packages/restapi/src/lib/chat/requests.ts @@ -1,8 +1,13 @@ -import { getAPIBaseUrls, isValidETHAddress } from '../helpers'; +import { convertToValidDID, getAPIBaseUrls, isValidPushCAIP } from '../helpers'; import Constants, { ENV } from '../constants'; import { IFeeds } from '../types'; import { axiosGet } from '../utils/axiosUtil'; -import { IPGPHelper, PGPHelper, addDeprecatedInfo, getInboxLists, getUserDID } from './helpers'; +import { + IPGPHelper, + PGPHelper, + addDeprecatedInfo, + getInboxLists, +} from './helpers'; import { handleError } from '../errors/validationError'; export type RequestOptionsType = { @@ -30,15 +35,15 @@ export type RequestOptionsType = { * The first time an address wants to send a message to another peer, the address sends an intent request. This first message shall not land in this peer Inbox but in its Request box. * This function will return all the chats that landed on the address' Request box. The user can then approve the request or ignore it for now. */ -export const requests = async ( +export const requests = async ( options: RequestOptionsType ): Promise => { - return await requestsCore(options, PGPHelper) + return await requestsCore(options, PGPHelper); }; -export const requestsCore = async ( +export const requestsCore = async ( options: RequestOptionsType, - pgpHelper:IPGPHelper, + pgpHelper: IPGPHelper ): Promise => { const { account, @@ -48,26 +53,29 @@ export const requestsCore = async ( page = 1, limit = 10, } = options || {}; - const user = await getUserDID(account, env); + const user = await convertToValidDID(account, env); const API_BASE_URL = getAPIBaseUrls(env); const apiEndpoint = `${API_BASE_URL}/v1/chat/users/${user}/requests?page=${page}&limit=${limit}`; try { - if (!isValidETHAddress(user)) { + if (!isValidPushCAIP(user)) { throw new Error(`Invalid address!`); } const response = await axiosGet(apiEndpoint); const requests: IFeeds[] = response.data.requests; const updatedRequests = addDeprecatedInfo(requests); - const Feeds: IFeeds[] = await getInboxLists({ - lists: updatedRequests, - user, - toDecrypt, - pgpPrivateKey, - env, - },pgpHelper); + const Feeds: IFeeds[] = await getInboxLists( + { + lists: updatedRequests, + user, + toDecrypt, + pgpPrivateKey, + env, + }, + pgpHelper + ); return Feeds; } catch (err) { - throw handleError(err, requests.name); + throw handleError(err, requests.name); } -}; \ No newline at end of file +}; diff --git a/packages/restapi/src/lib/chat/send.ts b/packages/restapi/src/lib/chat/send.ts index fac436780..741e1e423 100644 --- a/packages/restapi/src/lib/chat/send.ts +++ b/packages/restapi/src/lib/chat/send.ts @@ -1,4 +1,4 @@ -import { getAPIBaseUrls, isValidETHAddress } from '../helpers'; +import { convertToValidDID, getAPIBaseUrls, isValidPushCAIP } from '../helpers'; import Constants, { MessageType, ENV } from '../constants'; import { ChatSendOptionsType, MessageWithCID, SignerType } from '../types'; import { @@ -6,7 +6,6 @@ import { PGPHelper, getAccountAddress, getConnectedUserV2Core, - getUserDID, getWallet, } from './helpers'; import { conversationHash } from './conversationHash'; @@ -51,9 +50,9 @@ export const sendCore = async ( env, pgpHelper ); - const receiver = await getUserDID(to, env); + const receiver = await convertToValidDID(to, env); const API_BASE_URL = getAPIBaseUrls(env); - const isGroup = isValidETHAddress(to) ? false : true; + const isGroup = isValidPushCAIP(to) ? false : true; const group = isGroup ? await getGroupInfo({ @@ -133,7 +132,7 @@ const validateOptions = async (options: ComputedOptionsType) => { const wallet = getWallet({ account, signer }); const address = await getAccountAddress(wallet); - if (!isValidETHAddress(address)) { + if (!isValidPushCAIP(address)) { throw new Error( `Invalid sender. Please ensure that either 'account' or 'signer' is properly defined.` ); diff --git a/packages/restapi/src/lib/chat/updateGroup.ts b/packages/restapi/src/lib/chat/updateGroup.ts index e825656b1..12730f4d6 100644 --- a/packages/restapi/src/lib/chat/updateGroup.ts +++ b/packages/restapi/src/lib/chat/updateGroup.ts @@ -1,4 +1,4 @@ -import { getAPIBaseUrls } from '../helpers'; +import { convertToValidDID, getAPIBaseUrls } from '../helpers'; import Constants from '../constants'; import { ChatStatus, @@ -15,7 +15,6 @@ import { PGPHelper, getConnectedUserV2Core, getAccountAddress, - getUserDID, updateGroupRequestValidator, } from './helpers'; import * as CryptoJS from 'crypto-js'; @@ -97,10 +96,10 @@ export const updateGroupCore = async ( pgpHelper ); const convertedMembersPromise = members.map(async (each) => { - return getUserDID(each, env); + return convertToValidDID(each, env); }); const convertedAdminsPromise = admins.map(async (each) => { - return getUserDID(each, env); + return convertToValidDID(each, env); }); const convertedMembers = await Promise.all(convertedMembersPromise); const convertedAdmins = await Promise.all(convertedAdminsPromise); diff --git a/packages/restapi/src/lib/chat/updateGroupMembers.ts b/packages/restapi/src/lib/chat/updateGroupMembers.ts index b315ed1de..6338f6896 100644 --- a/packages/restapi/src/lib/chat/updateGroupMembers.ts +++ b/packages/restapi/src/lib/chat/updateGroupMembers.ts @@ -1,11 +1,10 @@ import axios from 'axios'; -import { getAPIBaseUrls } from '../helpers'; +import { convertToValidDID, getAPIBaseUrls } from '../helpers'; import Constants, { PACKAGE_BUILD } from '../constants'; import { getWallet, PGPHelper, getConnectedUserV2Core, - getUserDID, validateGroupMemberUpdateOptions, pgpEncrypt, } from './helpers'; @@ -60,7 +59,7 @@ export const updateGroupMembers = async ( const convertedUpsertPromise = Object.entries(upsert).map( async ([role, userDIDs]) => { const userIDs = await Promise.all( - userDIDs.map((userDID) => getUserDID(userDID, env)) + userDIDs.map((userDID) => convertToValidDID(userDID, env)) ); return [role, userIDs]; } @@ -69,7 +68,7 @@ export const updateGroupMembers = async ( await Promise.all(convertedUpsertPromise) ); const convertedRemove = await Promise.all( - remove.map((userDID) => getUserDID(userDID, env)) + remove.map((userDID) => convertToValidDID(userDID, env)) ); let encryptedSecret: string | null = null; diff --git a/packages/restapi/src/lib/helpers/address.ts b/packages/restapi/src/lib/helpers/address.ts index c8e2b40d5..f50796aa5 100644 --- a/packages/restapi/src/lib/helpers/address.ts +++ b/packages/restapi/src/lib/helpers/address.ts @@ -1,40 +1,42 @@ import * as viem from 'viem'; -import Constants, {ENV} from '../constants'; -import { getUserDID } from '../chat/helpers'; +import Constants, { ENV } from '../constants'; +import { get } from '../user'; export interface AddressValidatorsType { - [key: string]: ({ address } : { address: string }) => boolean; + [key: string]: ({ address }: { address: string }) => boolean; } -export function isValidETHAddress(address: string) { - if(isValidCAIP10NFTAddress(address))return true; - if (address.includes('eip155:')) { - const splittedAddress = address.split(':'); - if(splittedAddress.length === 3){ - return viem.isAddress(splittedAddress[2]); - } - if(splittedAddress.length === 2) - return viem.isAddress(splittedAddress[1]); +/** + * CHECK IF THE WALLET IS A VALID PUSH CAIP SCW DID + * @param wallet scw:eip155:chainId:address + * @returns boolean + */ +export const isValidSCWCAIP = (wallet: string) => { + try { + const walletComponent = wallet.split(':'); + return ( + walletComponent.length === 4 && + walletComponent[0] === 'scw' && + walletComponent[1] === 'eip155' && + !isNaN(Number(walletComponent[2])) && + Number(walletComponent[2]) > 0 && + viem.isAddress(walletComponent[3]) + ); + } catch (err) { + return false; } - return viem.isAddress(address); -} - -export function isValidNFTCAIP10Address (realCAIP10: string) { - const walletComponent = realCAIP10.split(':'); - if (isNaN(Number(walletComponent[1]))) return false - return (walletComponent.length === 3 && walletComponent[0] === 'eip155' && viem.isAddress(walletComponent[2])) -} +}; /** - * + * CHECK IF THE WALLET IS A VALID PUSH CAIP NFT DID * @param wallet nft:eip155:nftChainId:nftContractAddress:nftTokenId - * @returns + * @returns boolean */ -export const isValidCAIP10NFTAddress = (wallet: string): boolean => { +export const isValidNFTCAIP = (wallet: string): boolean => { try { const walletComponent = wallet.split(':'); return ( - (walletComponent.length === 5 || walletComponent.length === 6)&& + (walletComponent.length === 5 || walletComponent.length === 6) && walletComponent[0].toLowerCase() === 'nft' && !isNaN(Number(walletComponent[4])) && Number(walletComponent[4]) > 0 && @@ -48,26 +50,121 @@ export const isValidCAIP10NFTAddress = (wallet: string): boolean => { } }; +/** + * CHECK IF THE WALLET IS A VALID PUSH CAIP EOA DID + * @param wallet eip155:chainId:address | eip155:address + * @returns + */ +export const isValidEOACAIP = (wallet: string): boolean => { + try { + const walletComponent = wallet.split(':'); + if (walletComponent.length === 3) { + return ( + walletComponent[0] === 'eip155' && + !isNaN(Number(walletComponent[1])) && + Number(walletComponent[1]) > 0 && + viem.isAddress(walletComponent[2]) + ); + } + if (walletComponent.length === 2) { + return ( + walletComponent[0] === 'eip155' && viem.isAddress(walletComponent[1]) + ); + } + return false; + } catch (err) { + return false; + } +}; + +/** + * CHECK IF THE WALLET IS A VALID PUSH CAIP + * @param wallet + * @returns boolean + */ +export const isValidPushCAIP = (wallet: string): boolean => { + return ( + isValidEOACAIP(wallet) || + isValidSCWCAIP(wallet) || + isValidNFTCAIP(wallet) || + viem.isAddress(wallet) + ); +}; + +/** + * CONVERT A VALID PUSH CAIP TO A VALID PUSH DID + * @param wallet valid wallet CAIP + * @param env optional env + * @param chainId optional chainId + * @param provider optional provider + * @returns valid Push DID + */ +export const convertToValidDID = async ( + wallet: string, + env: ENV = ENV.STAGING, + chainId?: number, + provider?: any +) => { + /** @dev Why Not throw error? - Used by Group ChatID also */ + if (!isValidPushCAIP(wallet)) return wallet; + if ( + isValidEOACAIP(wallet) || + isValidSCWCAIP(wallet) || + (isValidNFTCAIP(wallet) && wallet.split(':').length === 6) + ) + return wallet; + + if (isValidNFTCAIP(wallet)) { + const user = await get({ account: wallet, env: env }); + if (user && user.did) return user.did; + const epoch = Math.floor(Date.now() / 1000); + return `${wallet}:${epoch}`; + } + + // TODO: Implement SCW DID CHECK + if (provider) { + try { + // check if onChain code exists + } catch (err) { + // Ignore if it fails + } + } + + return chainId ? `eip155:${chainId}:${wallet}` : `eip155:${wallet}`; +}; + +/** + * CHECK IF THE WALLET IS A VALID FULL CAIP10 + * @param wallet eip155:chainId:address + * @returns boolean + */ +export const isValidFullCAIP10 = (wallet: string) => { + const walletComponent = wallet.split(':'); + if (isNaN(Number(walletComponent[1]))) return false; + return ( + walletComponent[0] === 'eip155' && + !isNaN(Number(walletComponent[1])) && + Number(walletComponent[1]) > 0 && + viem.isAddress(walletComponent[2]) + ); +}; + const AddressValidators: AddressValidatorsType = { // Ethereum - 'eip155': ({ address } : { address: string }) => { - return isValidETHAddress(address); - } + eip155: ({ address }: { address: string }) => { + return isValidPushCAIP(address); + }, // Add other chains here }; export function validateCAIP(addressInCAIP: string) { - const [ - blockchain, - networkId, - address - ] = addressInCAIP.split(':'); + const [blockchain, networkId, address] = addressInCAIP.split(':'); if (!blockchain) return false; if (!networkId) return false; if (!address) return false; - if(isValidCAIP10NFTAddress(addressInCAIP))return true; + if (isValidNFTCAIP(addressInCAIP)) return true; const validatorFn = AddressValidators[blockchain]; @@ -80,18 +177,14 @@ export type CAIPDetailsType = { address: string; }; -export function getCAIPDetails(addressInCAIP: string) : CAIPDetailsType | null { +export function getCAIPDetails(addressInCAIP: string): CAIPDetailsType | null { if (validateCAIP(addressInCAIP)) { - const [ - blockchain, - networkId, - address - ] = addressInCAIP.split(':'); + const [blockchain, networkId, address] = addressInCAIP.split(':'); return { blockchain, networkId, - address + address, }; } @@ -101,7 +194,11 @@ export function getCAIPDetails(addressInCAIP: string) : CAIPDetailsType | null { export function getFallbackETHCAIPAddress(env: ENV, address: string) { let chainId = 1; // by default PROD - if (env === Constants.ENV.DEV || env === Constants.ENV.STAGING || env === Constants.ENV.LOCAL) { + if ( + env === Constants.ENV.DEV || + env === Constants.ENV.STAGING || + env === Constants.ENV.LOCAL + ) { chainId = 11155111; } @@ -109,23 +206,23 @@ export function getFallbackETHCAIPAddress(env: ENV, address: string) { } /** - * This helper + * This helper * checks if a VALID CAIP * return the CAIP * else * check if valid ETH * return a CAIP representation of that address (EIP155 + env) - * else + * else * throw error! */ export async function getCAIPAddress(env: ENV, address: string, msg?: string) { - if(isValidCAIP10NFTAddress(address)){ - return await getUserDID(address, env); + if (isValidNFTCAIP(address)) { + return await convertToValidDID(address, env); } if (validateCAIP(address)) { return address; } else { - if (isValidETHAddress(address)) { + if (isValidPushCAIP(address)) { return getFallbackETHCAIPAddress(env, address); } else { throw Error(`Invalid Address! ${msg} \n Address: ${address}`); @@ -133,27 +230,29 @@ export async function getCAIPAddress(env: ENV, address: string, msg?: string) { } } -export const getCAIPWithChainId = (address:string, chainId:number, msg?: string) => { - if(isValidETHAddress(address)) { - if(!address.includes('eip155:')) - return `eip155:${chainId}:${address}`; - else - return address; +export const getCAIPWithChainId = ( + address: string, + chainId: number, + msg?: string +) => { + if (isValidPushCAIP(address)) { + if (!address.includes('eip155:')) return `eip155:${chainId}:${address}`; + else return address; } else { throw Error(`Invalid Address! ${msg} \n Address: ${address}`); } -} +}; // P = Partial CAIP -export const walletToPCAIP10 = (account:string): string => { - if(isValidCAIP10NFTAddress(account) || account.includes('eip155:')){ - return account +export const walletToPCAIP10 = (account: string): string => { + if (isValidNFTCAIP(account) || account.includes('eip155:')) { + return account; } - return 'eip155:' + account -} + return 'eip155:' + account; +}; export const pCAIP10ToWallet = (wallet: string): string => { - if(isValidCAIP10NFTAddress(wallet))return wallet; - wallet = wallet.replace('eip155:', '') - return wallet -} \ No newline at end of file + if (isValidNFTCAIP(wallet)) return wallet; + wallet = wallet.replace('eip155:', ''); + return wallet; +}; diff --git a/packages/restapi/src/lib/helpers/crypto.ts b/packages/restapi/src/lib/helpers/crypto.ts index 7ed3e7557..94b90cb98 100644 --- a/packages/restapi/src/lib/helpers/crypto.ts +++ b/packages/restapi/src/lib/helpers/crypto.ts @@ -23,11 +23,7 @@ import { ProgressHookType, ProgressHookTypeFunction, } from '../types'; -import { - isValidCAIP10NFTAddress, - isValidETHAddress, - pCAIP10ToWallet, -} from './address'; +import { isValidNFTCAIP, isValidPushCAIP, pCAIP10ToWallet } from './address'; import { verifyProfileSignature } from '../chat/helpers/signature'; import { upgrade } from '../user/upgradeUser'; import PROGRESSHOOK from '../progressHook'; @@ -133,7 +129,7 @@ export const decryptPGPKey = async (options: decryptPgpKeyProps) => { const wallet = getWallet({ account, signer }); const address = await getAccountAddress(wallet); - if (!isValidETHAddress(address)) { + if (!isValidPushCAIP(address)) { throw new Error(`Invalid address!`); } @@ -530,7 +526,7 @@ export const verifyProfileKeys = async ( encryptedPrivateKey, }; - if (isValidCAIP10NFTAddress(did)) { + if (isValidNFTCAIP(did)) { const keyToRemove = 'owner'; const parsedEncryptedPrivateKey = JSON.parse(encryptedPrivateKey); if (keyToRemove in parsedEncryptedPrivateKey) { @@ -544,7 +540,7 @@ export const verifyProfileKeys = async ( const isValidSig: boolean = await verifyProfileSignature( verificationProof, signedData, - isValidCAIP10NFTAddress(did) + isValidNFTCAIP(did) ? pCAIP10ToWallet(JSON.parse(encryptedPrivateKey).owner) : pCAIP10ToWallet(did) ); diff --git a/packages/restapi/src/lib/payloads/helpers.ts b/packages/restapi/src/lib/payloads/helpers.ts index 228cbb77b..de1be2071 100644 --- a/packages/restapi/src/lib/payloads/helpers.ts +++ b/packages/restapi/src/lib/payloads/helpers.ts @@ -15,7 +15,7 @@ import { CHAIN_ID_TO_SOURCE, SOURCE_TYPES, } from './constants'; -import { getConnectedUser, sign } from '../chat/helpers'; +import { sign } from '../chat/helpers'; export function getUUID() { return uuidv4(); diff --git a/packages/restapi/src/lib/payloads/sendNotifications.ts b/packages/restapi/src/lib/payloads/sendNotifications.ts index 8de6e6bfb..ea02b3c12 100644 --- a/packages/restapi/src/lib/payloads/sendNotifications.ts +++ b/packages/restapi/src/lib/payloads/sendNotifications.ts @@ -13,8 +13,8 @@ import { getCAIPAddress, getCAIPDetails, getConfig, - isValidCAIP10NFTAddress, - isValidETHAddress, + isValidNFTCAIP, + isValidPushCAIP, } from '../helpers'; import { IDENTITY_TYPE, @@ -33,7 +33,7 @@ function validateOptions(options: ISendNotificationInputOptions) { if (!options?.channel) { throw '[Push SDK] - Error - sendNotification() - "channel" is mandatory!'; } - if (!isValidETHAddress(options.channel)) { + if (!isValidPushCAIP(options.channel)) { throw '[Push SDK] - Error - sendNotification() - "channel" is invalid!'; } if (options.senderType === 0 && options.signer === undefined) { @@ -213,7 +213,7 @@ export async function sendNotification(options: ISendNotificationInputOptions) { verificationProof, identity, sender: - senderType === 1 && !isValidCAIP10NFTAddress(_channelAddress) + senderType === 1 && !isValidNFTCAIP(_channelAddress) ? `${channelCAIPDetails?.blockchain}:${channelCAIPDetails?.address}` : _channelAddress, source, diff --git a/packages/restapi/src/lib/pushNotification/notification.ts b/packages/restapi/src/lib/pushNotification/notification.ts index d6b8ab7bc..c1e5a1438 100644 --- a/packages/restapi/src/lib/pushNotification/notification.ts +++ b/packages/restapi/src/lib/pushNotification/notification.ts @@ -97,7 +97,7 @@ export class Notification extends PushNotificationBaseClass { page = Constants.PAGINATION.INITIAL_PAGE, limit = Constants.PAGINATION.LIMIT, channel = null, - raw + raw, } = options || {}; const account = options?.account ? options.account @@ -109,7 +109,7 @@ export class Notification extends PushNotificationBaseClass { user: account!, env: this.env, channel: channel, - raw + raw, }); } catch (error) { throw new Error( diff --git a/packages/restapi/src/lib/pushapi/PushAPI.ts b/packages/restapi/src/lib/pushapi/PushAPI.ts index 6165b77fb..292ec9b37 100644 --- a/packages/restapi/src/lib/pushapi/PushAPI.ts +++ b/packages/restapi/src/lib/pushapi/PushAPI.ts @@ -18,7 +18,7 @@ import { import { ALPHA_FEATURE_CONFIG } from '../config'; import { Space } from './space'; import { Video } from './video'; -import { isValidCAIP10NFTAddress } from '../helpers'; +import { isValidNFTCAIP } from '../helpers'; import { LRUCache } from 'lru-cache'; import { cache } from '../helpers/cache'; import { v4 as uuidv4 } from 'uuid'; @@ -261,7 +261,7 @@ export class PushAPI { message: decryptionError, }); console.error(decryptionError); - if (isValidCAIP10NFTAddress(derivedAccount)) { + if (isValidNFTCAIP(derivedAccount)) { const nftDecryptionError = 'NFT Account Detected. If this NFT was recently transferred to you, please ensure you have received the correct password from the previous owner. Alternatively, you can reinitialize for a fresh start. Please be aware that reinitialization will result in the loss of all previous account data.'; diff --git a/packages/restapi/src/lib/pushapi/chat.ts b/packages/restapi/src/lib/pushapi/chat.ts index ad5ffcb37..57aad1b04 100644 --- a/packages/restapi/src/lib/pushapi/chat.ts +++ b/packages/restapi/src/lib/pushapi/chat.ts @@ -25,8 +25,8 @@ import { } from './pushAPITypes'; import * as PUSH_USER from '../user'; import * as PUSH_CHAT from '../chat'; -import { PGPHelper, getUserDID } from '../chat/helpers'; -import { isValidETHAddress } from '../helpers'; +import { PGPHelper } from '../chat/helpers'; +import { convertToValidDID, isValidPushCAIP } from '../helpers'; import { ChatUpdateGroupProfileType, updateGroupProfile, @@ -208,7 +208,7 @@ export class Chat { }); for (const element of users) { - if (!isValidETHAddress(element)) { + if (!isValidPushCAIP(element)) { throw new Error('Invalid address in the users: ' + element); } } @@ -249,7 +249,7 @@ export class Chat { }); for (const element of users) { - if (!isValidETHAddress(element)) { + if (!isValidPushCAIP(element)) { throw new Error('Invalid address in the users: ' + element); } } @@ -259,7 +259,7 @@ export class Chat { } const userDIDsPromises = users.map(async (user) => { - return (await getUserDID(user, this.env)).toLowerCase(); + return (await convertToValidDID(user, this.env)).toLowerCase(); }); const userDIDs = await Promise.all(userDIDsPromises); @@ -284,33 +284,29 @@ export class Chat { } async info( - receipient: string, + recipient: string, options?: { overrideAccount?: string; } ): Promise { const accountToUse = options?.overrideAccount || this.account; const request: PUSH_CHAT.GetChatInfoType = { - receipient: receipient, - sender: accountToUse, + recipient: recipient, + account: accountToUse, env: this.env, }; try { const chatInfo = await PUSH_CHAT.getChatInfo(request); - const finalRecipient = chatInfo.meta.group - ? chatInfo.chatId - : receipient; - - const response: ChatInfoResponse = { - meta: chatInfo.meta, - list: chatInfo.list, - participants: chatInfo.participants, - chatId: chatInfo.chatId, - receipient: finalRecipient, - }; - - return response; - return chatInfo; + const finalRecipient = chatInfo.meta.group ? chatInfo.chatId : recipient; + + const response: ChatInfoResponse = { + meta: chatInfo.meta, + list: chatInfo.list, + participants: chatInfo.participants, + chatId: chatInfo.chatId, + recipient: finalRecipient, + }; + return response; } catch (error) { console.error(`Error in Chat.info: `, error); throw new Error(`Error fetching chat info: ${error}`); @@ -508,7 +504,7 @@ export class Chat { } accounts.forEach((account) => { - if (!isValidETHAddress(account)) { + if (!isValidPushCAIP(account)) { throw new Error(`Invalid account address: ${account}`); } }); @@ -561,7 +557,7 @@ export class Chat { } accounts.forEach((account) => { - if (!isValidETHAddress(account)) { + if (!isValidPushCAIP(account)) { throw new Error(`Invalid account address: ${account}`); } }); @@ -623,7 +619,7 @@ export class Chat { } accounts.forEach((account) => { - if (!isValidETHAddress(account)) { + if (!isValidPushCAIP(account)) { throw new Error(`Invalid account address: ${account}`); } }); diff --git a/packages/restapi/src/lib/pushapi/space.ts b/packages/restapi/src/lib/pushapi/space.ts index 51f609a18..52a2014d4 100644 --- a/packages/restapi/src/lib/pushapi/space.ts +++ b/packages/restapi/src/lib/pushapi/space.ts @@ -39,7 +39,7 @@ import { groupInfoDtoToSpaceInfoDto, mapSpaceListTypeToChatListType, } from '../chat'; -import { isValidETHAddress } from '../helpers'; +import { isValidPushCAIP } from '../helpers'; import { Chat } from './chat'; import { Signer as PushSigner } from '../helpers'; @@ -237,7 +237,7 @@ export class Space { } accounts.forEach((account) => { - if (!isValidETHAddress(account)) { + if (!isValidPushCAIP(account)) { throw new Error(`Invalid account address: ${account}`); } }); @@ -282,7 +282,7 @@ export class Space { } accounts.forEach((account) => { - if (!isValidETHAddress(account)) { + if (!isValidPushCAIP(account)) { throw new Error(`Invalid account address: ${account}`); } }); @@ -347,7 +347,7 @@ export class Space { } accounts.forEach((account) => { - if (!isValidETHAddress(account)) { + if (!isValidPushCAIP(account)) { throw new Error(`Invalid account address: ${account}`); } }); diff --git a/packages/restapi/src/lib/space/approve.ts b/packages/restapi/src/lib/space/approve.ts index 61b426fcc..bea10fe00 100644 --- a/packages/restapi/src/lib/space/approve.ts +++ b/packages/restapi/src/lib/space/approve.ts @@ -1,58 +1,48 @@ -import { - isValidETHAddress, -} from '../helpers'; +import { isValidPushCAIP } from '../helpers'; import Constants from '../constants'; -import { - EnvOptionsType, - SignerType -} from '../types'; -import { - approve as approveRequest -} from '../chat/approveRequest'; +import { EnvOptionsType, SignerType } from '../types'; +import { approve as approveRequest } from '../chat/approveRequest'; interface ApproveRequestOptionsType extends EnvOptionsType { senderAddress: string; - pgpPrivateKey ? : string | null; - status ? : 'Approved'; - account ? : string | null; - signer ? : SignerType | null; + pgpPrivateKey?: string | null; + status?: 'Approved'; + account?: string | null; + signer?: SignerType | null; } export const approve = async ( options: ApproveRequestOptionsType -): Promise < string > => { +): Promise => { const { - status = 'Approved', - account = null, - signer = null, - senderAddress, // space id - env = Constants.ENV.PROD, - pgpPrivateKey = null, + status = 'Approved', + account = null, + signer = null, + senderAddress, // space id + env = Constants.ENV.PROD, + pgpPrivateKey = null, } = options || {}; try { + if (account == null && signer == null) { + throw new Error(`At least one from account or signer is necessary!`); + } - if (account == null && signer == null) { - throw new Error(`At least one from account or signer is necessary!`); - } - - if (!isValidETHAddress(senderAddress) && !senderAddress.startsWith("spaces:")) { - throw new Error("Not a valid spaceId or ETH address"); - } - return await approveRequest({ - status: status, - account: account, - signer: signer, - senderAddress: senderAddress, - env: env, - pgpPrivateKey: pgpPrivateKey - }) + if ( + !isValidPushCAIP(senderAddress) && + !senderAddress.startsWith('spaces:') + ) { + throw new Error('Not a valid spaceId or ETH address'); + } + return await approveRequest({ + status: status, + account: account, + signer: signer, + senderAddress: senderAddress, + env: env, + pgpPrivateKey: pgpPrivateKey, + }); } catch (err) { - console.error( - `[Push SDK] - API - Error - API ${approve.name} -: `, - err - ); - throw Error( - `[Push SDK] - API - Error - API ${approve.name} -: ${err}` - ); + console.error(`[Push SDK] - API - Error - API ${approve.name} -: `, err); + throw Error(`[Push SDK] - API - Error - API ${approve.name} -: ${err}`); } }; diff --git a/packages/restapi/src/lib/space/requests.ts b/packages/restapi/src/lib/space/requests.ts index b6821f590..fb0ce10a8 100644 --- a/packages/restapi/src/lib/space/requests.ts +++ b/packages/restapi/src/lib/space/requests.ts @@ -1,7 +1,7 @@ -import { getAPIBaseUrls, isValidETHAddress } from '../helpers'; +import { convertToValidDID, getAPIBaseUrls, isValidPushCAIP } from '../helpers'; import Constants, { ENV } from '../constants'; -import { SpaceIFeeds } from '../types'; -import { getSpaceInboxLists, getUserDID } from '../chat/helpers'; +import { SpaceIFeeds } from '../types'; +import { getSpaceInboxLists } from '../chat/helpers'; import { axiosGet } from '../utils/axiosUtil'; export type RequestOptionsType = { @@ -40,11 +40,11 @@ export const requests = async ( page = 1, limit = 10, } = options || {}; - const user = await getUserDID(account, env); + const user = await convertToValidDID(account, env); const API_BASE_URL = getAPIBaseUrls(env); const apiEndpoint = `${API_BASE_URL}/v1/spaces/users/${user}/requests?page=${page}&limit=${limit}`; try { - if (!isValidETHAddress(user)) { + if (!isValidPushCAIP(user)) { throw new Error(`Invalid address!`); } const response = await axiosGet(apiEndpoint); diff --git a/packages/restapi/src/lib/space/spaceFeed.ts b/packages/restapi/src/lib/space/spaceFeed.ts index 5084feebd..a994a4417 100644 --- a/packages/restapi/src/lib/space/spaceFeed.ts +++ b/packages/restapi/src/lib/space/spaceFeed.ts @@ -1,7 +1,7 @@ -import { getAPIBaseUrls, isValidETHAddress } from '../helpers'; +import { convertToValidDID, getAPIBaseUrls, isValidPushCAIP } from '../helpers'; import Constants, { ENV } from '../constants'; import { SpaceIFeeds } from '../types'; -import { getSpaceInboxLists, getUserDID } from './../chat/helpers'; +import { getSpaceInboxLists } from './../chat/helpers'; import { axiosGet } from '../utils/axiosUtil'; export const spaceFeed = async (options: { @@ -18,9 +18,9 @@ export const spaceFeed = async (options: { toDecrypt = false, recipient, } = options || {}; - const user = await getUserDID(account, env); - const recipientWallet = await getUserDID(recipient, env); - if (!isValidETHAddress(user)) throw new Error(`Invalid address ${user}`); + const user = await convertToValidDID(account, env); + const recipientWallet = await convertToValidDID(recipient, env); + if (!isValidPushCAIP(user)) throw new Error(`Invalid address ${user}`); const API_BASE_URL = getAPIBaseUrls(env); const apiEndpoint = `${API_BASE_URL}/v1/spaces/users/${user}/space/${recipientWallet}`; try { diff --git a/packages/restapi/src/lib/space/spaces.ts b/packages/restapi/src/lib/space/spaces.ts index 1f802781c..cd24c0901 100644 --- a/packages/restapi/src/lib/space/spaces.ts +++ b/packages/restapi/src/lib/space/spaces.ts @@ -1,7 +1,7 @@ -import { getAPIBaseUrls, isValidETHAddress } from '../helpers'; +import { convertToValidDID, getAPIBaseUrls, isValidPushCAIP } from '../helpers'; import Constants, { ENV } from '../constants'; -import { SpaceIFeeds } from '../types'; -import { getSpaceInboxLists, getUserDID } from '../chat/helpers'; +import { SpaceIFeeds } from '../types'; +import { getSpaceInboxLists } from '../chat/helpers'; import { axiosGet } from '../utils/axiosUtil'; export type ChatsOptionsType = { @@ -28,7 +28,9 @@ export type ChatsOptionsType = { /** * Return the latest message from all wallet addresses you have talked to. This can be used when building the inbox page. */ -export const spaces = async (options: ChatsOptionsType): Promise => { +export const spaces = async ( + options: ChatsOptionsType +): Promise => { const { account, pgpPrivateKey, @@ -36,10 +38,10 @@ export const spaces = async (options: ChatsOptionsType): Promise page = 1, limit = 10, } = options || {}; - if (!isValidETHAddress(account)) { + if (!isValidPushCAIP(account)) { throw new Error(`Invalid address!`); } - const user = await getUserDID(account, env); + const user = await convertToValidDID(account, env); const API_BASE_URL = getAPIBaseUrls(env); const apiEndpoint = `${API_BASE_URL}/v1/spaces/users/${user}/spaces?page=${page}&limit=${limit}`; const requestUrl = `${apiEndpoint}`; diff --git a/packages/restapi/src/lib/user/auth.updateUser.ts b/packages/restapi/src/lib/user/auth.updateUser.ts index 8074dcfc8..789abd0e2 100644 --- a/packages/restapi/src/lib/user/auth.updateUser.ts +++ b/packages/restapi/src/lib/user/auth.updateUser.ts @@ -6,7 +6,7 @@ import { import Constants, { ENV, ENCRYPTION_TYPE } from '../constants'; import { encryptPGPKey, - isValidETHAddress, + isValidPushCAIP, preparePGPPublicKey, walletToPCAIP10, } from '../helpers'; @@ -68,7 +68,7 @@ export const authUpdate = async (options: AuthUpdateProps): Promise => { ? true : false; - if (!isValidETHAddress(address)) { + if (!isValidPushCAIP(address)) { throw new Error(`Invalid address!`); } diff --git a/packages/restapi/src/lib/user/createUser.ts b/packages/restapi/src/lib/user/createUser.ts index 2583ac78e..c14822009 100644 --- a/packages/restapi/src/lib/user/createUser.ts +++ b/packages/restapi/src/lib/user/createUser.ts @@ -8,11 +8,11 @@ import { } from '../chat/helpers'; import Constants, { ENV } from '../constants'; import { - isValidETHAddress, + isValidPushCAIP, walletToPCAIP10, encryptPGPKey, preparePGPPublicKey, - isValidCAIP10NFTAddress, + isValidNFTCAIP, validatePssword, } from '../helpers'; import { @@ -76,7 +76,7 @@ export const createUserCore = async ( const wallet = getWallet({ account, signer }); const address = await getAccountAddress(wallet); - if (!isValidETHAddress(address)) { + if (!isValidPushCAIP(address)) { throw new Error(`Invalid address!`); } if (additionalMeta?.NFTPGP_V1?.password) { @@ -86,7 +86,7 @@ export const createUserCore = async ( const caip10: string = walletToPCAIP10(address); let encryptionType = version; - if (isValidCAIP10NFTAddress(caip10)) { + if (isValidNFTCAIP(caip10)) { // upgrade to v4 (nft encryption) encryptionType = Constants.ENC_TYPE_V4; } else { diff --git a/packages/restapi/src/lib/user/decryptAuth.ts b/packages/restapi/src/lib/user/decryptAuth.ts index b9a160a2c..47f6c42c5 100644 --- a/packages/restapi/src/lib/user/decryptAuth.ts +++ b/packages/restapi/src/lib/user/decryptAuth.ts @@ -1,5 +1,5 @@ import Constants, { ENV } from '../constants'; -import { decryptPGPKey, isValidCAIP10NFTAddress } from '../helpers'; +import { decryptPGPKey, isValidNFTCAIP } from '../helpers'; import PROGRESSHOOK from '../progressHook'; import { ProgressHookType, @@ -37,7 +37,7 @@ export const decryptAuth = async ( progressHook, } = options || {}; try { - if (!isValidCAIP10NFTAddress(account as string)) { + if (!isValidNFTCAIP(account as string)) { return null; } // Report Progress diff --git a/packages/restapi/src/lib/user/getUser.ts b/packages/restapi/src/lib/user/getUser.ts index a3012c1a8..ee67b568b 100644 --- a/packages/restapi/src/lib/user/getUser.ts +++ b/packages/restapi/src/lib/user/getUser.ts @@ -1,5 +1,5 @@ import { AccountEnvOptionsType, IUser } from '../types'; -import { isValidETHAddress, walletToPCAIP10 } from '../helpers/address'; +import { isValidPushCAIP, walletToPCAIP10 } from '../helpers/address'; import { getAPIBaseUrls, verifyProfileKeys } from '../helpers'; import Constants from '../constants'; import { populateDeprecatedUser } from '../utils/populateIUser'; @@ -7,7 +7,7 @@ import { axiosGet } from '../utils/axiosUtil'; export const get = async (options: AccountEnvOptionsType): Promise => { const { account, env = Constants.ENV.PROD } = options || {}; - if (!isValidETHAddress(account)) { + if (!isValidPushCAIP(account)) { throw new Error(`Invalid address!`); } const caip10 = walletToPCAIP10(account); diff --git a/packages/restapi/src/lib/user/getUsersBatch.ts b/packages/restapi/src/lib/user/getUsersBatch.ts index 2ec31fa4c..03b3b05a0 100644 --- a/packages/restapi/src/lib/user/getUsersBatch.ts +++ b/packages/restapi/src/lib/user/getUsersBatch.ts @@ -1,5 +1,5 @@ import { IUser } from '../types'; -import { isValidETHAddress, walletToPCAIP10 } from '../helpers/address'; +import { isValidPushCAIP, walletToPCAIP10 } from '../helpers/address'; import { getAPIBaseUrls, verifyProfileKeys } from '../helpers'; import Constants, { ENV } from '../constants'; import { populateDeprecatedUser } from '../utils/populateIUser'; @@ -24,7 +24,7 @@ export const getBatch = async (options: GetBatchType): Promise => { } for (let i = 0; i < userIds.length; i++) { - if (!isValidETHAddress(userIds[i])) { + if (!isValidPushCAIP(userIds[i])) { throw new Error(`Invalid user address!`); } } diff --git a/packages/restapi/src/lib/user/profile.updateUser.ts b/packages/restapi/src/lib/user/profile.updateUser.ts index 3d83b14c1..e33d76bad 100644 --- a/packages/restapi/src/lib/user/profile.updateUser.ts +++ b/packages/restapi/src/lib/user/profile.updateUser.ts @@ -1,9 +1,10 @@ import * as CryptoJS from 'crypto-js'; -import { IPGPHelper, PGPHelper, getUserDID } from '../chat/helpers'; +import { IPGPHelper, PGPHelper } from '../chat/helpers'; import Constants, { ENV } from '../constants'; import { + convertToValidDID, getAPIBaseUrls, - isValidETHAddress, + isValidPushCAIP, verifyProfileKeys, } from '../helpers'; import { IUser, ProgressHookType, ProgressHookTypeFunction } from '../types'; @@ -55,7 +56,7 @@ export const profileUpdateCore = async ( progressHook, } = options || {}; try { - if (!isValidETHAddress(account)) { + if (!isValidPushCAIP(account)) { throw new Error(`Invalid account!`); } @@ -67,7 +68,7 @@ export const profileUpdateCore = async ( if (profile.blockedUsersList) { for (const element of profile.blockedUsersList) { // Check if the element is a valid CAIP-10 address - if (!isValidETHAddress(element)) { + if (!isValidPushCAIP(element)) { throw new Error( 'Invalid address in the blockedUsersList: ' + element ); @@ -76,7 +77,7 @@ export const profileUpdateCore = async ( const convertedBlockedListUsersPromise = profile.blockedUsersList.map( async (each) => { - return getUserDID(each, env); + return convertToValidDID(each, env); } ); blockedUsersList = await Promise.all(convertedBlockedListUsersPromise); diff --git a/packages/restapi/src/lib/user/upgradeUser.ts b/packages/restapi/src/lib/user/upgradeUser.ts index 5bc39d04b..0a7888bec 100644 --- a/packages/restapi/src/lib/user/upgradeUser.ts +++ b/packages/restapi/src/lib/user/upgradeUser.ts @@ -1,6 +1,6 @@ import { getAccountAddress, getWallet } from '../chat/helpers'; import Constants, { ENV } from '../constants'; -import { isValidETHAddress, decryptPGPKey } from '../helpers'; +import { isValidPushCAIP, decryptPGPKey } from '../helpers'; import { SignerType, IUser, @@ -41,7 +41,7 @@ export const upgrade = async (options: UpgradeUserProps): Promise => { const wallet = getWallet({ account, signer }); const address = await getAccountAddress(wallet); - if (!isValidETHAddress(address)) { + if (!isValidPushCAIP(address)) { throw new Error(`Invalid address!`); } diff --git a/packages/restapi/src/lib/video/VideoV2.ts b/packages/restapi/src/lib/video/VideoV2.ts index 45d300f6e..eae801e2f 100644 --- a/packages/restapi/src/lib/video/VideoV2.ts +++ b/packages/restapi/src/lib/video/VideoV2.ts @@ -1,11 +1,7 @@ import { produce } from 'immer'; import { chats } from '../chat'; import { ENV } from '../constants'; -import { - isValidETHAddress, - pCAIP10ToWallet, - walletToPCAIP10, -} from '../helpers'; +import { isValidPushCAIP, pCAIP10ToWallet, walletToPCAIP10 } from '../helpers'; import { VIDEO_NOTIFICATION_ACCESS_TYPE } from '../payloads/constants'; import { VideoCallStatus, @@ -26,7 +22,7 @@ export class VideoV2 { private videoInstance: VideoV1; // peerInfo objects from the incoming video call requests - private peerInfos: {[key: string]: VideoPeerInfo}; + private peerInfos: { [key: string]: VideoPeerInfo }; /** * VideoV2 constructor @@ -41,13 +37,13 @@ export class VideoV2 { account, decryptedPgpPvtKey, env, - peerInfos + peerInfos, }: { videoV1Instance: VideoV1; account: string; decryptedPgpPvtKey: string; env: ENV; - peerInfos: {[key: string]: VideoPeerInfo} + peerInfos: { [key: string]: VideoPeerInfo }; }) { this.videoInstance = videoV1Instance; this.account = account; @@ -75,7 +71,7 @@ export class VideoV2 { const { rules } = options || {}; for (const recipient of recipients) { - if (!isValidETHAddress(recipient)) { + if (!isValidPushCAIP(recipient)) { throw new Error('Invalid recipient address found'); } } @@ -164,7 +160,9 @@ export class VideoV2 { if (!address) { const peerInfoAddresses = Object.keys(this.peerInfos); if (peerInfoAddresses.length !== 1) { - throw new Error('Either no request exists or more than one request found. Please pass an address.'); + throw new Error( + 'Either no request exists or more than one request found. Please pass an address.' + ); } address = peerInfoAddresses[0]; } @@ -189,7 +187,9 @@ export class VideoV2 { if (!address) { const peerInfoAddresses = Object.keys(this.peerInfos); if (peerInfoAddresses.length !== 1) { - throw new Error('Either no request exists or more than one request found. Please pass an address.'); + throw new Error( + 'Either no request exists or more than one request found. Please pass an address.' + ); } address = peerInfoAddresses[0]; } diff --git a/packages/restapi/src/lib/video/helpers/validatePeerInfo.ts b/packages/restapi/src/lib/video/helpers/validatePeerInfo.ts index b72f20a4b..9402063de 100644 --- a/packages/restapi/src/lib/video/helpers/validatePeerInfo.ts +++ b/packages/restapi/src/lib/video/helpers/validatePeerInfo.ts @@ -1,4 +1,4 @@ -import { isValidETHAddress } from '../../helpers'; +import { isValidPushCAIP } from '../../helpers'; import { VIDEO_NOTIFICATION_ACCESS_TYPE } from '../../payloads/constants'; import { VideoPeerInfo } from '../../types'; @@ -9,7 +9,7 @@ export const validatePeerInfo = (peerInfo: VideoPeerInfo) => { throw new Error('Invalid signal data received'); } - if (!isValidETHAddress(address)) { + if (!isValidPushCAIP(address)) { throw new Error('Invalid address received'); }