From bc496d09504bb5c7a6248bdedfbf0f953fd3a061 Mon Sep 17 00:00:00 2001 From: Girish bari Date: Wed, 16 Oct 2024 13:07:04 +0530 Subject: [PATCH 1/4] Improving logging message types and error messages --- src/Reclaim.ts | 54 ++++++++++++++++++------------------ src/utils/proofUtils.ts | 10 +++---- src/utils/sessionUtils.ts | 12 ++++---- src/utils/validationUtils.ts | 28 +++++++++---------- 4 files changed, 52 insertions(+), 52 deletions(-) diff --git a/src/Reclaim.ts b/src/Reclaim.ts index accb406..55a1ce1 100644 --- a/src/Reclaim.ts +++ b/src/Reclaim.ts @@ -1,5 +1,5 @@ import type { Proof, RequestedProof, Context, ProviderData } from './utils/interfaces' -import { getIdentifierFromClaimInfo } from './witness' +import { getIdentifierFromClaimerror } from './witness' import type { SignedClaim, ProofRequestOptions, @@ -40,7 +40,7 @@ const logger = loggerModule.logger export async function verifyProof(proof: Proof): Promise { if (!proof.signatures.length) { - throw new SignatureNotFoundError('No signatures') + throw new SignatureNotFoundError('No signatures, proof object is undefined') } try { @@ -55,8 +55,8 @@ export async function verifyProof(proof: Proof): Promise { proof.claimData.timestampS ) } - // then hash the claim info with the encoded ctx to get the identifier - const calculatedIdentifier = getIdentifierFromClaimInfo({ + // then hash the claim error with the encoded ctx to get the identifier + const calculatedIdentifier = getIdentifierFromClaimerror({ parameters: JSON.parse( canonicalize(proof.claimData.parameters) as string ), @@ -66,7 +66,7 @@ export async function verifyProof(proof: Proof): Promise { 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 = { @@ -80,20 +80,20 @@ export async function verifyProof(proof: Proof): Promise { 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 } return true } -export function transformForOnchain(proof: Proof): { claimInfo: any, signedClaim: any } { - const claimInfoBuilder = new Map([ +export function transformForOnchain(proof: Proof): { claimerror: any, signedClaim: any } { + const claimerrorBuilder = new Map([ ['context', proof.claimData.context], ['parameters', proof.claimData.parameters], ['provider', proof.claimData.provider], ]); - const claimInfo = Object.fromEntries(claimInfoBuilder); + const claimerror = Object.fromEntries(claimerrorBuilder); const claimBuilder = new Map([ ['epoch', proof.claimData.epoch], ['identifier', proof.claimData.identifier], @@ -104,7 +104,7 @@ export function transformForOnchain(proof: Proof): { claimInfo: any, signedClaim claim: Object.fromEntries(claimBuilder), signatures: proof.signatures, }; - return { claimInfo, signedClaim }; + return { claimerror, signedClaim }; } export class ReclaimProofRequest { @@ -128,12 +128,12 @@ export class ReclaimProofRequest { this.applicationId = applicationId; this.sessionId = ""; if (options?.log) { - loggerModule.setLogLevel('info'); + loggerModule.setLogLevel('error'); } else { loggerModule.setLogLevel('silent'); } this.options = options; - logger.info(`Initializing client with applicationId: ${this.applicationId}`); + logger.error(`Initializing client with applicationId: ${this.applicationId}`); } // Static initialization methods @@ -172,7 +172,7 @@ 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); throw new InitError('Failed to initialize ReclaimProofRequest', error as Error) } } @@ -225,7 +225,7 @@ export class ReclaimProofRequest { 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'); } } @@ -249,7 +249,7 @@ export class ReclaimProofRequest { ], 'addContext'); this.context = { contextAddress: address, contextMessage: message }; } catch (error) { - logger.info("Error adding context", error) + logger.error("Error adding context", error) throw new AddContextError("Error adding context", error as Error) } } @@ -276,7 +276,7 @@ export class ReclaimProofRequest { } this.requestedProof.parameters = { ...requestedProof.parameters, ...params } } catch (error) { - logger.info('Error Setting Params:', error); + logger.error('Error Setting Params:', error); throw new SetParamsError("Error setting params", error as Error) } } @@ -287,7 +287,7 @@ 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) throw new GetAppCallbackUrlError("Error getting app callback url", error as Error) } } @@ -297,7 +297,7 @@ 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) throw new GetStatusUrlError("Error fetching status url", error as Error) } } @@ -309,7 +309,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) } } @@ -328,7 +328,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}`) } } @@ -338,7 +338,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); } } @@ -361,7 +361,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) } } @@ -390,7 +390,7 @@ export class ReclaimProofRequest { } async getRequestUrl(): Promise { - logger.info('Creating Request Url') + logger.error('Creating Request Url') if (!this.signature) { throw new SignatureNotFoundError('Signature is not set.') } @@ -417,7 +417,7 @@ 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 } } @@ -425,7 +425,7 @@ export class ReclaimProofRequest { async startSession({ onSuccess, onError }: StartSessionParams): Promise { if (!this.sessionId) { const message = "Session can't be started due to undefined value of statusUrl and sessionId" - logger.info(message) + logger.warn(message) throw new SessionNotStartedError(message) } @@ -441,8 +441,8 @@ export class ReclaimProofRequest { const proof = statusUrlResponse.session.proofs[0] const verified = await verifyProof(proof) if (!verified) { - logger.info(`Proof not verified: ${proof}`) - throw new ProofNotVerifiedError() + logger.error(`Proof not verified: ${proof}`) + throw new ProofNotVerifiedError(`${proof} is not verified`) } if (onSuccess) { onSuccess(proof) diff --git a/src/utils/proofUtils.ts b/src/utils/proofUtils.ts index 83e4fe9..601cc9a 100644 --- a/src/utils/proofUtils.ts +++ b/src/utils/proofUtils.ts @@ -61,13 +61,13 @@ export async function getShortenedUrl(url: string): Promise { }) 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 } } @@ -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; } } @@ -107,7 +107,7 @@ export async function getWitnessesForClaim( ): Promise { 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) @@ -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}` ) diff --git a/src/utils/sessionUtils.ts b/src/utils/sessionUtils.ts index 37edcb1..4ea718a 100644 --- a/src/utils/sessionUtils.ts +++ b/src/utils/sessionUtils.ts @@ -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'}`); + logger.error(`Session initialization failed: ${res.message || 'Unknown error'}`); throw new InitSessionError(res.message || `Error initializing session with providerId: ${providerId}`); } 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}`, err); throw err; } } @@ -71,7 +71,7 @@ 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); } @@ -79,7 +79,7 @@ export async function updateSession(sessionId: string, status: SessionStatus) { 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}`); } } @@ -106,14 +106,14 @@ export async function fetchStatusUrl(sessionId: string): Promise { if (input == null) { - logger.info(`Validation failed: ${paramName} in ${functionName} is null or undefined`); + logger.warn(`Validation failed: ${paramName} in ${functionName} is null or undefined`); throw new InvalidParamError(`${paramName} passed to ${functionName} must not be null or undefined.`); } if (isString && typeof input !== 'string') { - logger.info(`Validation failed: ${paramName} in ${functionName} is not a string`); + logger.warn(`Validation failed: ${paramName} in ${functionName} is not a string`); throw new InvalidParamError(`${paramName} passed to ${functionName} must be a string.`); } if (isString && input.trim() === '') { - logger.info(`Validation failed: ${paramName} in ${functionName} is an empty string`); + logger.warn(`Validation failed: ${paramName} in ${functionName} is an empty string`); throw new InvalidParamError(`${paramName} passed to ${functionName} must not be an empty string.`); } }); @@ -39,7 +39,7 @@ export function validateURL(url: string, functionName: string): void { try { new URL(url); } catch (e) { - logger.info(`URL validation failed for ${url} in ${functionName}: ${(e as Error).message}`); + logger.error(`URL validation failed for ${url} in ${functionName}: ${(e as Error).message}`); throw new InvalidParamError(`Invalid URL format ${url} passed to ${functionName}.`, e as Error); } } @@ -58,8 +58,8 @@ export function validateSignature(providerId: string, signature: string, applica const message = canonicalize({ providerId, timestamp }); if (!message) { - logger.info('Failed to canonicalize message for signature validation'); - throw new Error('Failed to canonicalize message'); + logger.warn('Failed to canonicalize message for signature validation'); + throw new Error(`Failed to canonicalize message because message is ${message}`); } const messageHash = ethers.keccak256(new TextEncoder().encode(message)); let appId = ethers.verifyMessage( @@ -68,13 +68,13 @@ export function validateSignature(providerId: string, signature: string, applica ).toLowerCase(); if (ethers.getAddress(appId) !== ethers.getAddress(applicationId)) { - logger.info(`Signature validation failed: Mismatch between derived appId (${appId}) and provided applicationId (${applicationId})`); + logger.warn(`Signature validation failed: Mismatch between derived appId (${appId}) and provided applicationId (${applicationId})`); throw new InvalidSignatureError(`Signature does not match the application id: ${appId}`); } logger.info(`Signature validated successfully for applicationId: ${applicationId}`); } catch (err) { - logger.info(`Signature validation failed: ${(err as Error).message}`); + logger.error(`Signature validation failed: ${(err as Error).message}`); if (err instanceof InvalidSignatureError) { throw err; } @@ -90,12 +90,12 @@ export function validateSignature(providerId: string, signature: string, applica */ export function validateRequestedProof(requestedProof: RequestedProof): void { if (!requestedProof.url) { - logger.info(`Requested proof validation failed: Provided url in requested proof is not valid`); + logger.warn(`Requested proof validation failed: Provided url in requested proof is not valid`); throw new InvalidParamError(`The provided url in requested proof is not valid`); } if (requestedProof.parameters && typeof requestedProof.parameters !== 'object') { - logger.info(`Requested proof validation failed: Provided parameters in requested proof is not valid`); + logger.warn(`Requested proof validation failed: Provided parameters in requested proof is not valid`); throw new InvalidParamError(`The provided parameters in requested proof is not valid`); } } @@ -107,12 +107,12 @@ export function validateRequestedProof(requestedProof: RequestedProof): void { */ export function validateContext(context: Context): void { if (!context.contextAddress) { - logger.info(`Context validation failed: Provided context address in context is not valid`); + logger.warn(`Context validation failed: Provided context address in context is not valid`); throw new InvalidParamError(`The provided context address in context is not valid`); } if (!context.contextMessage) { - logger.info(`Context validation failed: Provided context message in context is not valid`); + logger.warn(`Context validation failed: Provided context message in context is not valid`); throw new InvalidParamError(`The provided context message in context is not valid`); } @@ -129,12 +129,12 @@ export function validateContext(context: Context): void { */ export function validateOptions(options: ProofRequestOptions): void { if (options.acceptAiProviders && typeof options.acceptAiProviders !== 'boolean') { - logger.info(`Options validation failed: Provided acceptAiProviders in options is not valid`); + logger.warn(`Options validation failed: Provided acceptAiProviders in options is not valid`); throw new InvalidParamError(`The provided acceptAiProviders in options is not valid`); } if (options.log && typeof options.log !== 'boolean') { - logger.info(`Options validation failed: Provided log in options is not valid`); + logger.warn(`Options validation failed: Provided log in options is not valid`); throw new InvalidParamError(`The provided log in options is not valid`); } } From 9f8a4e13bd60f32380a7aa2bcb83fb7a3ec4f197 Mon Sep 17 00:00:00 2001 From: Girish bari Date: Tue, 22 Oct 2024 19:08:13 +0530 Subject: [PATCH 2/4] refator import to getIdentifierFromClaimInfo from getIdentifierFromClaimerror --- src/Reclaim.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Reclaim.ts b/src/Reclaim.ts index 55a1ce1..7f63ba7 100644 --- a/src/Reclaim.ts +++ b/src/Reclaim.ts @@ -1,5 +1,5 @@ import type { Proof, RequestedProof, Context, ProviderData } from './utils/interfaces' -import { getIdentifierFromClaimerror } from './witness' +import { getIdentifierFromClaimInfo } from './witness' import type { SignedClaim, ProofRequestOptions, @@ -56,7 +56,7 @@ export async function verifyProof(proof: Proof): Promise { ) } // then hash the claim error with the encoded ctx to get the identifier - const calculatedIdentifier = getIdentifierFromClaimerror({ + const calculatedIdentifier = getIdentifierFromClaimInfo({ parameters: JSON.parse( canonicalize(proof.claimData.parameters) as string ), From 69ceaccf384763181f972c971d4873bbc35b23c6 Mon Sep 17 00:00:00 2001 From: Girish bari Date: Fri, 1 Nov 2024 10:26:53 +0530 Subject: [PATCH 3/4] Added required changes for log meesages --- src/Reclaim.ts | 22 ++++++++++++++++------ src/utils/constants.ts | 3 ++- src/utils/logger.ts | 19 ++++++++++++------- src/utils/sessionUtils.ts | 4 ++-- src/utils/types.ts | 9 ++++++++- src/utils/validationUtils.ts | 19 +++++++++++++++++-- 6 files changed, 57 insertions(+), 19 deletions(-) diff --git a/src/Reclaim.ts b/src/Reclaim.ts index 7f63ba7..c549245 100644 --- a/src/Reclaim.ts +++ b/src/Reclaim.ts @@ -127,13 +127,13 @@ export class ReclaimProofRequest { this.timeStamp = Date.now().toString(); this.applicationId = applicationId; this.sessionId = ""; - if (options?.log) { - loggerModule.setLogLevel('error'); + if (options?.log && options?.logLevel) { + loggerModule.setLogLevel(options?.logLevel!); } else { - loggerModule.setLogLevel('silent'); + loggerModule.setLogLevel('all') } this.options = options; - logger.error(`Initializing client with applicationId: ${this.applicationId}`); + logger.info(`Initializing client with applicationId: ${this.applicationId}`); } // Static initialization methods @@ -154,8 +154,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') + } } } @@ -173,6 +178,7 @@ export class ReclaimProofRequest { return proofRequestInstance } catch (error) { logger.error('Failed to initialize ReclaimProofRequest', error as Error); + logger.info("Try changing values of applicationId, applicationSecret, ProviderId, Option's Parameters") throw new InitError('Failed to initialize ReclaimProofRequest', error as Error) } } @@ -250,6 +256,7 @@ export class ReclaimProofRequest { this.context = { contextAddress: address, contextMessage: message }; } catch (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)`) throw new AddContextError("Error adding context", error as Error) } } @@ -277,6 +284,7 @@ export class ReclaimProofRequest { this.requestedProof.parameters = { ...requestedProof.parameters, ...params } } catch (error) { logger.error('Error Setting Params:', error); + logger.info(`Arguments passed in setParams must be object which contains key => value pairs`) throw new SetParamsError("Error setting params", error as Error) } } @@ -288,6 +296,7 @@ export class ReclaimProofRequest { return this.appCallbackUrl || `${constants.DEFAULT_RECLAIM_CALLBACK_URL}${this.sessionId}` } catch (error) { logger.error("Error getting app callback url", error) + logger.info(`Make sure to pass URL and as a string`) throw new GetAppCallbackUrlError("Error getting app callback url", error as Error) } } @@ -298,6 +307,7 @@ export class ReclaimProofRequest { return `${constants.DEFAULT_RECLAIM_STATUS_URL}${this.sessionId}` } catch (error) { logger.error("Error fetching Status Url", error) + logger.info(`Make sure to pass URL and as a string`) throw new GetStatusUrlError("Error fetching status url", error as Error) } } @@ -390,7 +400,7 @@ export class ReclaimProofRequest { } async getRequestUrl(): Promise { - logger.error('Creating Request Url') + logger.info('Creating Request Url') if (!this.signature) { throw new SignatureNotFoundError('Signature is not set.') } diff --git a/src/utils/constants.ts b/src/utils/constants.ts index a0aa03c..aa92c27 100644 --- a/src/utils/constants.ts +++ b/src/utils/constants.ts @@ -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=', + }; diff --git a/src/utils/logger.ts b/src/utils/logger.ts index da78917..f5dd477 100644 --- a/src/utils/logger.ts +++ b/src/utils/logger.ts @@ -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']; 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); @@ -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); + }; } } @@ -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); } diff --git a/src/utils/sessionUtils.ts b/src/utils/sessionUtils.ts index 4ea718a..9b70cf4 100644 --- a/src/utils/sessionUtils.ts +++ b/src/utils/sessionUtils.ts @@ -36,12 +36,12 @@ export async function initSession( if (!response.ok) { logger.error(`Session initialization failed: ${res.message || 'Unknown error'}`); - throw new InitSessionError(res.message || `Error initializing session with providerId: ${providerId}`); + throw new InitSessionError(); } return res as InitSessionResponse; } catch (err) { - logger.error(`Failed to initialize session for providerId: ${providerId}, appId: ${appId}`, err); + logger.error(`Failed to initialize session for providerId: ${providerId}, appId: ${appId}`); throw err; } } diff --git a/src/utils/types.ts b/src/utils/types.ts index 01a2121..0ce3c16 100644 --- a/src/utils/types.ts +++ b/src/utils/types.ts @@ -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']; @@ -10,6 +12,8 @@ export type AnyClaimInfo = ClaimInfo | { identifier: ClaimID }; export type CompleteClaimData = Pick & AnyClaimInfo; + + export type SignedClaim = { claim: CompleteClaimData; signatures: Uint8Array[]; @@ -29,9 +33,12 @@ export type StartSessionParams = { export type OnSuccess = (proof: Proof) => void; export type OnError = (error: Error) => void; + + export type ProofRequestOptions = { log?: boolean; - acceptAiProviders?: boolean; + logLevel?: LogLevel; + acceptAiProviders?: boolean; }; // Session and response types diff --git a/src/utils/validationUtils.ts b/src/utils/validationUtils.ts index f35c6b6..956bfd7 100644 --- a/src/utils/validationUtils.ts +++ b/src/utils/validationUtils.ts @@ -2,10 +2,12 @@ import { ethers } from "ethers"; import { InvalidParamError, InvalidSignatureError, ProviderNotFoundError } from "./errors"; import canonicalize from 'canonicalize' import { Context, RequestedProof } from "./interfaces"; -import loggerModule from './logger'; +import loggerModule, {LogLevel} from './logger'; import { ProofRequestOptions } from "./types"; const logger = loggerModule.logger; +const REFERENCE_FOR_DASHBOARD = "https://dev.reclaimprotocol.org/dashboard" + /** * Validates function parameters based on specified criteria * @param params - An array of objects containing input, paramName, and optional isString flag @@ -15,9 +17,12 @@ const logger = loggerModule.logger; export function validateFunctionParams(params: { input: any, paramName: string, isString?: boolean }[], functionName: string): void { params.forEach(({ input, paramName, isString }) => { if (input == null) { - logger.warn(`Validation failed: ${paramName} in ${functionName} is null or undefined`); + logger.warn(`Validation failed: Expected ${paramName} in ${functionName} is null or undefined`); throw new InvalidParamError(`${paramName} passed to ${functionName} must not be null or undefined.`); } + if(paramName === 'acceptAiProvider' || paramName === 'log' || paramName || paramName === 'logLevel') { + validateOptions(input) + } if (isString && typeof input !== 'string') { logger.warn(`Validation failed: ${paramName} in ${functionName} is not a string`); throw new InvalidParamError(`${paramName} passed to ${functionName} must be a string.`); @@ -40,6 +45,7 @@ export function validateURL(url: string, functionName: string): void { new URL(url); } catch (e) { logger.error(`URL validation failed for ${url} in ${functionName}: ${(e as Error).message}`); + logger.info('Make sure to pass URL as string') throw new InvalidParamError(`Invalid URL format ${url} passed to ${functionName}.`, e as Error); } } @@ -96,6 +102,7 @@ export function validateRequestedProof(requestedProof: RequestedProof): void { if (requestedProof.parameters && typeof requestedProof.parameters !== 'object') { logger.warn(`Requested proof validation failed: Provided parameters in requested proof is not valid`); + logger.info(`Requested Proof's parameters must be an Object`) throw new InvalidParamError(`The provided parameters in requested proof is not valid`); } } @@ -130,11 +137,19 @@ export function validateContext(context: Context): void { export function validateOptions(options: ProofRequestOptions): void { if (options.acceptAiProviders && typeof options.acceptAiProviders !== 'boolean') { logger.warn(`Options validation failed: Provided acceptAiProviders in options is not valid`); + logger.info(`acceptAiProviders option must be boolean value`) throw new InvalidParamError(`The provided acceptAiProviders in options is not valid`); } if (options.log && typeof options.log !== 'boolean') { logger.warn(`Options validation failed: Provided log in options is not valid`); + logger.info(`log option must be boolean value`) + throw new InvalidParamError(`The provided log in options is not valid`); + } + + if (options.logLevel && !['info', 'warn', 'error'].includes(options.logLevel)) { + logger.warn(`Options validation failed: Provided loglevel in options is not valid`); + logger.info(`Available options for log is 'info' , 'warn' , 'error' `) throw new InvalidParamError(`The provided log in options is not valid`); } } From 5e89b4d566e379ee565e0c75afc4f24b3bcd2187 Mon Sep 17 00:00:00 2001 From: Girish bari Date: Fri, 8 Nov 2024 20:54:23 +0530 Subject: [PATCH 4/4] remove unnecessary changes --- src/Reclaim.ts | 19 ++++++++++--------- src/utils/validationUtils.ts | 5 ++--- 2 files changed, 12 insertions(+), 12 deletions(-) diff --git a/src/Reclaim.ts b/src/Reclaim.ts index 775abe4..f324d52 100644 --- a/src/Reclaim.ts +++ b/src/Reclaim.ts @@ -59,7 +59,7 @@ export async function verifyProof(proof: Proof): Promise { proof.claimData.timestampS ) } - // then hash the claim error with the encoded ctx to get the identifier + // then hash the claim info with the encoded ctx to get the identifier const calculatedIdentifier = getIdentifierFromClaimInfo({ parameters: JSON.parse( canonicalize(proof.claimData.parameters) as string @@ -91,13 +91,13 @@ export async function verifyProof(proof: Proof): Promise { return true } -export function transformForOnchain(proof: Proof): { claimerror: any, signedClaim: any } { - const claimerrorBuilder = new Map([ +export function transformForOnchain(proof: Proof): { claimInfo: any, signedClaim: any } { + const claimInfoBuilder = new Map([ ['context', proof.claimData.context], ['parameters', proof.claimData.parameters], ['provider', proof.claimData.provider], ]); - const claimerror = Object.fromEntries(claimerrorBuilder); + const claimInfo = Object.fromEntries(claimInfoBuilder); const claimBuilder = new Map([ ['epoch', proof.claimData.epoch], ['identifier', proof.claimData.identifier], @@ -108,9 +108,10 @@ export function transformForOnchain(proof: Proof): { claimerror: any, signedClai claim: Object.fromEntries(claimBuilder), signatures: proof.signatures, }; - return { claimerror, signedClaim }; + return { claimInfo, signedClaim }; } + export class ReclaimProofRequest { // Private class properties private applicationId: string; @@ -185,7 +186,7 @@ export class ReclaimProofRequest { return proofRequestInstance } catch (error) { logger.error('Failed to initialize ReclaimProofRequest', error as Error); - logger.info("Try changing values of applicationId, applicationSecret, ProviderId, Option's Parameters") + logger.warn("Try changing values of applicationId, applicationSecret, ProviderId, Option's Parameters") throw new InitError('Failed to initialize ReclaimProofRequest', error as Error) } } @@ -293,7 +294,7 @@ export class ReclaimProofRequest { this.requestedProof.parameters = { ...requestedProof.parameters, ...params } } catch (error) { logger.error('Error Setting Params:', error); - logger.info(`Arguments passed in setParams must be object which contains key => value pairs`) + logger.warn(`Arguments passed in setParams must be object which contains key => value pairs`) throw new SetParamsError("Error setting params", error as Error) } } @@ -305,7 +306,7 @@ export class ReclaimProofRequest { return this.appCallbackUrl || `${constants.DEFAULT_RECLAIM_CALLBACK_URL}${this.sessionId}` } catch (error) { logger.error("Error getting app callback url", error) - logger.info(`Make sure to pass URL and as a string`) + logger.warn(`Make sure to pass URL and as a string`) throw new GetAppCallbackUrlError("Error getting app callback url", error as Error) } } @@ -316,7 +317,7 @@ export class ReclaimProofRequest { return `${constants.DEFAULT_RECLAIM_STATUS_URL}${this.sessionId}` } catch (error) { logger.error("Error fetching Status Url", error) - logger.info(`Make sure to pass URL and as a string`) + logger.warn(`Make sure to pass URL and as a string`) throw new GetStatusUrlError("Error fetching status url", error as Error) } } diff --git a/src/utils/validationUtils.ts b/src/utils/validationUtils.ts index 956bfd7..2805834 100644 --- a/src/utils/validationUtils.ts +++ b/src/utils/validationUtils.ts @@ -6,7 +6,6 @@ import loggerModule, {LogLevel} from './logger'; import { ProofRequestOptions } from "./types"; const logger = loggerModule.logger; -const REFERENCE_FOR_DASHBOARD = "https://dev.reclaimprotocol.org/dashboard" /** * Validates function parameters based on specified criteria @@ -45,7 +44,7 @@ export function validateURL(url: string, functionName: string): void { new URL(url); } catch (e) { logger.error(`URL validation failed for ${url} in ${functionName}: ${(e as Error).message}`); - logger.info('Make sure to pass URL as string') + logger.warn('Make sure to pass URL as string') throw new InvalidParamError(`Invalid URL format ${url} passed to ${functionName}.`, e as Error); } } @@ -102,7 +101,7 @@ export function validateRequestedProof(requestedProof: RequestedProof): void { if (requestedProof.parameters && typeof requestedProof.parameters !== 'object') { logger.warn(`Requested proof validation failed: Provided parameters in requested proof is not valid`); - logger.info(`Requested Proof's parameters must be an Object`) + logger.warn(`Requested Proof's parameters must be an Object`) throw new InvalidParamError(`The provided parameters in requested proof is not valid`); } }