Skip to content

Added required changes for log messages #18

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 32 additions & 21 deletions src/Reclaim.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ const sdkVersion = require('../package.json').version;

export async function verifyProof(proof: Proof): Promise<boolean> {
if (!proof.signatures.length) {
throw new SignatureNotFoundError('No signatures')
throw new SignatureNotFoundError('No signatures, proof object is undefined')
}

try {
Expand All @@ -70,7 +70,7 @@ export async function verifyProof(proof: Proof): Promise<boolean> {
proof.identifier = replaceAll(proof.identifier, '"', '')
// check if the identifier matches the one in the proof
if (calculatedIdentifier !== proof.identifier) {
throw new ProofNotVerifiedError('Identifier Mismatch')
throw new ProofNotVerifiedError(`Identifier Mismatch, ${calculatedIdentifier} is not as ${proof.identifier}`)
}

const signedClaim: SignedClaim = {
Expand All @@ -84,7 +84,7 @@ export async function verifyProof(proof: Proof): Promise<boolean> {

assertValidSignedClaim(signedClaim, witnesses)
} catch (e: Error | unknown) {
logger.info(`Error verifying proof: ${e instanceof Error ? e.message : String(e)}`)
logger.error(`Error verifying proof: ${e instanceof Error ? e.message : String(e)}`)
return false
}

Expand All @@ -111,6 +111,7 @@ export function transformForOnchain(proof: Proof): { claimInfo: any, signedClaim
return { claimInfo, signedClaim };
}


export class ReclaimProofRequest {
// Private class properties
private applicationId: string;
Expand All @@ -132,10 +133,10 @@ export class ReclaimProofRequest {
this.timeStamp = Date.now().toString();
this.applicationId = applicationId;
this.sessionId = "";
if (options?.log) {
loggerModule.setLogLevel('info');
if (options?.log && options?.logLevel) {
loggerModule.setLogLevel(options?.logLevel!);
} else {
loggerModule.setLogLevel('silent');
loggerModule.setLogLevel('all')
}
this.options = options;
// Fetch sdk version from package.json
Expand All @@ -161,8 +162,13 @@ export class ReclaimProofRequest {
}
if (options.log) {
validateFunctionParams([
{ paramName: 'log', input: options.log }
{ paramName: 'log', input: options.log },
], 'the constructor')

if(options.logLevel){
validateFunctionParams([{ paramName: 'logLevel', input: options.logLevel }
], 'the constructor')
}
}

}
Expand All @@ -179,7 +185,8 @@ export class ReclaimProofRequest {

return proofRequestInstance
} catch (error) {
logger.info('Failed to initialize ReclaimProofRequest', error as Error);
logger.error('Failed to initialize ReclaimProofRequest', error as Error);
logger.warn("Try changing values of applicationId, applicationSecret, ProviderId, Option's Parameters")
throw new InitError('Failed to initialize ReclaimProofRequest', error as Error)
}
}
Expand Down Expand Up @@ -234,7 +241,7 @@ export class ReclaimProofRequest {
proofRequestInstance.sdkVersion = sdkVersion;
return proofRequestInstance
} catch (error) {
logger.info('Failed to parse JSON string in fromJsonString:', error);
logger.error('Failed to parse JSON string in fromJsonString:', error);
throw new InvalidParamError('Invalid JSON string provided to fromJsonString');
}
}
Expand All @@ -258,7 +265,8 @@ export class ReclaimProofRequest {
], 'addContext');
this.context = { contextAddress: address, contextMessage: message };
} catch (error) {
logger.info("Error adding context", error)
logger.error("Error adding context", error)
logger.info(`contextId: A unique identifier for the context (hex address) \nContext message: Additional information about the proof request (string)`)
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This info log should be not be in the catch block. Better to move it at top inside the try block

throw new AddContextError("Error adding context", error as Error)
}
}
Expand All @@ -285,7 +293,8 @@ export class ReclaimProofRequest {
}
this.requestedProof.parameters = { ...requestedProof.parameters, ...params }
} catch (error) {
logger.info('Error Setting Params:', error);
logger.error('Error Setting Params:', error);
logger.warn(`Arguments passed in setParams must be object which contains key => value pairs`)
throw new SetParamsError("Error setting params", error as Error)
}
}
Expand All @@ -296,7 +305,8 @@ export class ReclaimProofRequest {
validateFunctionParams([{ input: this.sessionId, paramName: 'sessionId', isString: true }], 'getAppCallbackUrl');
return this.appCallbackUrl || `${constants.DEFAULT_RECLAIM_CALLBACK_URL}${this.sessionId}`
} catch (error) {
logger.info("Error getting app callback url", error)
logger.error("Error getting app callback url", error)
logger.warn(`Make sure to pass URL and as a string`)
throw new GetAppCallbackUrlError("Error getting app callback url", error as Error)
}
}
Expand All @@ -306,7 +316,8 @@ export class ReclaimProofRequest {
validateFunctionParams([{ input: this.sessionId, paramName: 'sessionId', isString: true }], 'getStatusUrl');
return `${constants.DEFAULT_RECLAIM_STATUS_URL}${this.sessionId}`
} catch (error) {
logger.info("Error fetching Status Url", error)
logger.error("Error fetching Status Url", error)
logger.warn(`Make sure to pass URL and as a string`)
throw new GetStatusUrlError("Error fetching status url", error as Error)
}
}
Expand All @@ -318,7 +329,7 @@ export class ReclaimProofRequest {
this.signature = signature;
logger.info(`Signature set successfully for applicationId: ${this.applicationId}`);
} catch (error) {
logger.info("Error setting signature", error)
logger.error("Error setting signature", error)
throw new SetSignatureError("Error setting signature", error as Error)
}
}
Expand All @@ -337,7 +348,7 @@ export class ReclaimProofRequest {

return await wallet.signMessage(ethers.getBytes(messageHash));
} catch (err) {
logger.info(`Error generating proof request for applicationId: ${this.applicationId}, providerId: ${this.providerId}, signature: ${this.signature}, timeStamp: ${this.timeStamp}`, err);
logger.error(`Error generating proof request for applicationId: ${this.applicationId}, providerId: ${this.providerId}, signature: ${this.signature}, timeStamp: ${this.timeStamp}`, err);
throw new SignatureGeneratingError(`Error generating signature for applicationSecret: ${applicationSecret}`)
}
}
Expand All @@ -347,7 +358,7 @@ export class ReclaimProofRequest {
this.requestedProof = generateRequestedProof(provider);
return this.requestedProof;
} catch (err: Error | unknown) {
logger.info(err instanceof Error ? err.message : String(err));
logger.error(err instanceof Error ? err.message : String(err));
throw new BuildProofRequestError('Something went wrong while generating proof request', err as Error);
}
}
Expand All @@ -370,7 +381,7 @@ export class ReclaimProofRequest {
return [...new Set(availableParamsStore)];

} catch (error) {
logger.info("Error fetching available params", error)
logger.error("Error fetching available params", error)
throw new AvailableParamsError("Error fetching available params", error as Error)
}
}
Expand Down Expand Up @@ -428,16 +439,16 @@ export class ReclaimProofRequest {
await updateSession(this.sessionId, SessionStatus.SESSION_STARTED)
return link
} catch (error) {
logger.info('Error creating Request Url:', error)
logger.error('Error creating Request Url:', error)
throw error
}
}

async startSession({ onSuccess, onError }: StartSessionParams): Promise<void> {
if (!this.sessionId) {
const message = "Session can't be started due to undefined value of sessionId";
logger.info(message);
throw new SessionNotStartedError(message);
const message = "Session can't be started due to undefined value of statusUrl and sessionId"
logger.warn(message)
throw new SessionNotStartedError(message)
}

logger.info('Starting session');
Expand Down
3 changes: 2 additions & 1 deletion src/utils/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,5 +11,6 @@ export const constants = {
DEFAULT_RECLAIM_STATUS_URL: `${BACKEND_BASE_URL}/api/sdk/session/`,

// URL for sharing Reclaim templates
RECLAIM_SHARE_URL: 'https://share.reclaimprotocol.org/verifier/?template='
RECLAIM_SHARE_URL: 'https://share.reclaimprotocol.org/verifier/?template=',

};
19 changes: 12 additions & 7 deletions src/utils/logger.ts
Original file line number Diff line number Diff line change
@@ -1,21 +1,22 @@
// Define the possible log levels
export type LogLevel = 'info' | 'warn' | 'error' | 'silent';
export type LogLevel = 'info' | 'warn' | 'error' ;
export type ExtendedLog = LogLevel | 'all'

// Define a simple logger class
class SimpleLogger {
private level: LogLevel = 'info';
private level: ExtendedLog = 'info';

setLevel(level: LogLevel) {
setLevel(level: LogLevel | 'all') {
this.level = level;
}

private shouldLog(messageLevel: LogLevel): boolean {
const levels: LogLevel[] = ['error', 'warn', 'info', 'silent'];
const levels: ExtendedLog[] = ['error', 'warn', 'info', 'all'];
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Will this log all there types of log 'error', 'warn', 'info' when logLevel is set to info ?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I didnt get your question

return levels.indexOf(this.level) >= levels.indexOf(messageLevel);
}

private log(level: LogLevel, message: string, ...args: any[]) {
if (this.shouldLog(level) && this.level !== 'silent') {
if (this.shouldLog(level)) {
const logFunction = this.getLogFunction(level);
console.log('current level', this.level);
logFunction(`[${level.toUpperCase()}]`, message, ...args);
Expand All @@ -31,7 +32,11 @@ class SimpleLogger {
case 'info':
return console.info;
default:
return () => {}; // No-op for 'silent'
return (message: string, ...optionalParams: any[]) => {
console.info('info',message, ...optionalParams);
console.warn('warn',message, ...optionalParams);
console.error('error',message, ...optionalParams);
};
}
}

Expand All @@ -52,7 +57,7 @@ class SimpleLogger {
const logger = new SimpleLogger();

// Function to set the log level
export function setLogLevel(level: LogLevel) {
export function setLogLevel(level: LogLevel | 'all') {
logger.setLevel(level);
}

Expand Down
10 changes: 5 additions & 5 deletions src/utils/proofUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,13 +61,13 @@ export async function getShortenedUrl(url: string): Promise<string> {
})
const res = await response.json()
if (!response.ok) {
logger.info(`Failed to shorten URL: ${url}, Response: ${JSON.stringify(res)}`);
logger.error(`Failed to shorten URL: ${url}, Response: ${JSON.stringify(res)}`);
return url;
}
const shortenedVerificationUrl = res.result.shortUrl
return shortenedVerificationUrl
} catch (err) {
logger.info(`Error shortening URL: ${url}, Error: ${err}`);
logger.error(`Error shortening URL: ${url}, Error: ${err}`);
return url
}
}
Expand All @@ -87,7 +87,7 @@ export async function createLinkWithTemplateData(templateData: TemplateData): Pr
const shortenedLink = await getShortenedUrl(fullLink)
return shortenedLink;
} catch (err) {
logger.info(`Error creating link for sessionId: ${templateData.sessionId}, Error: ${err}`);
logger.error(`Error creating link for sessionId: ${templateData.sessionId}, Error: ${err}`);
return fullLink;
}
}
Expand All @@ -107,7 +107,7 @@ export async function getWitnessesForClaim(
): Promise<string[]> {
const beacon = makeBeacon()
if (!beacon) {
logger.info('No beacon available for getting witnesses');
logger.warn('No beacon available for getting witnesses');
throw new Error('No beacon available');
}
const state = await beacon.getState(epoch)
Expand Down Expand Up @@ -153,7 +153,7 @@ export function assertValidSignedClaim(

if (witnessesNotSeen.size > 0) {
const missingWitnesses = Array.from(witnessesNotSeen).join(', ');
logger.info(`Claim validation failed. Missing signatures from: ${missingWitnesses}`);
logger.warn(`Claim validation failed. Missing signatures from: ${missingWitnesses}`);
throw new ProofNotVerifiedError(
`Missing signatures from ${missingWitnesses}`
)
Expand Down
14 changes: 7 additions & 7 deletions src/utils/sessionUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,13 +35,13 @@ export async function initSession(
const res = await response.json();

if (!response.ok) {
logger.info(`Session initialization failed: ${res.message || 'Unknown error'}`);
throw new InitSessionError(res.message || `Error initializing session with providerId: ${providerId}`);
logger.error(`Session initialization failed: ${res.message || 'Unknown error'}`);
throw new InitSessionError();
}

return res as InitSessionResponse;
} catch (err) {
logger.info(`Failed to initialize session for providerId: ${providerId}, appId: ${appId}`, err);
logger.error(`Failed to initialize session for providerId: ${providerId}, appId: ${appId}`);
throw err;
}
}
Expand Down Expand Up @@ -71,15 +71,15 @@ export async function updateSession(sessionId: string, status: SessionStatus) {

if (!response.ok) {
const errorMessage = `Error updating session with sessionId: ${sessionId}. Status Code: ${response.status}`;
logger.info(errorMessage, res);
logger.error(errorMessage, res);
throw new UpdateSessionError(errorMessage);
}

logger.info(`Session status updated successfully for sessionId: ${sessionId}`);
return res;
} catch (err) {
const errorMessage = `Failed to update session with sessionId: ${sessionId}`;
logger.info(errorMessage, err);
logger.error(errorMessage, err);
throw new UpdateSessionError(`Error updating session with sessionId: ${sessionId}`);
}
}
Expand All @@ -106,14 +106,14 @@ export async function fetchStatusUrl(sessionId: string): Promise<StatusUrlRespon

if (!response.ok) {
const errorMessage = `Error fetching status URL for sessionId: ${sessionId}. Status Code: ${response.status}`;
logger.info(errorMessage, res);
logger.error(errorMessage, res);
throw new StatusUrlError(errorMessage);
}

return res as StatusUrlResponse;
} catch (err) {
const errorMessage = `Failed to fetch status URL for sessionId: ${sessionId}`;
logger.info(errorMessage, err);
logger.error(errorMessage, err);
throw new StatusUrlError(`Error fetching status URL for sessionId: ${sessionId}`);
}
}
Expand Down
9 changes: 8 additions & 1 deletion src/utils/types.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import type { Context, Proof, ProviderClaimData, ProviderData, RequestedProof } from './interfaces';
import type { ParsedQs } from 'qs';
import { LogLevel } from './logger';


// Claim-related types
export type ClaimID = ProviderClaimData['identifier'];
Expand All @@ -10,6 +12,8 @@ export type AnyClaimInfo = ClaimInfo | { identifier: ClaimID };

export type CompleteClaimData = Pick<ProviderClaimData, 'owner' | 'timestampS' | 'epoch'> & AnyClaimInfo;



export type SignedClaim = {
claim: CompleteClaimData;
signatures: Uint8Array[];
Expand All @@ -29,9 +33,12 @@ export type StartSessionParams = {
export type OnSuccess = (proof?: Proof | string) => void;
export type OnError = (error: Error) => void;



export type ProofRequestOptions = {
log?: boolean;
acceptAiProviders?: boolean;
logLevel?: LogLevel;
acceptAiProviders?: boolean;
};

// Session and response types
Expand Down
Loading