Skip to content

Commit

Permalink
fix: tes cases and minor bugs (#1212)
Browse files Browse the repository at this point in the history
  • Loading branch information
Aman035 authored Apr 8, 2024
1 parent ed9d3a7 commit d30e095
Show file tree
Hide file tree
Showing 16 changed files with 187 additions and 113 deletions.
24 changes: 10 additions & 14 deletions packages/restapi/src/lib/channels/getChannel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import { parseSettings } from '../utils/parseSettings';
export type GetChannelOptionsType = {
channel: string;
env?: ENV;
raw?: boolean
raw?: boolean;
};

export const getChannel = async (options: GetChannelOptionsType) => {
Expand All @@ -21,17 +21,13 @@ export const getChannel = async (options: GetChannelOptionsType) => {
const apiEndpoint = `${API_BASE_URL}/v1/channels`;
const requestUrl = `${apiEndpoint}/${_channel}`;

return await axiosGet(requestUrl)
.then((response) => {
if(raw)
return response.data
else
{
response.data.channel_settings = response.data.channel_settings? parseSettings(response.data.channel_settings): null;
return response.data
}
})
.catch((err) => {
console.error(`[Push SDK] - API ${requestUrl}: `, err);
});
return await axiosGet(requestUrl).then((response) => {
if (raw) return response.data;
else {
response.data.channel_settings = response.data.channel_settings
? parseSettings(response.data.channel_settings)
: null;
return response.data;
}
});
};
4 changes: 3 additions & 1 deletion packages/restapi/src/lib/chat/helpers/crypto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -429,13 +429,15 @@ export const getEip712Signature = async (
export async function getDecryptedPrivateKey(
wallet: walletType,
user: any,
address: string
address: string,
env: ENV
): Promise<string> {
let decryptedPrivateKey;
if (wallet.signer) {
decryptedPrivateKey = await decryptPGPKey({
signer: wallet.signer,
encryptedPGPPrivateKey: user.encryptedPrivateKey,
env,
});
} else {
decryptedPrivateKey = await decryptWithWalletRPCMethod(
Expand Down
11 changes: 7 additions & 4 deletions packages/restapi/src/lib/chat/helpers/user.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,8 @@ export const getConnectedUser = async (
const decryptedPrivateKey = await getDecryptedPrivateKey(
wallet,
newUser,
address
address,
env
);
return { ...newUser, privateKey: decryptedPrivateKey };
}
Expand All @@ -86,7 +87,7 @@ export const getConnectedUserV2Core = async (
wallet: walletType,
privateKey: string | null,
env: ENV,
pgpHelper: IPGPHelper,
pgpHelper: IPGPHelper
): Promise<IConnectedUser> => {
const address = await getAccountAddress(wallet);
const user = await get({ account: address, env: env || Constants.ENV.PROD });
Expand All @@ -100,7 +101,8 @@ export const getConnectedUserV2Core = async (
const decryptedPrivateKey = await getDecryptedPrivateKey(
wallet,
user,
address
address,
env
);
return { ...user, privateKey: decryptedPrivateKey };
}
Expand All @@ -124,7 +126,8 @@ export const getConnectedUserV2Core = async (
const decryptedPrivateKey = await getDecryptedPrivateKey(
wallet,
newUser,
address
address,
env
);
return { ...newUser, privateKey: decryptedPrivateKey };
}
Expand Down
44 changes: 23 additions & 21 deletions packages/restapi/src/lib/payloads/sendNotifications.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@ import {
VIDEO_NOTIFICATION_ACCESS_TYPE,
} from './constants';
import { ENV } from '../constants';
import { getChannel } from '../channels/getChannel';
import { axiosPost } from '../utils/axiosUtil';
/**
* Validate options for some scenarios
Expand Down Expand Up @@ -86,30 +85,30 @@ function validateOptions(options: ISendNotificationInputOptions) {
* @returns boolean
*/
async function checkSimulateNotification(payloadOptions: {
channel: string;
channelFound: boolean;
channelorAlias: string;
recipient: string | string[] | undefined;
type: NOTIFICATION_TYPE;
env: ENV | undefined;
senderType: 0 | 1;
}): Promise<boolean> {
try {
const { channel, recipient, type, env } = payloadOptions || {};
// fetch channel info
const channelInfo = await getChannel({
channel: channel,
env: env,
});
// check if channel exists, if it does then its not simulate type
if (channelInfo) return false;
else {
// if no channel info found, check if channel address = recipient and notification type is targeted
const convertedRecipient =
typeof recipient == 'string' && recipient?.split(':').length == 3
? recipient.split(':')[2]
: recipient;
return (
channel == convertedRecipient && type == NOTIFICATION_TYPE.TARGETTED
);
}
const { channelFound, channelorAlias, recipient, type, env, senderType } =
payloadOptions || {};

// Video call notifications are not simulated
// If channel is found, then it is not a simulate type
if (senderType === 1 || channelFound) return false;

// if no channel info found, check if channel address = recipient and notification type is targeted
const convertedRecipient =
typeof recipient == 'string' && recipient?.split(':').length == 3
? recipient.split(':')[2]
: recipient;
return (
channelorAlias == convertedRecipient &&
type == NOTIFICATION_TYPE.TARGETTED
);
} catch (e) {
return true;
}
Expand All @@ -135,6 +134,7 @@ export async function sendNotification(options: ISendNotificationInputOptions) {
chatId,
rules,
pgpPrivateKey,
channelFound = true,
} = options || {};

validateOptions(options);
Expand Down Expand Up @@ -199,10 +199,12 @@ export async function sendNotification(options: ISendNotificationInputOptions) {
});

const source = (await checkSimulateNotification({
channel: options.channel,
channelFound: channelFound,
channelorAlias: options.channel,
recipient: options.recipients,
type: options.type,
env: options.env,
senderType: options.senderType as 0 | 1,
}))
? SOURCE_TYPES.SIMULATE
: getSource(chainId, identityType, senderType);
Expand Down
22 changes: 12 additions & 10 deletions packages/restapi/src/lib/pushNotification/channel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import * as config from '../config';
import {
getCAIPDetails,
getFallbackETHCAIPAddress,
pCAIP10ToWallet,
validateCAIP,
} from '../helpers';
import * as PUSH_PAYLOAD from '../payloads';
Expand Down Expand Up @@ -132,20 +131,17 @@ export class Channel extends PushNotificationBaseClass {
send = async (recipients: string[], options: NotificationOptions) => {
try {
this.checkSignerObjectExists();
const info = await this.getChannelOrAliasInfo(
const channelInfo = await this.getChannelOrAliasInfo(
options.channel! ?? this.account
);
let settings = null;
if (info && info.channel_settings) {
settings = JSON.parse(info.channel_settings);
}

const lowLevelPayload = this.generateNotificationLowLevelPayload({
signer: this.signer!,
env: this.env!,
recipients: recipients,
options: options,
channel: options.channel ?? this.account,
settings: settings,
channelInfo: channelInfo,
});
return await PUSH_PAYLOAD.sendNotification(lowLevelPayload);
} catch (error) {
Expand Down Expand Up @@ -384,7 +380,13 @@ export class Channel extends PushNotificationBaseClass {
config.MIN_TOKEN_BALANCE[this.env!].toString(),
18
);
if (fees > balance) {
// get counter
const counter = await this.fetchUpdateCounter(
this.coreContract,
this.account!
);
const totalFees = fees * counter;
if (totalFees > balance) {
throw new Error('Insufficient PUSH balance');
}
const allowanceAmount = await this.fetchAllownace(
Expand All @@ -393,11 +395,11 @@ export class Channel extends PushNotificationBaseClass {
config.CORE_CONFIG[this.env!].EPNS_CORE_CONTRACT
);
// if allowance is not greater than the fees, dont call approval again
if (!(allowanceAmount >= fees)) {
if (!(allowanceAmount >= totalFees)) {
const approveRes = await this.approveToken(
pushTokenContract,
config.CORE_CONFIG[this.env!].EPNS_CORE_CONTRACT,
fees
totalFees
);
if (!approveRes) {
throw new Error('Something went wrong while approving your token');
Expand Down
68 changes: 49 additions & 19 deletions packages/restapi/src/lib/pushNotification/pushNotificationBase.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,10 @@ import {
} from 'viem';
import * as PUSH_CHANNEL from '../channels';
import {
CAIPDetailsType,
Signer,
getAPIBaseUrls,
getCAIPDetails,
getFallbackETHCAIPAddress,
validateCAIP,
} from '../helpers';
Expand Down Expand Up @@ -140,14 +142,14 @@ export class PushNotificationBaseClass {
recipients,
options,
channel,
settings,
channelInfo,
}: {
signer: SignerType;
env: ENV;
recipients: string[];
options: NotificationOptions;
channel?: string;
settings: any | null;
channelInfo: any | null;
}): ISendNotificationInputOptions {
if (!channel) {
channel = `${this.account}`;
Expand All @@ -156,6 +158,14 @@ export class PushNotificationBaseClass {
const identityType = IDENTITY_TYPE.DIRECT_PAYLOAD;
// fetch the minimal version based on conifg that was passed
let index = '';

const settings =
channelInfo && channelInfo.channel_settings
? JSON.parse(channelInfo.channel_settings)
: null;

const channelFound = channelInfo ? true : false;

if (options.payload?.category && settings) {
if (settings[options.payload.category - 1].type == SLIDER_TYPE) {
index =
Expand Down Expand Up @@ -200,6 +210,7 @@ export class PushNotificationBaseClass {
env: env,
chatId: options.advanced?.chatid,
pgpPrivateKey: options.advanced?.pgpPrivateKey,
channelFound: channelFound,
};

return notificationPayload;
Expand Down Expand Up @@ -792,31 +803,50 @@ export class PushNotificationBaseClass {
return numberOfSettings + SETTING_SEPARATOR + userSetting;
}

/**
* @param address Address of the channel or alias
* @returns Channel info for the address
*/
protected async getChannelOrAliasInfo(address: string) {
try {
address = validateCAIP(address)
const channelOrAliasCaip = validateCAIP(address)
? address
: getFallbackETHCAIPAddress(this.env!, this.account!);

const { networkId } = getCAIPDetails(
channelOrAliasCaip
) as CAIPDetailsType;

let channelInCaip = channelOrAliasCaip;
if (networkId !== '1' && networkId !== '11155111') {
// Alias
const aliasInfo = await this.getAliasInfo(address);
channelInCaip = aliasInfo?.channel || channelInCaip;
}

const channelInfo = await PUSH_CHANNEL.getChannel({
channel: address as string,
channel: channelInCaip,
env: this.env,
});
if (channelInfo) return channelInfo;
// // TODO: Temp fix, do a more concrete fix later
const API_BASE_URL = getAPIBaseUrls(this.env!);
const apiEndpoint = `${API_BASE_URL}/v1/alias`;
const requestUrl = `${apiEndpoint}/${address}/channel`;
const aliasInfo = await axiosGet(requestUrl)
.then((response) => response.data)
.catch((err) => {
console.error(`[EPNS-SDK] - API ${requestUrl}: `, err);
});
const aliasInfoFromChannel = await PUSH_CHANNEL.getChannel({
channel: aliasInfo.channel as string,
env: this.env,
});
if (aliasInfoFromChannel) return aliasInfoFromChannel;

return channelInfo || null;
} catch (error) {
return null;
}
}

/**
* @param aliasInCaip Alias address in CAIP format
* @returns Channel info for the alias
*/
private async getAliasInfo(aliasInCaip: string) {
const API_BASE_URL = getAPIBaseUrls(this.env!);
const apiEndpoint = `${API_BASE_URL}/v1/alias`;
const requestUrl = `${apiEndpoint}/${aliasInCaip}/channel`;

try {
const response = await axiosGet(requestUrl);
return response.data;
} catch (error) {
return null;
}
Expand Down
12 changes: 8 additions & 4 deletions packages/restapi/src/lib/types/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,10 @@ import {
import { ENV, MessageType } from '../constants';
import { EthEncryptedData } from '@metamask/eth-sig-util';
import { Message, MessageObj } from './messageTypes';
import { SpaceMemberEventBase, VideoEvent } from '../pushstream/pushStreamTypes';
import {
SpaceMemberEventBase,
VideoEvent,
} from '../pushstream/pushStreamTypes';
export * from './messageTypes';
export * from './videoTypes';

Expand Down Expand Up @@ -184,6 +187,7 @@ export interface ISendNotificationInputOptions {
chatId?: string;
rules?: SendNotificationRules;
pgpPrivateKey?: string;
channelFound?: boolean;
}

export interface INotificationPayload {
Expand Down Expand Up @@ -960,8 +964,8 @@ export namespace TYPES {
}
}

export enum NotifictaionType {
export enum NotifictaionType {
BROADCAT = 1,
TARGETTED = 3,
SUBSET = 4
}
SUBSET = 4,
}
Loading

0 comments on commit d30e095

Please sign in to comment.